<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
    <NODE name="GETENV" label="TRAITEMENT ENVIRONNEMENT [FINESS] [FINESS_TEXTE] DEPUIS [CONSO_PMSI_ANNEE_DEBUT]">
        <NODE name="INIT" label="Initialisations">
            <sqlcmd><![CDATA[

                -- Enregistrement environnement --
                INSERT INTO base.t_finess (code, texte, texte_court) 
                    SELECT '[FINESS]', '[FINESS]', '[FINESS]' 
                    WHERE '[FINESS]' NOT IN (SELECT code FROM base.t_finess)
                ;

                SELECT base.cti_copy_table
                    (
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]',
                    'SELECT *
                     FROM base.t_finess
                     WHERE code = ''[FINESS]''',
                    'temp e_finess'
                    )
                ;
                
                UPDATE base.t_finess
                SET 
                    texte = e_finess.texte,
                    texte_court = e_finess.texte_court,
                    secondaire = '1'
                FROM e_finess
                WHERE 1=1
                    AND t_finess.code = e_finess.code
                    AND t_finess.code <> '[FINESS_PRINCIPAL]'
                    AND (1!=1
                        OR t_finess.texte IS DISTINCT FROM e_finess.texte
                        OR t_finess.texte_court IS DISTINCT FROM e_finess.texte_court
                        OR t_finess.secondaire IS DISTINCT FROM '1'
                        )
                ;


                SELECT base.cti_copy_table
                    (
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]',
                    'SELECT code
                     FROM base.t_territoires_sante
                     WHERE oid  = ( SELECT territoire_sante_id
                                    FROM base.t_finess
                                    WHERE code = ''[FINESS]'')',
                    'temp e_ter_code'
                    )
                ;

		        with e_territoire_sante_id as 
		            (
                        SELECT oid as terr_sant_id 
		                FROM base.t_territoires_sante
		                JOIN e_ter_code ON t_territoires_sante.code = e_ter_code.code
		            )

                UPDATE base.t_finess
                SET 
                    territoire_sante_id = e_territoire_sante_id.terr_sant_id
                FROM e_finess
                JOIN e_territoire_sante_id ON 1=1
                WHERE 1=1
                    AND t_finess.code = e_finess.code
                    AND (1!=1
                        OR t_finess.territoire_sante_id IS DISTINCT FROM e_territoire_sante_id.terr_sant_id
                        )
                ;

                INSERT INTO base.t_finess_database (finess_id, dbname, dbport, dbhost)
                    SELECT 
                        oid, '[DBNAME]', '[DBPORT]', '[DBHOST]'
                    FROM base.t_finess
                    WHERE 1=1
                        AND code = '[FINESS]'
                        AND oid NOT IN (SELECT finess_id FROM base.t_finess_database)
                ;
                    
                UPDATE base.t_finess_database
                SET
                    dbhost = '[DBHOST]',
                    dbname = '[DBNAME]',
                    dbport = '[DBPORT]'
                FROM base.t_finess
                WHERE 1=1
                    AND finess_id = t_finess.oid
                    AND t_finess.code = '[FINESS]'
                    AND (1!=1
                        OR dbhost IS DISTINCT FROM '[DBHOST]'
                        OR dbname IS DISTINCT FROM '[DBNAME]'
                        OR dbport IS DISTINCT FROM '[DBPORT]'
                        )
                ;

                -- Détection modifications --
                SELECT base.cti_copy_table
                    (
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]',
                    '
                       SELECT 
                        p_rss.en_cours,
                        p_rss.mois_sortie, 
                        SUM(
                            1 +
                            COALESCE(p_rss.base_remboursement,0) + 
                            (COALESCE(p_rss.ca_ghs,0) + COALESCE(p_rss.ca_ghs_raac,0)) * 10 + 
                            COALESCE(p_rss.ca_exh,0) * 100 + 
                            COALESCE(p_rss.ca_exb,0) * 1000 + 
                            COALESCE(p_rss.t2a_facture,0) * 10000 + 
                            COALESCE(p_rss.dmi_facture,0) * 100000 + 
                            COALESCE(p_rss.phc_facture,0) * 1000000 +
                            COALESCE(p_rss.import_id,0) * 10000000 +
                            CASE WHEN p_rss.medecin_rss_id <> 0 THEN 100000000 ELSE 0 END +
                            base.cti_to_ascii(substr(t_prestations.code,1,3)) * 1000000000 +
                            COALESCE(p_rsf_detail.sejour_remboursable * GREATEST(p_rsf_detail.no_rum,1),0) * 10000000000 +
							COALESCE(base.cti_to_ascii(substr(t_actes.code, 1, 1) || substr(t_actes.code, 3, 1) || substr(t_actes.code, LENGTH(t_actes.code), 1)), 0) * 100000000000 +
							CASE WHEN COALESCE(p_rss_cardio.rss_id,0) <> 0 THEN 1000000000000 ELSE 0 END +
							CASE WHEN COALESCE(p_rss_cancero.rss_id,0) <> 0 THEN 10000000000000 ELSE 0 END 
                        ) AS key
                    FROM pmsi.p_rss
						LEFT JOIN pmsi.p_rsf_detail ON p_rss.oid = p_rsf_detail.rss_id AND
							COALESCE(fides_detail,0) = 0
						LEFT JOIN pmsi.p_rss_cardio ON p_rss.oid = p_rss_cardio.rss_id 
                        LEFT JOIN pmsi.p_rss_cancero ON p_rss.oid = p_rss_cancero.rss_id AND p_rss_cancero.cdc = ''2022'' 
						LEFT JOIN pmsi.p_rss_actes ON p_rss.oid = p_rss_actes.rss_id
                        LEFT JOIN pmsi.t_prestations ON t_prestations.oid = p_rss.prestation_principale_id
					    LEFT JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id    
					        WHERE 1=1
                        AND p_rss.etat <> ''S''
                        AND p_rss.no_rss <> 0
                        AND p_rss.mois_sortie >= [CONSO_PMSI_ANNEE_DEBUT]
                    GROUP BY 1,2',
                    'temp e_checksum'
                    )
                ;
                    
                    
                DROP TABLE IF EXISTS c_checksum
                ;
                
                CREATE TEMP TABLE c_checksum AS
                    SELECT 
                        p_rss.en_cours,
                        p_rss.mois_sortie, 
                        SUM(
                            1 +
                            COALESCE(p_rss.base_remboursement,0) + 
                            (COALESCE(p_rss.ca_ghs,0) + COALESCE(p_rss.ca_ghs_raac,0)) * 10 + 
                            COALESCE(p_rss.ca_exh,0) * 100 + 
                            COALESCE(p_rss.ca_exb,0) * 1000 + 
                            COALESCE(p_rss.t2a_facture,0) * 10000 + 
                            COALESCE(p_rss.dmi_facture,0) * 100000 + 
                            COALESCE(p_rss.phc_facture,0) * 1000000 +
                            COALESCE(p_rss.import_id,0) * 10000000 +
                            CASE WHEN p_rss.medecin_rss_id <> 0 THEN 100000000 ELSE 0 END +
                            base.cti_to_ascii(substr(t_prestations.code,1,3)) * 1000000000 +
                            COALESCE(p_rsf_detail.sejour_remboursable * GREATEST(p_rsf_detail.no_rum,1),0) * 10000000000 +
							COALESCE(base.cti_to_ascii(substr(t_actes.code, 1, 1) || substr(t_actes.code, 3, 1) || substr(t_actes.code, LENGTH(t_actes.code), 1)), 0) * 100000000000 +
							CASE WHEN COALESCE(p_rss_cardio.rss_id,0) <> 0 THEN 1000000000000 ELSE 0 END +
							CASE WHEN COALESCE(p_rss_cancero.rss_id,0) <> 0 THEN 10000000000000 ELSE 0 END 
                        ) AS key
                    FROM pmsi.p_rss
						LEFT JOIN pmsi.p_rsf_detail ON p_rss.oid = p_rsf_detail.rss_id AND
							COALESCE(fides_detail,0) = 0
						LEFT JOIN pmsi.p_rss_cardio ON p_rss.oid = p_rss_cardio.rss_id 
                        LEFT JOIN pmsi.p_rss_cancero ON p_rss.oid = p_rss_cancero.rss_id AND p_rss_cancero.cdc = '2022' 
						LEFT JOIN pmsi.p_rss_actes ON p_rss.oid = p_rss_actes.rss_id
                        LEFT JOIN pmsi.t_prestations ON t_prestations.oid = p_rss.prestation_principale_id
					    LEFT JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id     
                    WHERE 1=1
                        AND p_rss.finess = '[FINESS]'
                        AND p_rss.etat <> 'S'
                        AND p_rss.no_rss <> 0
                        AND p_rss.mois_sortie >= [CONSO_PMSI_ANNEE_DEBUT]
                    GROUP BY 1,2
                ;
                
                
                INSERT INTO e_checksum 
                SELECT c_checksum.en_cours, c_checksum.mois_sortie, NULL
                FROM c_checksum
                    LEFT JOIN e_checksum ON 1=1
                        AND e_checksum.mois_sortie = c_checksum.mois_sortie
                        AND e_checksum.en_cours = c_checksum.en_cours
                WHERE e_checksum.mois_sortie IS NULL
                ORDER BY c_checksum.mois_sortie;
                
                CTISELECT_PROPERTY_READ 'MOISMODIFIES', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                FROM e_checksum
                    LEFT JOIN c_checksum ON 1=1
                        AND e_checksum.mois_sortie = c_checksum.mois_sortie
                        AND e_checksum.en_cours = c_checksum.en_cours
                WHERE 1!=1
                    OR e_checksum.key IS DISTINCT FROM c_checksum.key
                    OR e_checksum.mois_sortie IN ([MOISFORCES])
                ;

                CTISELECT_PROPERTY_READ 'MOISMODIFIES_MAT2A', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                FROM e_checksum
                        LEFT JOIN c_checksum ON 1=1
                            AND e_checksum.mois_sortie = c_checksum.mois_sortie
                            AND e_checksum.en_cours = c_checksum.en_cours
                WHERE 1!=1
                    OR (1=1
                        AND e_checksum.en_cours = '0'
                        AND e_checksum.key IS DISTINCT FROM c_checksum.key
                        )
                    OR e_checksum.mois_sortie IN ([MOISFORCES])
                ;
                    
                CTISELECT_PROPERTY_READ 'MOISMODIFIES_ENCOURS', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                FROM e_checksum
                    LEFT JOIN c_checksum ON 1=1
                        AND e_checksum.mois_sortie = c_checksum.mois_sortie
                        AND e_checksum.en_cours = c_checksum.en_cours
                WHERE 1!=1
                    OR (1=1
                        AND e_checksum.en_cours <> '0'
                        AND e_checksum.key IS DISTINCT FROM c_checksum.key
                        )
                    OR e_checksum.mois_sortie IN ([MOISFORCES])
                ;
                
                echo Mois modifiés (mat2a) : [MOISMODIFIES_MAT2A], (fil de l'eau) : [MOISMODIFIES_ENCOURS];
        
            ]]></sqlcmd>
        </NODE>
        <NODE name="PARAM" label="Paramètres">
            <condition><![CDATA[
                "[MOISMODIFIES]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[

                -- CMD --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM pmsi.t_cmd WHERE oid <> 0', 'temp e_cmd')
                ;
                
                INSERT INTO pmsi.t_cmd (code, texte, texte_court)
                    SELECT code, texte, texte_court
                    FROM e_cmd
                    WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_cmd) AND oid <> 0
                ;

                DROP TABLE IF EXISTS c_cmd
                ;
                
                CREATE TEMP TABLE c_cmd AS
                    SELECT e_cmd.oid AS oid_source, coalesce(t_cmd.oid,0) AS oid
                    FROM e_cmd
                        LEFT JOIN pmsi.t_cmd ON e_cmd.code = t_cmd.code
                ;
                
                ALTER TABLE c_cmd ADD CONSTRAINT c_cmd_pkey PRIMARY KEY(oid_source)
                ;
                  
                  
                -- GHM5 --  
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte FROM pmsi.t_ghm5 WHERE oid <> 0', 'temp e_ghm5')
                ;
                
                INSERT INTO pmsi.t_ghm5 (code, texte)
                    SELECT code, texte FROM e_ghm5
                    WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_ghm5) AND oid <> 0
                ;

                DROP TABLE IF EXISTS c_ghm5
                ;
                
                CREATE TEMP TABLE c_ghm5 AS
                    SELECT e_ghm5.oid AS oid_source, coalesce(t_ghm5.oid,0) AS oid
                    FROM e_ghm5
                        LEFT JOIN pmsi.t_ghm5 ON e_ghm5.code = t_ghm5.code
                ;
                
                ALTER TABLE c_ghm5 ADD CONSTRAINT c_ghm5_pkey PRIMARY KEY(oid_source)
                ;
                
                
                -- Lignes OAP --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    'SELECT oid, code FROM pmsi.t_lignes_oap WHERE oid <> 0', 'temp e_lignes_oap')
                ;

                DROP TABLE IF EXISTS c_lignes_oap
                ;
                
                CREATE TEMP TABLE c_lignes_oap AS
                    SELECT e_lignes_oap.oid AS oid_source, coalesce(t_lignes_oap.oid,0) AS oid
                    FROM e_lignes_oap 
                        LEFT JOIN pmsi.t_lignes_oap ON e_lignes_oap.code = t_lignes_oap.code
                ;

                ALTER TABLE c_lignes_oap ADD CONSTRAINT c_lignes_oap_pkey PRIMARY KEY(oid_source)
                ;

                
                -- Groupes activité --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    'SELECT * FROM pmsi.t_groupes_activite WHERE oid <> 0', 'temp e_groupes_activite')
                ;

                DROP TABLE IF EXISTS c_groupes_activite
                ;
                
                CREATE TEMP TABLE c_groupes_activite AS
                    SELECT 
                        e_groupes_activite.oid AS oid_source,
                        coalesce(t_groupes_activite.oid,0) AS oid
                    FROM e_groupes_activite
                        LEFT JOIN pmsi.t_groupes_activite ON e_groupes_activite.code = t_groupes_activite.code
                ;

                ALTER TABLE c_groupes_activite ADD CONSTRAINT c_groupes_activite_pkey PRIMARY KEY(oid_source)
                ;
                
                
                -- GHM --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT * FROM pmsi.t_ghm WHERE oid <> 0', 'temp e_ghm')
                ;
                
                INSERT INTO pmsi.t_ghm (
                    code,
                    texte,
                    mco,
                    aso,
                    severite,
                    cmd_id,
                    groupe_activite_id,
                    ghm5_id,
                    ligne_oap_id
                    )
                    SELECT 
                        code,
                        texte,
                        mco,
                        aso,
                        severite,
                        COALESCE(c_cmd.oid,0) AS cmd_id,
                        COALESCE(c_groupes_activite.oid,0) AS groupe_activite_id,
                        COALESCE(c_ghm5.oid,0) AS ghm5_id,
                        COALESCE(c_lignes_oap.oid,0) AS ligne_oap_id
                    FROM e_ghm
                        LEFT JOIN c_cmd ON cmd_id = c_cmd.oid_source
                        LEFT JOIN c_groupes_activite ON groupe_activite_id = c_groupes_activite.oid_source
                        LEFT JOIN c_ghm5 ON ghm5_id = c_ghm5.oid_source
                        LEFT JOIN c_lignes_oap ON ligne_oap_id = c_lignes_oap.oid_source
                    WHERE e_ghm.oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_ghm)
                ;

                DROP TABLE IF EXISTS c_ghm
                ;
                
                CREATE TEMP TABLE c_ghm AS
                    SELECT e_ghm.oid AS oid_source, coalesce(t_ghm.oid,0) AS oid
                    FROM e_ghm LEFT JOIN pmsi.t_ghm ON e_ghm.code = t_ghm.code
                ;
                
                ALTER TABLE c_ghm ADD CONSTRAINT c_ghm_pkey PRIMARY KEY(oid_source)
                ;
                
                -- GHS --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, borne_basse, borne_haute, dms_nationale FROM pmsi.t_ghs WHERE oid <> 0', 'temp e_ghs');
                
                INSERT INTO pmsi.t_ghs (code, texte, borne_basse, borne_haute, dms_nationale)
                SELECT code, texte, borne_basse, borne_haute, dms_nationale
                FROM e_ghs
                WHERE e_ghs.oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_ghs);

                DROP TABLE IF EXISTS c_ghs;
                CREATE TEMP TABLE c_ghs AS
                SELECT e_ghs.oid AS oid_source, coalesce(t_ghs.oid,0) AS oid
                FROM e_ghs LEFT JOIN pmsi.t_ghs ON e_ghs.code = t_ghs.code;
                
                ALTER TABLE c_ghs ADD CONSTRAINT c_ghs_pkey PRIMARY KEY(oid_source);
                
                -- Gestes marqueurs --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court, age_min, age_max FROM pmsi.t_gestes_marqueurs WHERE oid <> 0', 'temp e_gestes_marqueurs');
                
                INSERT INTO pmsi.t_gestes_marqueurs (code, texte, texte_court, age_min, age_max)
                SELECT code, texte, texte_court, age_min, age_max
                FROM e_gestes_marqueurs
                WHERE e_gestes_marqueurs.oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_gestes_marqueurs);

                DROP TABLE IF EXISTS c_gestes_marqueurs;
                CREATE TEMP TABLE c_gestes_marqueurs AS
                SELECT e_gestes_marqueurs.oid AS oid_source, coalesce(t_gestes_marqueurs.oid,0) AS oid
                FROM e_gestes_marqueurs LEFT JOIN pmsi.t_gestes_marqueurs ON e_gestes_marqueurs.code = t_gestes_marqueurs.code;
                
                ALTER TABLE c_gestes_marqueurs ADD CONSTRAINT c_gestes_marqueurs_pkey PRIMARY KEY(oid_source);
                
                -- Regroupements CCAM --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code FROM pmsi.t_ccam_regroupements WHERE oid <> 0', 'temp e_ccam_regroupements');
                
                DROP TABLE IF EXISTS c_ccam_regroupements;
                CREATE TEMP TABLE c_ccam_regroupements AS
                SELECT e_ccam_regroupements.oid AS oid_source,  coalesce(t_ccam_regroupements.oid,0) AS oid
                FROM e_ccam_regroupements LEFT JOIN pmsi.t_ccam_regroupements ON e_ccam_regroupements.code = t_ccam_regroupements.code;
                
                ALTER TABLE c_ccam_regroupements ADD CONSTRAINT c_ccam_regroupements_pkey PRIMARY KEY(oid_source);
                
                -- Actes --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT * FROM pmsi.t_actes WHERE nomenclature <> ''CDAM'' AND oid <> 0', 'temp e_actes');
                
                INSERT INTO pmsi.t_actes (
                    code,
                    texte,
                    texte_court,
                    nomenclature,
                    classant,
                    ccam_regroupement_id_1,
                    ccam_regroupement_id_4,
                    geste_marqueur_id
                )
                SELECT 
                    code,
                    texte,
                    texte_court,
                    nomenclature,
                    classant,
                    COALESCE(c_ccam_regroupements_1.oid,0) AS ccam_regroupement_id_1,
                    COALESCE(c_ccam_regroupements_4.oid,0) AS ccam_regroupement_id_4,
                    COALESCE(c_gestes_marqueurs.oid,0) AS geste_marqueur_id
                FROM e_actes
                LEFT JOIN c_ccam_regroupements c_ccam_regroupements_1 ON ccam_regroupement_id_1 = c_ccam_regroupements_1.oid_source
                LEFT JOIN c_ccam_regroupements c_ccam_regroupements_4 ON ccam_regroupement_id_4 = c_ccam_regroupements_4.oid_source
                LEFT JOIN c_gestes_marqueurs ON geste_marqueur_id = c_gestes_marqueurs.oid_source
                WHERE e_actes.oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_actes);

                DROP TABLE IF EXISTS c_actes;
                CREATE TEMP TABLE c_actes AS
                SELECT e_actes.oid AS oid_source,   coalesce(t_actes.oid,0) AS oid
                FROM e_actes LEFT JOIN pmsi.t_actes ON e_actes.code = t_actes.code;
                
                ALTER TABLE c_actes ADD CONSTRAINT c_actes_pkey PRIMARY KEY(oid_source);

                -- Prestations --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court, compteur_rsf, type_ghs, supplement FROM pmsi.t_prestations WHERE oid <> 0', 'temp e_prestations');
                
                INSERT INTO pmsi.t_prestations (code, texte, texte_court, compteur_rsf, type_ghs, supplement)
                SELECT code, texte, texte_court, compteur_rsf, type_ghs, supplement
                FROM e_prestations
                WHERE e_prestations.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM pmsi.t_prestations);

                DROP TABLE IF EXISTS c_prestations;
                CREATE TEMP TABLE c_prestations AS
                SELECT e_prestations.oid AS oid_source, coalesce(t_prestations.oid,0) AS oid
                FROM e_prestations LEFT JOIN pmsi.t_prestations ON e_prestations.code = t_prestations.code;
                
                ALTER TABLE c_prestations ADD CONSTRAINT c_prestations_pkey PRIMARY KEY(oid_source);


                -- Codes retour groupeur --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, type, code, texte, bloquante FROM pmsi.t_codes_retour_groupeur WHERE oid <> 0', 'temp e_codes_retour_groupeur');
                
                INSERT INTO pmsi.t_codes_retour_groupeur (type, code, texte, bloquante)
                SELECT type, code, texte, bloquante
                FROM e_codes_retour_groupeur
                WHERE e_codes_retour_groupeur.oid <> 0 AND code <> '' AND type||'_'||code NOT IN (SELECT type||'_'||code FROM pmsi.t_codes_retour_groupeur);

                DROP TABLE IF EXISTS c_codes_retour_groupeur;
                CREATE TEMP TABLE c_codes_retour_groupeur AS
                SELECT e_codes_retour_groupeur.oid AS oid_source, coalesce(t_codes_retour_groupeur.oid,0) AS oid
                FROM e_codes_retour_groupeur 
                    LEFT JOIN pmsi.t_codes_retour_groupeur ON e_codes_retour_groupeur.code = t_codes_retour_groupeur.code AND e_codes_retour_groupeur.type = t_codes_retour_groupeur.type;
                
                
                ALTER TABLE c_codes_retour_groupeur ADD CONSTRAINT c_codes_retour_groupeur_pkey PRIMARY KEY(oid_source);


                -- Prise en charge du forfait journalier --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_pec_fj WHERE oid <> 0', 'temp e_pec_fj');
                
                INSERT INTO base.t_pec_fj (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_pec_fj
                WHERE e_pec_fj.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_pec_fj);

                DROP TABLE IF EXISTS c_pec_fj;
                CREATE TEMP TABLE c_pec_fj AS
                SELECT e_pec_fj.oid AS oid_source, MIN(coalesce(t_pec_fj.oid,0)) AS oid
                FROM e_pec_fj LEFT JOIN base.t_pec_fj ON e_pec_fj.code = t_pec_fj.code
				GROUP BY 1
				;
                
                ALTER TABLE c_pec_fj ADD CONSTRAINT c_pec_fj_pkey PRIMARY KEY(oid_source);


                -- Grands régimes --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court, code_original FROM base.t_grands_regimes WHERE oid <> 0', 'temp e_grands_regimes');
                
                INSERT INTO base.t_grands_regimes (code, texte, texte_court, code_original)
                SELECT code, texte, texte_court, code_original
                FROM e_grands_regimes
                WHERE e_grands_regimes.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_grands_regimes);

                DROP TABLE IF EXISTS c_grands_regimes;
                CREATE TEMP TABLE c_grands_regimes AS
                SELECT e_grands_regimes.oid AS oid_source, MIN(coalesce(t_grands_regimes.oid,0)) AS oid
                FROM e_grands_regimes LEFT JOIN base.t_grands_regimes ON e_grands_regimes.code = t_grands_regimes.code
				GROUP BY 1
				;
                
                ALTER TABLE c_grands_regimes ADD CONSTRAINT c_grands_regimes_pkey PRIMARY KEY(oid_source);


                -- Exonération ticket modérateur --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_exoneration_tm WHERE oid <> 0', 'temp e_exoneration_tm');
                
                INSERT INTO base.t_exoneration_tm (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_exoneration_tm
                WHERE e_exoneration_tm.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_exoneration_tm);

                DROP TABLE IF EXISTS c_exoneration_tm;
                CREATE TEMP TABLE c_exoneration_tm AS
                SELECT e_exoneration_tm.oid AS oid_source, MIN(coalesce(t_exoneration_tm.oid,0)) AS oid
                FROM e_exoneration_tm LEFT JOIN base.t_exoneration_tm ON e_exoneration_tm.code = t_exoneration_tm.code
				GROUP BY 1
				;
                
                ALTER TABLE c_exoneration_tm ADD CONSTRAINT c_exoneration_tm_pkey PRIMARY KEY(oid_source);


                -- Nature d'assurance --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_nature_assurance WHERE oid <> 0', 'temp e_nature_assurance');
                
                INSERT INTO base.t_nature_assurance (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_nature_assurance
                WHERE e_nature_assurance.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_nature_assurance WHERE code IS NOT NULL);

                DROP TABLE IF EXISTS c_nature_assurance;
                CREATE TEMP TABLE c_nature_assurance AS
                SELECT e_nature_assurance.oid AS oid_source, MIN(coalesce(t_nature_assurance.oid,0)) AS oid
                FROM e_nature_assurance LEFT JOIN base.t_nature_assurance ON e_nature_assurance.code = t_nature_assurance.code
				GROUP BY 1
				;
                
                ALTER TABLE c_nature_assurance ADD CONSTRAINT c_nature_assurance_pkey PRIMARY KEY(oid_source);


                -- Prise en charge --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_pec WHERE oid <> 0', 'temp e_pec');
                
                INSERT INTO base.t_pec (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_pec
                WHERE e_pec.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_pec);

                DROP TABLE IF EXISTS c_pec;
                CREATE TEMP TABLE c_pec AS
                SELECT e_pec.oid AS oid_source, MIN(coalesce(t_pec.oid,0)) AS oid
                FROM e_pec LEFT JOIN base.t_pec ON e_pec.code = t_pec.code
				GROUP BY 1
				;
                
                ALTER TABLE c_pec ADD CONSTRAINT c_pec_pkey PRIMARY KEY(oid_source);


                -- Type de contrat organisme complémentaire --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_type_contrat_oc WHERE oid <> 0', 'temp e_type_contrat_oc');
                
                INSERT INTO base.t_type_contrat_oc (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_type_contrat_oc
                WHERE e_type_contrat_oc.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_type_contrat_oc);

                DROP TABLE IF EXISTS c_type_contrat_oc;
                CREATE TEMP TABLE c_type_contrat_oc AS
                SELECT e_type_contrat_oc.oid AS oid_source, MIN(coalesce(t_type_contrat_oc.oid,0)) AS oid
                FROM e_type_contrat_oc LEFT JOIN base.t_type_contrat_oc ON e_type_contrat_oc.code = t_type_contrat_oc.code
				GROUP BY 1
				;
                
                ALTER TABLE c_type_contrat_oc ADD CONSTRAINT c_type_contrat_oc_pkey PRIMARY KEY(oid_source);


                -- Motif de non facturation --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_motif_non_facturation WHERE oid <> 0', 'temp e_motif_non_facturation');
                
                INSERT INTO base.t_motif_non_facturation (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_motif_non_facturation
                WHERE e_motif_non_facturation.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_motif_non_facturation);

                DROP TABLE IF EXISTS c_motif_non_facturation;
                CREATE TEMP TABLE c_motif_non_facturation AS
                SELECT e_motif_non_facturation.oid AS oid_source, MIN(coalesce(t_motif_non_facturation.oid,0)) AS oid
                FROM e_motif_non_facturation LEFT JOIN base.t_motif_non_facturation ON e_motif_non_facturation.code = t_motif_non_facturation.code
				GROUP BY 1
				;
                
                ALTER TABLE c_motif_non_facturation ADD CONSTRAINT c_motif_non_facturation_pkey PRIMARY KEY(oid_source);


                -- Facturation 18 euros --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_facturation_18euros WHERE oid <> 0', 'temp e_facturation_18euros');
                
                INSERT INTO base.t_facturation_18euros (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_facturation_18euros
                WHERE e_facturation_18euros.oid <> 0 AND code <> '' AND code NOT IN (SELECT code FROM base.t_facturation_18euros);

                DROP TABLE IF EXISTS c_facturation_18euros;
                CREATE TEMP TABLE c_facturation_18euros AS
                SELECT e_facturation_18euros.oid AS oid_source, MIN(coalesce(t_facturation_18euros.oid,0)) AS oid
                FROM e_facturation_18euros LEFT JOIN base.t_facturation_18euros ON e_facturation_18euros.code = t_facturation_18euros.code
				GROUP BY 1
				;
                
                ALTER TABLE c_facturation_18euros ADD CONSTRAINT c_facturation_18euros_pkey PRIMARY KEY(oid_source);


                -- LPP --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM pmsi.t_lpp WHERE oid <> 0', 'temp e_lpp');
                
                UPDATE pmsi.t_lpp SET
                    texte = e_lpp.texte,
                    texte_court = e_lpp.texte_court
                FROM
                    e_lpp
                WHERE 1=1
                    AND t_lpp.oid <> 0
                    AND t_lpp.code = e_lpp.code
                    AND t_lpp.texte != e_lpp.texte;
                
                INSERT INTO pmsi.t_lpp (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_lpp
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_lpp) AND oid <> 0;

                DROP TABLE IF EXISTS c_lpp;
                CREATE TEMP TABLE c_lpp AS
                SELECT e_lpp.oid AS oid_source, coalesce(t_lpp.oid,0) AS oid
                FROM e_lpp LEFT JOIN pmsi.t_lpp ON e_lpp.code = t_lpp.code;
                
                ALTER TABLE c_lpp ADD CONSTRAINT c_lpp_pkey PRIMARY KEY(oid_source);
                
                -- UCD --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM pmsi.t_ucd WHERE oid <> 0', 'temp e_ucd');
                
                UPDATE pmsi.t_ucd SET
                    texte = e_ucd.texte,
                    texte_court = e_ucd.texte_court
                FROM
                    e_ucd
                WHERE 1=1
                    AND t_ucd.oid <> 0
                    AND t_ucd.code = e_ucd.code
                    AND t_ucd.texte != e_ucd.texte;
                
                INSERT INTO pmsi.t_ucd (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_ucd
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_ucd) AND oid <> 0;

                DROP TABLE IF EXISTS c_ucd;
                CREATE TEMP TABLE c_ucd AS
                SELECT e_ucd.oid AS oid_source, coalesce(t_ucd.oid,0) AS oid
                FROM e_ucd LEFT JOIN pmsi.t_ucd ON e_ucd.code = t_ucd.code;
                
                ALTER TABLE c_ucd ADD CONSTRAINT c_ucd_pkey PRIMARY KEY(oid_source);

                -- LPP DANS BASE--
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_lpp WHERE oid <> 0', 'temp base_e_lpp');
                
                UPDATE base.t_lpp SET
                    texte = base_e_lpp.texte,
                    texte_court = base_e_lpp.texte_court
                FROM
                    base_e_lpp
                WHERE 1=1
                    AND t_lpp.oid <> 0
                    AND t_lpp.code = base_e_lpp.code
                    AND t_lpp.texte != base_e_lpp.texte;
                
                INSERT INTO base.t_lpp (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM base_e_lpp
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM base.t_lpp) AND oid <> 0;


                -- UCD DANS BASE--
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_ucd WHERE oid <> 0', 'temp base_e_ucd');
                
                UPDATE base.t_ucd SET
                    texte = base_e_ucd.texte,
                    texte_court = base_e_ucd.texte_court
                FROM
                    base_e_ucd
                WHERE 1=1
                    AND t_ucd.oid <> 0
                    AND t_ucd.code = base_e_ucd.code
                    AND t_ucd.texte != base_e_ucd.texte;
                
                INSERT INTO base.t_ucd (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM base_e_ucd
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM base.t_ucd) AND oid <> 0;

                
                -- Types Autorisations --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT DISTINCT trim(code) as code, texte, texte_court FROM pmsi.t_types_autorisations', 'temp e_types_autorisations');

                INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_types_autorisations
                WHERE 1=1 AND
                    code IS NOT NULL AND
                    code NOT IN (SELECT code FROM pmsi.t_types_autorisations);
                    
                -- Unités médicales --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, COALESCE(trim(type_autorisation), '''') as type_autorisation, date_effet_autorisation FROM pmsi.t_unites_medicales WHERE oid <> 0', 'temp e_unites_medicales');
                
                INSERT INTO pmsi.t_unites_medicales (code, texte, type_autorisation)
                SELECT e_unites_medicales.code || '_' || t_finess.oid AS code, 
                    e_unites_medicales.texte || ' (' || t_finess.code || ')', 
                    type_autorisation
                FROM e_unites_medicales
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                WHERE e_unites_medicales.oid <> 0 AND e_unites_medicales.code || '_' || t_finess.oid NOT IN (SELECT code FROM pmsi.t_unites_medicales) ;
                
                UPDATE pmsi.t_unites_medicales
                SET texte = (e_unites_medicales.texte || ' (' || t_finess.code || ')'),
                    type_autorisation = e_unites_medicales.type_autorisation,
                    date_effet_autorisation = e_unites_medicales.date_effet_autorisation
                FROM e_unites_medicales
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                WHERE e_unites_medicales.code || '_' || t_finess.oid = t_unites_medicales.code AND
                    (
                    t_unites_medicales.texte IS DISTINCT FROM (e_unites_medicales.texte || ' (' || t_finess.code || ')') OR
                    t_unites_medicales.type_autorisation IS DISTINCT FROM e_unites_medicales.type_autorisation OR
                    t_unites_medicales.date_effet_autorisation IS DISTINCT FROM e_unites_medicales.date_effet_autorisation
                    );

                DROP TABLE IF EXISTS c_unites_medicales;
                CREATE TEMP TABLE c_unites_medicales AS
                SELECT e_unites_medicales.oid AS oid_source, coalesce(t_unites_medicales.oid,0) AS oid
                FROM e_unites_medicales 
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                LEFT JOIN pmsi.t_unites_medicales ON e_unites_medicales.code || '_' || t_finess.oid = t_unites_medicales.code;
                
                ALTER TABLE c_unites_medicales ADD CONSTRAINT c_unites_medicales_pkey PRIMARY KEY(oid_source);
                    
                -- Unités fonctionnelles --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte FROM pmsi.t_unites_fonctionnelles WHERE oid <> 0', 'temp e_unites_fonctionnelles');
                
                INSERT INTO pmsi.t_unites_fonctionnelles (code, texte)
                SELECT e_unites_fonctionnelles.code || '_' || t_finess.oid AS code, 
                    e_unites_fonctionnelles.texte || ' (' || t_finess.code || ')'
                FROM e_unites_fonctionnelles
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                WHERE e_unites_fonctionnelles.oid <> 0 AND e_unites_fonctionnelles.code || '_' || t_finess.oid NOT IN (SELECT code FROM pmsi.t_unites_fonctionnelles) ;
                
                UPDATE pmsi.t_unites_fonctionnelles
                SET texte = (e_unites_fonctionnelles.texte || ' (' || t_finess.code || ')')
                FROM e_unites_fonctionnelles
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                WHERE e_unites_fonctionnelles.code || '_' || t_finess.oid = t_unites_fonctionnelles.code AND
                    t_unites_fonctionnelles.texte IS DISTINCT FROM (e_unites_fonctionnelles.texte || ' (' || t_finess.code || ')');

                DROP TABLE IF EXISTS c_unites_fonctionnelles;
                CREATE TEMP TABLE c_unites_fonctionnelles AS
                SELECT e_unites_fonctionnelles.oid AS oid_source, coalesce(t_unites_fonctionnelles.oid,0) AS oid
                FROM e_unites_fonctionnelles 
                JOIN base.t_finess ON t_finess.code = '[FINESS]'
                LEFT JOIN pmsi.t_unites_fonctionnelles ON e_unites_fonctionnelles.code || '_' || t_finess.oid = t_unites_fonctionnelles.code;
                
                ALTER TABLE c_unites_fonctionnelles ADD CONSTRAINT c_unites_fonctionnelles_pkey PRIMARY KEY(oid_source);

                -- Modes E/S --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT trim(code) AS code, texte, texte_court FROM pmsi.t_modes_entree', 'temp e_modes_entree');
                
                INSERT INTO pmsi.t_modes_entree (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_modes_entree
                WHERE code NOT IN (SELECT trim(code) FROM pmsi.t_modes_entree) ;
                
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT trim(code) AS code, texte, texte_court FROM pmsi.t_modes_sortie', 'temp e_modes_sortie');
                
                INSERT INTO pmsi.t_modes_sortie (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_modes_sortie
                WHERE code NOT IN (SELECT trim(code) FROM pmsi.t_modes_sortie) ;
                
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT trim(code) AS code, texte, texte_court FROM pmsi.t_provenances_entree', 'temp e_provenances_entree');
                
                INSERT INTO pmsi.t_provenances_entree (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_provenances_entree
                WHERE code NOT IN (SELECT trim(code) FROM pmsi.t_provenances_entree) ;

                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT trim(code) AS code, texte, texte_court FROM pmsi.t_destinations_sortie', 'temp e_destinations_sortie');
                
                INSERT INTO pmsi.t_destinations_sortie (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_destinations_sortie
                WHERE code NOT IN (SELECT trim(code) FROM pmsi.t_destinations_sortie) ;

                
                -- Diagnostics --                       
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, severite_fg11_code, severite_fg12_code, severite_fg13_code FROM pmsi.t_diagnostics WHERE oid <> 0', 'temp e_diagnostics');
                
                INSERT INTO pmsi.t_diagnostics (code, texte, severite_fg11_code, severite_fg12_code, severite_fg13_code)
                SELECT code, texte, severite_fg11_code, severite_fg12_code, severite_fg13_code
                FROM e_diagnostics
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_diagnostics);

                DROP TABLE IF EXISTS c_diagnostics;
                CREATE TEMP TABLE c_diagnostics AS
                SELECT e_diagnostics.oid AS oid_source, coalesce(t_diagnostics.oid,0) AS oid
                FROM e_diagnostics
                    LEFT JOIN pmsi.t_diagnostics ON e_diagnostics.code = t_diagnostics.code;
                
                ALTER TABLE c_diagnostics ADD CONSTRAINT c_diagnostics_pkey PRIMARY KEY(oid_source);
                
                
                -- Spécialités (base) --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte, texte_court FROM base.t_specialites_medecin WHERE oid <> 0', 'temp e_specialites_medecin_base');
                
                INSERT INTO base.t_specialites_medecin (code, texte, texte_court)
                SELECT code, texte, texte_court
                FROM e_specialites_medecin_base
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM base.t_specialites_medecin WHERE code IS NOT NULL);

                DROP TABLE IF EXISTS c_specialites_medecin_base;
                CREATE TEMP TABLE c_specialites_medecin_base AS
                SELECT e_specialites_medecin_base.oid AS oid_source, coalesce(t_specialites_medecin.oid,0) AS oid
                FROM e_specialites_medecin_base 
                    LEFT JOIN base.t_specialites_medecin ON e_specialites_medecin_base.code = t_specialites_medecin.code;
                
                ALTER TABLE c_specialites_medecin_base ADD CONSTRAINT c_specialites_medecin_base_pkey PRIMARY KEY(oid_source);
                
                
                -- Médecins (base) --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT * FROM base.t_medecins 
                    WHERE oid <> 0 AND code <> ''''
                        AND oid IN (SELECT medecin_id FROM pmsi.t_medecins JOIN pmsi.p_oids ON code_table like ''medecins_%'' AND t_medecins.oid = p_oids.oid GROUP BY 1)', 'temp e_medecins_base');
                
                INSERT INTO base.t_medecins (code, nom, prenom, numero_ordre, specialite_id)
                SELECT e_medecins_base.code, 
                    e_medecins_base.nom, 
                    COALESCE(e_medecins_base.prenom,''::text), 
                    e_medecins_base.numero_ordre, 
                    COALESCE(c_specialites_medecin_base.oid,0)
                FROM e_medecins_base
                LEFT JOIN c_specialites_medecin_base ON e_medecins_base.specialite_id = c_specialites_medecin_base.oid_source
                LEFT JOIN base.t_medecins ON e_medecins_base.nom = t_medecins.nom AND
                     e_medecins_base.prenom = t_medecins.prenom AND
                     e_medecins_base.numero_ordre = t_medecins.numero_ordre AND
                    t_medecins.specialite_id = COALESCE(c_specialites_medecin_base.oid,0)
                WHERE e_medecins_base.oid <> 0 AND
                    t_medecins.oid IS NULL;
                
                DROP TABLE IF EXISTS c_medecins_base;
                CREATE TEMP TABLE c_medecins_base AS
                SELECT e_medecins_base.oid AS oid_source, MIN(coalesce(t_medecins.oid,0)) AS oid
                FROM e_medecins_base 
                    LEFT JOIN c_specialites_medecin_base ON oid_source = e_medecins_base.specialite_id
                    LEFT JOIN base.t_medecins ON e_medecins_base.nom = t_medecins.nom AND
                        e_medecins_base.prenom = t_medecins.prenom AND
                        e_medecins_base.numero_ordre = t_medecins.numero_ordre AND 
                        c_specialites_medecin_base.oid =  t_medecins.specialite_id
                GROUP BY 1;
                
                ALTER TABLE c_medecins_base ADD CONSTRAINT c_medecins_base_pkey PRIMARY KEY(oid_source);
                
                                        
                -- Spécialités --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte FROM pmsi.t_specialites_medecin WHERE oid <> 0', 'temp e_specialites_medecin');
                
                INSERT INTO pmsi.t_specialites_medecin (code, texte)
                SELECT code, texte
                FROM e_specialites_medecin
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_specialites_medecin);

                DROP TABLE IF EXISTS c_specialites_medecin;
                CREATE TEMP TABLE c_specialites_medecin AS
                SELECT e_specialites_medecin.oid AS oid_source, coalesce(t_specialites_medecin.oid,0) AS oid
                FROM e_specialites_medecin LEFT JOIN pmsi.t_specialites_medecin ON e_specialites_medecin.code = t_specialites_medecin.code;
                
                ALTER TABLE c_specialites_medecin ADD CONSTRAINT c_specialites_medecin_pkey PRIMARY KEY(oid_source);
                
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code, texte FROM pmsi.t_specialites_internes_medecin WHERE oid <> 0', 'temp e_specialites_internes_medecin');
                
                INSERT INTO pmsi.t_specialites_internes_medecin (code, texte)
                SELECT code, texte
                FROM e_specialites_internes_medecin
                WHERE oid <> 0 AND code NOT IN (SELECT code FROM pmsi.t_specialites_internes_medecin);

                DROP TABLE IF EXISTS c_specialites_internes_medecin;
                CREATE TEMP TABLE c_specialites_internes_medecin AS
                SELECT e_specialites_internes_medecin.oid AS oid_source, coalesce(t_specialites_internes_medecin.oid,0) AS oid
                FROM e_specialites_internes_medecin LEFT JOIN pmsi.t_specialites_internes_medecin ON e_specialites_internes_medecin.code = t_specialites_internes_medecin.code;
                
                ALTER TABLE c_specialites_internes_medecin ADD CONSTRAINT c_specialites_internes_medecin_pkey PRIMARY KEY(oid_source);

                
                -- Médecins --
                DROP TABLE IF EXISTS e_medecins;
                                        
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT *
                    FROM pmsi.t_medecins 
                    WHERE oid <> 0
                        AND oid IN (SELECT oid FROM pmsi.p_oids WHERE code_table LIKE ''medecin_%'' GROUP BY 1)', 'temp e_medecins');
                    
                CREATE INDEX e_medecins_key
                  ON e_medecins
                  USING btree
                  (temp.t_medecins_key(nom,COALESCE(prenom, ''::text)));


                -- correction de l'ancienne méthode (on remonte maintenant tous les médecins systématiquement)
                UPDATE pmsi.t_medecins
                SET code = e_medecins.code::text || '#'::text || upper(substr(md5(e_medecins.nom::text || COALESCE(e_medecins.prenom,''::text) || e_medecins.oid::text),1,5))::text
                FROM e_medecins
                LEFT JOIN c_specialites_medecin ON specialite_id = c_specialites_medecin.oid_source
                LEFT JOIN c_specialites_internes_medecin ON specialite_interne_id = c_specialites_internes_medecin.oid_source
                LEFT JOIN c_medecins_base ON medecin_id = c_medecins_base.oid_source
                WHERE
                    temp.t_medecins_key(e_medecins.nom, COALESCE(e_medecins.prenom,''::text)) = temp.t_medecins_key(t_medecins.nom, COALESCE(t_medecins.prenom,''::text)) 
                    AND t_medecins.code = e_medecins.code
                    AND (t_medecins.specialite_id = c_specialites_medecin.oid  AND t_medecins.specialite_interne_id = c_specialites_internes_medecin.oid )
                ;
                  
                --maj des spécialités et references si le médecin côté consolidé n'a pas de référence auquel cas on considère que c'est surchargé dans le conso
                UPDATE pmsi.t_medecins
                SET
                    medecin_id = c_medecins_base.oid,
                    specialite_id = c_specialites_medecin.oid,
                    specialite_interne_id = c_specialites_internes_medecin.oid
                FROM e_medecins
                    LEFT JOIN c_medecins_base ON e_medecins.medecin_id = c_medecins_base.oid_source
                    LEFT JOIN c_specialites_medecin ON e_medecins.specialite_id = c_specialites_medecin.oid_source
                    LEFT JOIN c_specialites_internes_medecin ON e_medecins.specialite_interne_id = c_specialites_internes_medecin.oid_source
                WHERE 1=1 
                    AND t_medecins.oid = 0
                    AND e_medecins.code::text || '#'::text || upper(substr(md5(e_medecins.nom::text || COALESCE(e_medecins.prenom::text,'') || e_medecins.oid::text),1,5))::text = t_medecins.code
                    AND (
                        e_medecins.medecin_id <> COALESCE(c_medecins_base.oid,0) OR
                        e_medecins.specialite_id <> c_specialites_medecin.oid OR
                        e_medecins.specialite_interne_id <> c_specialites_internes_medecin.oid
                        )
                ;
                  
                INSERT INTO pmsi.t_medecins ( 
                    code,
                    nom,
                    prenom,
                    specialite_id,
                    no_adeli,
                    statut,
                    medecin_reference_id,
                    specialite_interne_id,
                    identifiant_annuaire,
                    medecin_id
                )
                SELECT 
                    e_medecins.code::text || '#'::text || upper(substr(md5(nom::text || COALESCE(prenom::text, ''::text) || e_medecins.oid::text),1,5))::text,
                    nom,
                    COALESCE(prenom, ''::text),
                    COALESCE(c_specialites_medecin.oid,0) AS specialite_id,
                    no_adeli,
                    statut,
                    0 AS medecin_reference_id,
                    COALESCE(c_specialites_internes_medecin.oid,0) AS specialite_interne_id,
                    identifiant_annuaire,
                    COALESCE(c_medecins_base.oid,0) AS medecin_id
                FROM e_medecins
                LEFT JOIN c_specialites_medecin ON specialite_id = c_specialites_medecin.oid_source
                LEFT JOIN c_specialites_internes_medecin ON specialite_interne_id = c_specialites_internes_medecin.oid_source
                LEFT JOIN c_medecins_base ON medecin_id = c_medecins_base.oid_source
                WHERE e_medecins.oid <> 0 AND 
                    e_medecins.code::text || '#'::text || upper(substr(md5(nom::text || COALESCE(prenom::text, ''::text) || e_medecins.oid::text),1,5))::text
                    NOT IN (SELECT code FROM pmsi.t_medecins)
                    ;
                    
                -- Si code unique, enlever suffixe  
                --UPDATE pmsi.t_medecins
                --SET code = to_code
                --FROM (
                --  SELECT split_part(code,'#',1) AS to_code, MAX(code) AS from_code
                --  FROM pmsi.t_medecins
                --  WHERE code like '%#%' AND
                --      split_part(code,'#',1) NOT IN (SELECT code FROM pmsi.t_medecins WHERE code IS NOT NULL)
                --  GROUP BY 1
                --  HAVING count(*) = 1
                --) subview
                --WHERE subview.from_code = t_medecins.code;
                
                DROP TABLE IF EXISTS c_medecins;
                CREATE TEMP TABLE c_medecins AS
                SELECT e_medecins.oid AS oid_source, 
                    t_medecins.oid AS oid
                FROM e_medecins 
                    JOIN pmsi.t_medecins ON e_medecins.code::text || '#'::text || upper(substr(md5(e_medecins.nom::text || COALESCE(e_medecins.prenom::text, ''::text) || e_medecins.oid::text),1,5))::text = t_medecins.code
                ;

                ALTER TABLE c_medecins ADD CONSTRAINT c_medecins_pkey PRIMARY KEY(oid_source);

                
                -- Codes postaux --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, code FROM base.t_codes_postaux WHERE oid <> 0', 'temp e_codes_postaux');
                
                DROP TABLE IF EXISTS c_codes_postaux;
                CREATE TEMP TABLE c_codes_postaux AS
                SELECT e_codes_postaux.oid AS oid_source, coalesce(t_codes_postaux.oid,0) AS oid
                FROM e_codes_postaux LEFT JOIN base.t_codes_postaux ON e_codes_postaux.code = t_codes_postaux.code;
                
                ALTER TABLE c_codes_postaux ADD CONSTRAINT c_codes_postaux_pkey PRIMARY KEY(oid_source);
                                        
            ]]></sqlcmd>
        </NODE>
        <NODE name="PRODUCTION" label="Production">
            <condition><![CDATA[
                "[MOISMODIFIES]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[    
            -- Effacement avant regénération --
                DROP TABLE IF EXISTS w_rss_modifies
                ;
                
                CREATE TEMP TABLE w_rss_modifies AS
                    SELECT oid FROM pmsi.p_rss WHERE finess = '[FINESS]' AND  
                            (p_rss.en_cours = '0' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> '0' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                ;
                
                ALTER TABLE w_rss_modifies ADD CONSTRAINT w_rss_modifies_pkey PRIMARY KEY(oid);
                
                DELETE FROM pmsi.p_identites USING w_rss_modifies WHERE rss_id = oid;
                
                DELETE FROM pmsi.p_rss_etat USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rss_rum USING w_rss_modifies WHERE rss_id = oid;
				
                DELETE FROM pmsi.p_rss_transferts USING w_rss_modifies WHERE rss_id = oid;

                DELETE FROM pmsi.p_rss_cardio USING w_rss_modifies WHERE p_rss_cardio.rss_id = w_rss_modifies.oid;

                DELETE FROM pmsi.p_rss_ipa USING w_rss_modifies WHERE rss_id = oid;
                
                DELETE FROM pmsi.p_rss_src USING w_rss_modifies WHERE p_rss_src.oid = w_rss_modifies.oid;
                
                DELETE FROM pmsi.p_rss_rea USING w_rss_modifies WHERE p_rss_rea.oid = w_rss_modifies.oid;
                
                DELETE FROM pmsi.p_etude_impact_cma USING w_rss_modifies WHERE rss_id = oid;
                
                DELETE FROM pmsi.p_rss_gm USING w_rss_modifies WHERE rss_id = oid;

                DELETE FROM pmsi.p_rss_diagnostics USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rss_actes USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rss_lpp USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rss_ucd USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rss_leg USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rsf_total USING w_rss_modifies WHERE rss_id = oid;
            
                DELETE FROM pmsi.p_rsf_detail USING w_rss_modifies WHERE rss_id = oid;
                
				
				DELETE FROM pmsi.p_expert_rss_controle
				USING pmsi.p_rss
				WHERE p_rss.oid = rss_id AND
					p_rss.finess = '[FINESS]'
				;
				

                ;
				DELETE FROM pmsi.p_simulation_fg2223 USING w_rss_modifies WHERE rss_id = oid
				;
                DELETE FROM pmsi.p_simulation_fg2324 USING w_rss_modifies WHERE rss_id = oid
                ;

                DELETE FROM pmsi.p_rss_cancero USING pmsi.p_rss WHERE p_rss.oid = p_rss_cancero.rss_id AND finess = '[FINESS]';

                DELETE FROM pmsi.p_rss WHERE finess = '[FINESS]' AND  
                        (p_rss.en_cours = '0' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> '0' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]));          
                DELETE FROM pmsi.p_chiffrier WHERE finess = '[FINESS]' AND mois IN ([MOISMODIFIES]);

                SELECT setval('pmsi.s_rss', COALESCE(MAX(oid),0) + 1) FROM pmsi.p_rss;
                                        
                -- Chiffrier --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT *
                    FROM pmsi.p_chiffrier 
                    WHERE mois IN ([MOISMODIFIES])
                    ', 'temp e_chiffrier'
                );
        
                INSERT INTO pmsi.p_chiffrier(
                    mois,
                    finess,
                    nb_rsa,
                    ca_sejour,
                    nb_rsa_champ_ghs,
                    ca_sejour_champ_ghs,
                    nb_rsa_hors_champ_ghs,
                    ca_sejour_hors_champ_ghs,
                    nb_rsa_en_cours_valides_champ_ghs,
                    nb_rsa_en_cours_groupes_champ_ghs,
                    nb_rsa_en_cours_sortis_non_groupes_champ_ghs,
                    nb_rsa_en_cours_presents_champ_ghs,
                    ca_sejour_en_cours_valides_champ_ghs,
                    ca_sejour_en_cours_groupes_champ_ghs,
                    ca_sejour_en_cours_sortis_non_groupes_champ_ghs,
                    ca_sejour_en_cours_presents_champ_ghs)
                SELECT 
                    mois,
                    '[FINESS]', 
                    SUM(nb_rsa) AS nb_rsa,
                    SUM(ca_sejour) AS ca_sejour,
                    SUM(nb_rsa_champ_ghs) AS nb_rsa_champ_ghs,
                    SUM(ca_sejour_champ_ghs) AS ca_sejour_champ_ghs,
                    SUM(nb_rsa_hors_champ_ghs) AS nb_rsa_hors_champ_ghs,
                    SUM(ca_sejour_hors_champ_ghs) AS ca_sejour_hors_champ_ghs,
                    SUM(nb_rsa_en_cours_valides_champ_ghs) AS nb_rsa_en_cours_valides_champ_ghs,
                    SUM(nb_rsa_en_cours_groupes_champ_ghs) AS nb_rsa_en_cours_groupes_champ_ghs,
                    SUM(nb_rsa_en_cours_sortis_non_groupes_champ_ghs) AS nb_rsa_en_cours_sortis_non_groupes_champ_ghs,
                    SUM(nb_rsa_en_cours_presents_champ_ghs) AS nb_rsa_en_cours_presents_champ_ghs,
                    SUM(ca_sejour_en_cours_valides_champ_ghs) AS ca_sejour_en_cours_valides_champ_ghs,
                    SUM(ca_sejour_en_cours_groupes_champ_ghs) AS ca_sejour_en_cours_groupes_champ_ghs,
                    SUM(ca_sejour_en_cours_sortis_non_groupes_champ_ghs) AS ca_sejour_en_cours_sortis_non_groupes_champ_ghs,
                    SUM(ca_sejour_en_cours_presents_champ_ghs) AS ca_sejour_en_cours_presents_champ_ghs
                FROM e_chiffrier
                WHERE mois IN ([MOISMODIFIES])
                GROUP by 1;
                
                DROP TABLE IF EXISTS e_chiffrier;
                
                        
                -- Patients --
                
                DROP TABLE IF EXISTS e_patients;
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT *
                    FROM pmsi.p_patients
                    WHERE nom != '''' AND oid IN (SELECT patient_id FROM pmsi.p_rss WHERE  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS])))
                    ', 'temp e_patients'
                );
                
                CREATE INDEX e_patients_key
                  ON e_patients
                  USING btree
                  (temp.p_patients_key(e_patients.nom, e_patients.prenom, e_patients.sexe, e_patients.date_naissance));
                
                INSERT INTO pmsi.p_patients (finess, nom, prenom, sexe, date_naissance)
                SELECT  
                    '[FINESS]', 
                    UPPER(e_patients.nom) as nom,  
                    UPPER(e_patients.prenom) as prenom, 
                    e_patients.sexe, 
                    e_patients.date_naissance
                FROM e_patients 
                    LEFT JOIN pmsi.p_patients ON temp.p_patients_key(e_patients.nom, e_patients.prenom, e_patients.sexe, e_patients.date_naissance) =
                            temp.p_patients_key(p_patients.nom, p_patients.prenom, p_patients.sexe, p_patients.date_naissance)
                WHERE p_patients.oid IS NULL;

                DROP TABLE IF EXISTS c_patients;
                CREATE TEMP TABLE c_patients AS
                SELECT e_patients.oid AS oid_source, MAX(coalesce(p_patients.oid,0)) AS oid
                FROM e_patients 
                    LEFT JOIN pmsi.p_patients ON temp.p_patients_key(e_patients.nom, e_patients.prenom, e_patients.sexe, e_patients.date_naissance) =
                            temp.p_patients_key(p_patients.nom, p_patients.prenom, p_patients.sexe, p_patients.date_naissance)
                GROUP BY 1;
                
                ALTER TABLE c_patients ADD CONSTRAINT c_patients_pkey PRIMARY KEY(oid_source);
                                        
            
                -- RSS --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT *
                    FROM pmsi.p_rss
                    WHERE (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS])) 
                        AND etat <> ''S''
                        AND p_rss.no_rss <> 0 
                    ', 'temp e_rss'
                );
                
                UPDATE e_rss
                SET no_rss = 0-oid
                WHERE no_rss = 0
                ;

                INSERT INTO pmsi.p_rss(
                    no_patient,
                    finess,
                    no_rss,
                    version_groupage,
                    date_naissance,
                    sexe,
                    date_entree,
                    date_sortie,
                    mode_entree,
                    provenance,
                    mode_sortie,
                    destination,
                    code_postal,
                    poids_bebe,
                    igs2,
                    cma,
                    groupe_ghm,
                    duree_sejour,
                    nb_rsa,
                    age,
                    supprime,
                    date_import,
                    nb_rum,
                    secteur,
                    no_sejour_administratif,
                    nb_seances,
                    ghm_fg9,
                    ghm_id,
                    medecin_rss_id,
                    ghs_id,
                    mois_sortie,
                    diagnostic_principal_id,
                    diagnostic_relie_id,
                    ghm_production_id,
                    no_rum_principal,
                    unite_medicale_principale_id,
                    oid,
                    import_id,
                    etat,
                    acte_principal_id,
                    code_postal_id,
                    patient_id,
                    prestation_principale_id,
                    severite_fg11_simulation_code,
                    en_cours,
                    en_cours_etat,
                    base_remboursement,
                    sejour_facture,
                    honoraires_factures,
                    t2a_facture,
                    dmi_facture,
                    phc_facture,
                    ca_ghs_theorique,
                    nb_ghs,
                    ca_ghs,
                    nb_exb,
                    ca_exb,
                    nb_exh,
                    ca_exh,
                    nb_si,
                    ca_si,
                    nb_sur,
                    ca_sur,
                    nb_rea,
                    ca_rea,
                    nb_neonat,
                    ca_neonat,
                    traitement_epmsi,
                    code_retour_groupage,
                    comite_medical_id,
                    rehosp_meme_ghm,
                    from_oid,
                    forfait_facture,
                    age_gestationnel,
                    date_dernieres_regles,
                    confirmation_codage,
                    type_machine_rdth,
                    type_dosimetrie,
                    numero_innovation,
                    nombre_ivg_anterieures,
                    annee_ivg_precedente,
                    nombre_naissances_vivantes_anterieures,
                    avec_anesthesie,
                    nb_ghsmin,
					conversion_hp_hc_id,
					raac_id,
                    rescrit_tarif_id,
                    adm_prod_reshospi_id,
                    contexte_pat_id,
                    nb_intervention_id,
                    ca_ghs_raac,
                    np_id,
                    passage_urgences_code

                )
                SELECT 
                    no_patient,
                    '[FINESS]' AS finess,
                    no_rss,
                    version_groupage,
                    date_naissance,
                    sexe,
                    date_entree,
                    date_sortie,
                    mode_entree,
                    provenance,
                    mode_sortie,
                    destination,
                    code_postal,
                    poids_bebe,
                    igs2,
                    cma,
                    groupe_ghm,
                    duree_sejour,
                    nb_rsa,
                    age,
                    supprime,
                    date_import,
                    nb_rum,
                    secteur,
                    no_sejour_administratif,
                    nb_seances,
                    ghm_fg9,
                    COALESCE(c_ghm_r.oid,0) AS ghm_id,
                    COALESCE(c_medecins.oid,0) AS medecin_rss_id,
                    COALESCE(c_ghs.oid,0) AS ghs_id,
                    mois_sortie,
                    COALESCE(c_diagnostics_p.oid,0) AS diagnostic_principal_id,
                    COALESCE(c_diagnostics_r.oid,0) AS diagnostic_relie_id,
                    COALESCE(c_ghm_p.oid,0) AS ghm_production_id,
                    no_rum_principal,
                    COALESCE(c_unites_medicales.oid,0) AS unite_medicale_principale_id,
                    nextval('pmsi.s_rss'::regclass) AS oid,
                    import_id,
                    etat,
                    COALESCE(c_actes.oid,0) AS acte_principal_id,
                    COALESCE(c_codes_postaux.oid,0) AS code_postal_id,
                    COALESCE(c_patients.oid,0) AS patient_id,
                    COALESCE(c_prestations.oid,0) AS prestation_principale_id,
                    severite_fg11_simulation_code,
                    en_cours,
                    en_cours_etat,
                    base_remboursement,
                    sejour_facture,
                    honoraires_factures,
                    t2a_facture,
                    dmi_facture,
                    phc_facture,
                    ca_ghs_theorique,
                    nb_ghs,
                    ca_ghs,
                    nb_exb,
                    ca_exb,
                    nb_exh,
                    ca_exh,
                    nb_si,
                    ca_si,
                    nb_sur,
                    ca_sur,
                    nb_rea,
                    ca_rea,
                    nb_neonat,
                    ca_neonat,
                    traitement_epmsi,
                    code_retour_groupage,
                    0 AS comite_medical_id,
                    rehosp_meme_ghm,
                    e_rss.oid AS from_oid,
                    forfait_facture,
                    age_gestationnel,
                    date_dernieres_regles,
                    confirmation_codage,
                    type_machine_rdth,
                    type_dosimetrie,
                    numero_innovation,
                    nombre_ivg_anterieures,
                    annee_ivg_precedente,
                    nombre_naissances_vivantes_anterieures,
                    avec_anesthesie,
                    nb_ghsmin,
					conversion_hp_hc_id,
					raac_id,
                    rescrit_tarif_id,
                    adm_prod_reshospi_id,
                    contexte_pat_id,
                    nb_intervention_id,
                    ca_ghs_raac,
                    np_id,
                    passage_urgences_code
                FROM e_rss
                    LEFT JOIN c_medecins ON medecin_rss_id = c_medecins.oid_source
                    LEFT JOIN c_ghs ON ghs_id = c_ghs.oid_source
                    LEFT JOIN c_diagnostics c_diagnostics_p ON diagnostic_principal_id = c_diagnostics_p.oid_source
                    LEFT JOIN c_diagnostics c_diagnostics_r ON diagnostic_relie_id = c_diagnostics_r.oid_source
                    LEFT JOIN c_ghm c_ghm_p ON ghm_production_id = c_ghm_p.oid_source
                    LEFT JOIN c_ghm c_ghm_r ON ghm_id = c_ghm_r.oid_source
                    LEFT JOIN c_unites_medicales ON unite_medicale_principale_id = c_unites_medicales.oid_source
                    LEFT JOIN c_actes ON acte_principal_id = c_actes.oid_source
                    LEFT JOIN c_codes_postaux ON code_postal_id = c_codes_postaux.oid_source
                    LEFT JOIN c_patients ON patient_id = c_patients.oid_source
                    LEFT JOIN c_prestations ON prestation_principale_id = c_prestations.oid_source;

                DROP TABLE IF EXISTS c_rss;
                CREATE TEMP TABLE c_rss AS
                SELECT e_rss.oid AS oid_source, MAX(COALESCE(p_rss.oid,0)) AS oid
                FROM e_rss 
                    JOIN pmsi.p_rss ON p_rss.finess = '[FINESS]' AND e_rss.no_rss = p_rss.no_rss  AND e_rss.date_sortie = p_rss.date_sortie AND e_rss.import_id = p_rss.import_id
                GROUP BY 1;

                ANALYSE c_rss;

                ALTER TABLE c_rss ADD CONSTRAINT c_rss_pkey PRIMARY KEY(oid_source);


                -- Tables utiles si l'on veut regénérer des tables entières
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT oid, no_rss, no_sejour_administratif, date_sortie, import_id
                    FROM pmsi.p_rss
                    WHERE  etat <> ''S''
                        AND p_rss.no_rss <> 0
                    ', 'temp e_rss_all'
                );

                ANALYSE e_rss_all;

                DROP TABLE IF EXISTS c_rss_all;
                CREATE TEMP TABLE c_rss_all AS
                SELECT e_rss_all.oid AS oid_source, MAX(COALESCE(p_rss.oid,0)) AS oid
                FROM e_rss_all
                    JOIN pmsi.p_rss ON p_rss.finess = '[FINESS]' 
                    AND e_rss_all.no_rss = p_rss.no_rss
                    AND e_rss_all.date_sortie = p_rss.date_sortie 
                    AND e_rss_all.import_id = p_rss.import_id
                GROUP BY 1;

                ANALYSE c_rss_all;

                ALTER TABLE c_rss_all ADD CONSTRAINT c_rss_all_pkey PRIMARY KEY(oid_source);

                
                -- identités --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_identites.*
                    FROM pmsi.p_identites JOIN pmsi.p_rss ON p_identites.rss_id = p_rss.oid AND etat <> ''S'' AND
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_identites'
                );
            
                INSERT INTO pmsi.p_identites(
                    no_rss,
                    nom,
                    finess,
                    rss_id,
                    prenom,
                    nom_naissance
                )
                SELECT 
                    no_rss,
                    nom,
                    '[FINESS]' AS finess,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    prenom,
                    nom_naissance
                FROM e_identites
                    JOIN c_rss ON rss_id = c_rss.oid_source;

                    
                -- ETAT --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_etat.*
                    FROM pmsi.p_rss_etat JOIN pmsi.p_rss ON p_rss_etat.rss_id = p_rss.oid AND etat <> ''S'' AND p_rss.no_rss <> 0 AND
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_etat'
                );
				
				DELETE FROM pmsi.p_rss_etat
				USING e_rss_etat
					JOIN c_rss ON rss_id = c_rss.oid_source
				WHERE p_rss_etat.rss_id = c_rss.oid
				;
                
                INSERT INTO pmsi.p_rss_etat(
                    rss_id, 
                    est_groupe, 
                    est_valide, 
                    date_groupage, 
                    est_facture, 
                    date_facture)
                SELECT
                    COALESCE(c_rss.oid,0) AS rss_id,
                    est_groupe, 
                    est_valide, 
                    date_groupage, 
                    est_facture, 
                    date_facture
                FROM e_rss_etat
                JOIN c_rss ON rss_id = c_rss.oid_source
                GROUP BY 1,2,3,4,5,6;
            
                -- RUM --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_rum.*
                    FROM pmsi.p_rss_rum JOIN pmsi.p_rss ON p_rss_rum.rss_id = p_rss.oid AND etat <> ''S'' AND  p_rss.no_rss <> 0 AND
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_rum'
                );
            
                INSERT INTO pmsi.p_rss_rum(
                    finess,
                    no_rss,
                    no_rum,
                    date_entree,
                    date_sortie,
                    mode_entree,
                    provenance,
                    mode_sortie,
                    destination,
                    duree_sejour,
                    nb_seances,
                    unite_medicale,
                    diagnostic_principal_id,
                    diagnostic_relie_id,
                    unite_medicale_id,
                    type_autorisation,
                    rss_id,
                    igs2,
                    type_autorisation_lit_dedie,
                    supplement_code
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    no_rum,
                    date_entree,
                    date_sortie,
                    mode_entree,
                    provenance,
                    mode_sortie,
                    destination,
                    duree_sejour,
                    nb_seances,
                    unite_medicale,
                    COALESCE(c_diagnostics_p.oid,0) AS diagnostic_principal_id,
                    COALESCE(c_diagnostics_r.oid,0) AS diagnostic_relie_id,
                    COALESCE(c_unites_medicales.oid,0) AS unite_medicale_id,
                    type_autorisation,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    igs2,
                    type_autorisation_lit_dedie,
                    supplement_code
                FROM e_rss_rum
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_diagnostics c_diagnostics_p ON diagnostic_principal_id = c_diagnostics_p.oid_source
                    LEFT JOIN c_diagnostics c_diagnostics_r ON diagnostic_relie_id = c_diagnostics_r.oid_source
                    LEFT JOIN c_unites_medicales ON unite_medicale_id = c_unites_medicales.oid_source;
                    
                -- Diagnostics --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_diagnostics.*
                    FROM pmsi.p_rss_diagnostics JOIN pmsi.p_rss ON p_rss_diagnostics.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_diagnostics'
                );
            
                INSERT INTO pmsi.p_rss_diagnostics(
                    finess,
                    no_rss,
                    no_rum,
                    diagnostic_id,
                    type_diagnostic,
                    type_diagnostic_rss,
                    imprecis,
                    unite_medicale,
                    rss_id,
                    unite_medicale_id
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    no_rum,
                    COALESCE(c_diagnostics.oid,0) AS diagnostic_id,
                    type_diagnostic,
                    type_diagnostic_rss,
                    imprecis,
                    unite_medicale,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    COALESCE(c_unites_medicales.oid,0) AS unite_medicale_id
                FROM e_rss_diagnostics
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_diagnostics c_diagnostics ON diagnostic_id = c_diagnostics.oid_source
                    LEFT JOIN c_unites_medicales ON unite_medicale_id = c_unites_medicales.oid_source;
                                        
            
                -- Actes --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_actes.*
                    FROM pmsi.p_rss_actes JOIN pmsi.p_rss ON p_rss_actes.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_actes'
                );

                INSERT INTO pmsi.p_rss_actes(
                    finess,
                    no_rss,
                    no_rum,
                    unite_medicale,
                    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,
                    rss_id,
                    unite_medicale_id,
                    unite_fonctionnelle_id,
					acte_ccam_descriptif_id
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    no_rum,
                    unite_medicale,
                    date_acte,
                    COALESCE(c_medecins.oid,0) AS medecin_id,
                    COALESCE(c_actes.oid,0) AS 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,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    COALESCE(c_unites_medicales.oid,0) AS unite_medicale_id,
                    COALESCE(c_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(c_actes_desc.oid,0) AS acte_ccam_descriptif_id
                FROM e_rss_actes
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_medecins ON medecin_id = c_medecins.oid_source
                    LEFT JOIN c_actes c_actes ON acte_id = c_actes.oid_source
					LEFT JOIN c_actes c_actes_desc ON acte_ccam_descriptif_id = c_actes_desc.oid_source
                    LEFT JOIN c_unites_medicales ON unite_medicale_id = c_unites_medicales.oid_source
                    LEFT JOIN c_unites_fonctionnelles ON unite_fonctionnelle_id = c_unites_fonctionnelles.oid_source;
            
                -- LPP --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_lpp.*
                    FROM pmsi.p_rss_lpp JOIN pmsi.p_rss ON p_rss_lpp.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_lpp'
                );

                INSERT INTO pmsi.p_rss_lpp(
                    finess,
                    no_rss,
                    rang,
                    date_lpp,
                    lpp_id,
                    nombre,
                    prix_unitaire,
                    montant_facture,
                    rss_id,
                    non_pris_en_compte,
                    prix_unitaire_tr,
                    montant_tr,
                    montant_t2a_accorde,
                    montant_ecart_indemnisable
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    rang,
                    date_lpp,
                    COALESCE(c_lpp.oid,0) AS lpp_id,
                    nombre,
                    prix_unitaire,
                    montant_facture,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    non_pris_en_compte,
                    prix_unitaire_tr,
                    montant_tr,
                    montant_t2a_accorde,
                    montant_ecart_indemnisable
                FROM e_rss_lpp
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_lpp c_lpp ON lpp_id = c_lpp.oid_source;
                
                -- Erreurs de groupage --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_leg.*
                    FROM pmsi.p_rss_leg JOIN pmsi.p_rss ON p_rss_leg.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_leg'
                );

                INSERT INTO pmsi.p_rss_leg(
                    finess,
                    no_rsa,
                    rss_id,
                    code_retour_id,
                    nombre
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rsa,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    COALESCE(c_codes_retour_groupeur.oid,0) AS code_retour_id,
                    nombre
                FROM e_rss_leg
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_codes_retour_groupeur c_codes_retour_groupeur ON code_retour_id = c_codes_retour_groupeur.oid_source;
                
                -- UCD --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_ucd.*
                    FROM pmsi.p_rss_ucd JOIN pmsi.p_rss ON p_rss_ucd.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_ucd'
                );

                INSERT INTO pmsi.p_rss_ucd(
                    finess,
                    no_rss,
                    rang,
                    date_ucd,
                    ucd_id,
                    nombre,
                    coefficient_fractionnement,
                    prix_unitaire_achat,
                    prix_unitaire_ecart_indemnisable,
                    montant_ecart_indemnisable,
                    montant_facture,
                    rss_id,
                    non_pris_en_compte,
                    prix_unitaire_tr,
                    montant_tr,
                    montant_t2a_accorde,
                    type_ucd_id
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    rang,
                    date_ucd,
                    COALESCE(c_ucd.oid,0) AS ucd_id,
                    nombre,
                    coefficient_fractionnement,
                    prix_unitaire_achat,
                    prix_unitaire_ecart_indemnisable,
                    montant_ecart_indemnisable,
                    montant_facture,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    non_pris_en_compte,
                    prix_unitaire_tr,
                    montant_tr,
                    montant_t2a_accorde,
                    COALESCE(type_ucd_id, 0)
                FROM e_rss_ucd
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_ucd c_ucd ON ucd_id = c_ucd.oid_source;
                            
    
                -- TRANSFERTS --
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT *
                    FROM base.t_etablissements WHERE oid IN (SELECT etablissement_provenance_id FROM pmsi.p_rss_transferts)
                    OR oid IN (SELECT etablissement_destination_id FROM pmsi.p_rss_transferts)
                    ', 'temp e_etablissements'
                );

                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_transferts.*
                    FROM pmsi.p_rss_transferts JOIN pmsi.p_rss ON p_rss_transferts.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_transferts'
                );

                INSERT INTO base.t_etablissements (code, texte, texte_court)
                SELECT code, texte, texte_court 
                FROM e_etablissements WHERE code NOT IN (SELECT code FROM base.t_etablissements)
                ;
                
                DROP TABLE IF EXISTS c_etablissements;
                CREATE TEMP TABLE c_etablissements AS
                SELECT e_etablissements.oid AS oid_source, MAX(COALESCE(t_etablissements.oid,0)) AS oid
                FROM e_etablissements 
                    JOIN base.t_etablissements ON t_etablissements.code = e_etablissements.code
                GROUP BY 1;
                
                
				INSERT INTO pmsi.p_rss_transferts(
                    rss_id,
                    etablissement_provenance_id,
                    etablissement_destination_id
                )
                SELECT
                    c_rss.oid,
                    MAX(prov.oid),
                    MAX(dest.oid)
                FROM e_rss_transferts
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_etablissements prov ON etablissement_provenance_id = prov.oid_source
                    LEFT JOIN c_etablissements dest ON etablissement_destination_id = dest.oid_source
                GROUP BY 1
                ;


                -- Seuils Cancéros
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_cancero.*
                    FROM pmsi.p_rss_cancero WHERE cdc IN (''2017'', ''2022'')
                    ', 'temp e_rss_cancero'
                );


                INSERT INTO pmsi.p_rss_cancero(
                    rss_id,
                    activite_cancero_code,
                    activite_cancero_id,
                    activite_cancero_texte,
                    cancero_code,
                    cancero_id,
                    cancero_texte,
                    cancero_texte_court,
                    cdc
                )
                SELECT
                    c_rss_all.oid,
                    activite_cancero_code,
                    activite_cancero_id,
                    activite_cancero_texte,
                    cancero_code,
                    cancero_id,
                    cancero_texte,
                    cancero_texte_court,
                    cdc
                FROM e_rss_cancero
                    JOIN c_rss_all ON rss_id = c_rss_all.oid_source
                ;
                
                
                -- Seuils cardio
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                     SELECT 
                        p_rss_cardio.rss_id,
                        p_rss_cardio.acte_id,
                        t_etude_cardio_familles_actes.code AS cardio_familles_actes_code_source,
                        t_etude_cardio_mentions.code AS cardio_mention_code_source,
                        t_etude_cardio_modalites.code AS cardio_modalite_code_source,
                        t_listes.code AS liste_code_source,
                        p_rss_cardio.cdc,
                        p_rss_cardio.date_acte,
                        p_rss_cardio.date_sortie,
                        p_rss_cardio.finess,
                        p_rss_cardio.nombre
                      FROM pmsi.p_rss_cardio
                      JOIN pmsi.p_rss ON p_rss_cardio.rss_id = p_rss.oid
                      JOIN pmsi.t_etude_cardio_mentions ON t_etude_cardio_mentions.oid = p_rss_cardio.cardio_mention_id
                      JOIN pmsi.t_etude_cardio_modalites ON t_etude_cardio_modalites.oid = p_rss_cardio.cardio_modalite_id
                      JOIN pmsi.t_etude_cardio_familles_actes ON t_etude_cardio_familles_actes.oid = p_rss_cardio.cardio_famille_acte_id
                      JOIN pmsi.t_listes ON t_listes.oid = p_rss_cardio.liste_id
                      WHERE p_rss.en_cours = ''0''
                      AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS])
                ', 'temp e_rss_cardio'
                );


                INSERT INTO pmsi.p_rss_cardio(
                  rss_id,
                  acte_id,
                  cardio_famille_acte_id,
                  cardio_mention_id,
                  cardio_modalite_id,
                  cdc,
                  date_acte,
                  date_sortie,
                  finess,
                  liste_id,
                  nombre
                )
                SELECT
                  c_rss.oid,
                  c_actes.oid AS acte_id,
                  t_etude_cardio_familles_actes.oid AS cardio_famille_acte_id,
                  t_etude_cardio_mentions.oid AS cardio_mention_id,
                  t_etude_cardio_modalites.oid AS cardio_modalite_id,
                  e.cdc,
                  e.date_acte,
                  e.date_sortie,
                  e.finess,
                  t_listes.oid AS liste_id,
                  e.nombre
                FROM e_rss_cardio e
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    JOIN c_actes ON acte_id = c_actes.oid_source
                    JOIN pmsi.t_etude_cardio_familles_actes ON t_etude_cardio_familles_actes.code = e.cardio_familles_actes_code_source
                    JOIN pmsi.t_etude_cardio_mentions ON t_etude_cardio_mentions.code = e.cardio_mention_code_source
                    JOIN pmsi.t_etude_cardio_modalites ON t_etude_cardio_modalites.code = e.cardio_modalite_code_source
                    JOIN pmsi.t_listes ON t_listes.code = e.liste_code_source
                ;

                -- Etude Gestes Marqueurs --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_gm.*
                    FROM pmsi.p_rss_gm JOIN pmsi.p_rss ON p_rss_gm.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_gm'
                );

                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    'SELECT t_classes_sections.oid, t_classes_sections.code
                        FROM pmsi.p_rss_gm 
                        JOIN pmsi.t_classes_sections ON p_rss_gm.gm_principal_id = t_classes_sections.oid', 'temp e_classes_gm')
                ;


                DROP TABLE IF EXISTS c_classes_gm
                ;
                
                CREATE TEMP TABLE c_classes_gm AS
                    SELECT e_classes_gm.oid AS oid_source, MAX(COALESCE(t_classes_sections.oid,0)) AS oid
                    FROM e_classes_gm
                        LEFT JOIN pmsi.t_classes_sections ON e_classes_gm.code = t_classes_sections.code
                    GROUP BY 1
                ;

                INSERT INTO pmsi.p_rss_gm(
                    rss_id,
                    finess, 
                    gm_principal_id
                )
                SELECT
                    c_rss.oid,
                    finess,
                    c_classes_gm.oid
                FROM e_rss_gm
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    JOIN c_classes_gm ON gm_principal_id = c_classes_gm.oid_source
                    GROUP BY 1, 2, 3
                ;

                -- Etude IPA --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_ipa.*
                    FROM pmsi.p_rss_ipa JOIN pmsi.p_rss ON p_rss_ipa.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_ipa'
                );

                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    'SELECT oid, code FROM base.t_ipa WHERE oid <> 0', 'temp e_ipa')
                ;

                DROP TABLE IF EXISTS c_ipa
                ;
                
                CREATE TEMP TABLE c_ipa AS
                    SELECT e_ipa.oid AS oid_source, coalesce(t_ipa.oid,0) AS oid
                    FROM e_ipa 
                        LEFT JOIN base.t_ipa ON e_ipa.code = t_ipa.code
                ;

                INSERT INTO pmsi.p_rss_ipa(
                    rss_id,
                    est_maitre, 
                    nb_ipa,
                    ipa_id
                )
                SELECT
                    c_rss.oid,
                    est_maitre, 
                    nb_ipa,
                    c_ipa.oid
                FROM e_rss_ipa
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    JOIN c_ipa ON ipa_id = c_ipa.oid_source
                ;


                -- Etude SRC --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_src.*
                    FROM pmsi.p_rss_src JOIN pmsi.p_rss ON p_rss_src.oid = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_src'
                );

                INSERT INTO pmsi.p_rss_src(
                    oid,
                    age,
                    date_sortie,
                    finess,
                    no_rss,
                    rea_passage_nb_rss,
                    src_facturable_base_remboursement,
                    src_facturable_nb_prestations,
                    src_facturable_nb_rss,
                    src_facturable_regle,
                    src_facturable_regle_justificatif,
                    src_facturable_sans_src_ni_igs_nb_rss,
                    src_facturee_base_remboursement,
                    src_facturee_nb_prestations,
                    src_facturee_nb_rss,
                    src_passage_base_remboursement,
                    src_passage_duree_sejour,
                    src_passage_nb_rss
                )
                SELECT
                    c_rss.oid,
                    age,
                    date_sortie,
                    finess,
                    no_rss,
                    rea_passage_nb_rss,
                    src_facturable_base_remboursement,
                    src_facturable_nb_prestations,
                    src_facturable_nb_rss,
                    src_facturable_regle,
                    src_facturable_regle_justificatif,
                    src_facturable_sans_src_ni_igs_nb_rss,
                    src_facturee_base_remboursement,
                    src_facturee_nb_prestations,
                    src_facturee_nb_rss,
                    src_passage_base_remboursement,
                    src_passage_duree_sejour,
                    src_passage_nb_rss
                FROM e_rss_src
                    JOIN c_rss ON e_rss_src.oid = c_rss.oid_source
                ;


                -- Etude REA --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rss_rea.*
                    FROM pmsi.p_rss_rea JOIN pmsi.p_rss ON p_rss_rea.oid = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rss_rea'
                );

                INSERT INTO pmsi.p_rss_rea(
                    oid,
                    age,
                    date_sortie,
                    finess,
                    no_rss,
                    rea_passage_nb_rss,
                    rea_facturable_base_remboursement,
                    rea_facturable_nb_prestations,
                    rea_facturable_nb_rss,
                    rea_facturable_regle,
                    rea_facturable_regle_justificatif,
                    rea_facturable_sans_rea_ni_igs_nb_rss,
                    rea_facturee_base_remboursement,
                    rea_facturee_nb_prestations,
                    rea_facturee_nb_rss,
                    rea_passage_base_remboursement,
                    rea_passage_duree_sejour
                )
                SELECT
                    c_rss.oid,
                    age,
                    date_sortie,
                    finess,
                    no_rss,
                    rea_passage_nb_rss,
                    rea_facturable_base_remboursement,
                    rea_facturable_nb_prestations,
                    rea_facturable_nb_rss,
                    rea_facturable_regle,
                    rea_facturable_regle_justificatif,
                    rea_facturable_sans_rea_ni_igs_nb_rss,
                    rea_facturee_base_remboursement,
                    rea_facturee_nb_prestations,
                    rea_facturee_nb_rss,
                    rea_passage_base_remboursement,
                    rea_passage_duree_sejour
                FROM e_rss_rea
                    JOIN c_rss ON e_rss_rea.oid = c_rss.oid_source
                ;

                
                -- Etude IMPACT CMA --
                
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_etude_impact_cma.*
                    FROM pmsi.p_etude_impact_cma JOIN pmsi.p_rss ON p_etude_impact_cma.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_etude_impact_cma'
                );

                INSERT INTO pmsi.p_etude_impact_cma(
                    rss_id,
                    age,
                    ca_exh,
                    ca_ghs_dossier,
                    ca_ghs_theorique,
                    ca_perte_exb,
                    coefficient_mco,
                    duree_sejour,
                    ghm_age_cma,
                    ghm_calc,
                    ghm_dos,
                    ghs_calc,
                    ghs_dos,
                    impact_cma,
                    sev_ghm,
                    tarif_ghs_calc
                )
                SELECT
                    c_rss.oid,
                    age,
                    ca_exh,
                    ca_ghs_dossier,
                    ca_ghs_theorique,
                    ca_perte_exb,
                    coefficient_mco,
                    duree_sejour,
                    ghm_age_cma,
                    ghm_calc,
                    ghm_dos,
                    ghs_calc,
                    ghs_dos,
                    impact_cma,
                    sev_ghm,
                    tarif_ghs_calc
                FROM e_etude_impact_cma
                    JOIN c_rss ON rss_id = c_rss.oid_source
                ;

            
                -- Factures --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rsf_total.*
                    FROM pmsi.p_rsf_total JOIN pmsi.p_rss ON p_rsf_total.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rsf_total'
                );


                INSERT INTO pmsi.p_rsf_total(
                    finess,
                    no_rss,
                    code_pec,
                    rang_beneficiaire,
                    regime,
                    nature_pec,
                    justificatif_exo,
                    no_facture,
                    code_regularisation,
                    base_remboursement,
                    sejour_facture,
                    sejour_remboursable,
                    honoraires_factures,
                    honoraires_remboursable,
                    t2a_facture,
                    dmi_facture,
                    phc_facture,
                    participation_assure_avant_oc,
                    sejour_remboursable_2,
                    honoraires_remboursable_2,
                    montant_dmi_ghs2006,
                    nb_si,
                    ca_si,
                    nb_sur,
                    ca_sur,
                    nb_rea,
                    ca_rea,
                    nb_neonat,
                    ca_neonat,
                    nb_exh,
                    ca_exh,
                    nb_exb,
                    ca_exb,
                    nb_ghs,
                    ca_ghs,
                    rss_id,
                    ca_ghs_theorique,
                    taux_remboursement,
                    matricule_assure,
                    cle_matricule_assure,
                    forfait_facture,    
                    pat_benef_cmu,
                    valorise_fides,
                    no_facture_sejour_mere,
                    regime_id,
                    exoneration_tm_id,
                    nature_pec_id,
                    code_pec_id,
                    type_contrat_oc_id,
                    motif_non_facturation_id,
                    code_pec_fj_id,
                    facturation_18euros_id,
                    code_gestion,
                    no_organisme_complementaire,
                    no_at_date_adc,
                    nb_ghsmin,
                    ca_ghs_sans_coefficient
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    code_pec,
                    rang_beneficiaire,
                    regime,
                    nature_pec,
                    justificatif_exo,
                    no_facture,
                    code_regularisation,
                    base_remboursement,
                    sejour_facture,
                    sejour_remboursable,
                    honoraires_factures,
                    honoraires_remboursable,
                    t2a_facture,
                    dmi_facture,
                    phc_facture,
                    participation_assure_avant_oc,
                    sejour_remboursable_2,
                    honoraires_remboursable_2,
                    montant_dmi_ghs2006,
                    nb_si,
                    ca_si,
                    nb_sur,
                    ca_sur,
                    nb_rea,
                    ca_rea,
                    nb_neonat,
                    ca_neonat,
                    nb_exh,
                    ca_exh,
                    nb_exb,
                    ca_exb,
                    nb_ghs,
                    ca_ghs,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    ca_ghs_theorique,
                    taux_remboursement,
                    matricule_assure,
                    cle_matricule_assure,
                    forfait_facture,    
                    pat_benef_cmu,
                    valorise_fides,
                    no_facture_sejour_mere,
                    COALESCE(c_grands_regimes.oid, 0) AS regime_id,
                    COALESCE(c_exoneration_tm.oid, 0) AS exoneration_tm_id,
                    COALESCE(c_nature_assurance.oid, 0) AS nature_pec_id,
                    COALESCE(c_pec.oid, 0) AS code_pec_id,
                    COALESCE(c_type_contrat_oc.oid, 0) AS type_contrat_oc_id,
                    COALESCE(c_motif_non_facturation.oid, 0) AS motif_non_facturation_id,
                    COALESCE(c_pec_fj.oid, 0) AS code_pec_fj_id,
                    COALESCE(c_facturation_18euros.oid, 0) AS facturation_18euros_id,
                    code_gestion,
                    no_organisme_complementaire,
                    no_at_date_adc,
                    nb_ghsmin,
                    ca_ghs_sans_coefficient
                FROM e_rsf_total
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_grands_regimes ON regime_id = c_grands_regimes.oid_source
                    LEFT JOIN c_exoneration_tm ON exoneration_tm_id = c_exoneration_tm.oid_source
                    LEFT JOIN c_nature_assurance ON nature_pec_id = c_nature_assurance.oid_source
                    LEFT JOIN c_pec ON code_pec_id = c_pec.oid_source
                    LEFT JOIN c_type_contrat_oc ON type_contrat_oc_id = c_type_contrat_oc.oid_source
                    LEFT JOIN c_motif_non_facturation ON motif_non_facturation_id = c_motif_non_facturation.oid_source
                    LEFT JOIN c_pec_fj ON code_pec_fj_id = c_pec_fj.oid_source
                    LEFT JOIN c_facturation_18euros ON facturation_18euros_id = c_facturation_18euros.oid_source
                    ;
                    
                    
                -- Lignes factures --
            
                SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_rsf_detail.*
                    FROM pmsi.p_rsf_detail JOIN pmsi.p_rss ON p_rsf_detail.rss_id = p_rss.oid AND etat <> ''S'' AND  
                        (p_rss.en_cours = ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A]) OR p_rss.en_cours <> ''0'' AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS]))
                    ', 'temp e_rsf_detail'
                );


                INSERT INTO pmsi.p_rsf_detail(
                    finess,
                    no_rss,
                    nature,
                    mt,
                    dmt,
                    date_debut,
                    date_fin,
                    nombre,
                    coefficient,
                    prix_unitaire,
                    base_remboursement,
                    base_remboursement_sauf_transition,
                    taux_remboursement,
                    sejour_facture,
                    sejour_remboursable,
                    compteur,
                    ligne_t2a,
                    pec_fj,
                    coefficient_mco,
                    sejour_remboursable_2,
                    ghs_id,
                    sejour_rembourse_noemie,
                    nature_noemie,
                    prestation_id,
                    rss_id,
                    type,
                    coefficient_geo,
                    est_ligne_rss,
                    est_ligne_rum,
                    no_rum,
                    unite_medicale_id,
                    base_remboursement_rum,
                    montant_supplement_nf,
                    pec_fj_id,
                    sejour_remboursable_rum,
                    base_remboursement_rum_sauf_transition,
                    date_comptable,
                    operation_lamda,
					fides_detail
                )
                SELECT 
                    '[FINESS]' AS finess,
                    no_rss,
                    nature,
                    mt,
                    dmt,
                    date_debut,
                    date_fin,
                    nombre,
                    coefficient,
                    prix_unitaire,
                    base_remboursement,
                    base_remboursement_sauf_transition,
                    taux_remboursement,
                    sejour_facture,
                    sejour_remboursable,
                    compteur,
                    ligne_t2a,
                    pec_fj,
                    coefficient_mco,
                    sejour_remboursable_2,
                    COALESCE(c_ghs.oid,0) AS ghs_id,
                    sejour_rembourse_noemie,
                    nature_noemie,
                    COALESCE(c_prestations.oid,0) AS prestation_id,
                    COALESCE(c_rss.oid,0) AS rss_id,
                    type,
                    coefficient_geo,
                    est_ligne_rss,
                    est_ligne_rum,
                    no_rum,
                    COALESCE(c_unites_medicales.oid,0) AS unite_medicale_id,
                    base_remboursement_rum,
                    montant_supplement_nf,
                    COALESCE(c_pec_fj.oid, 0) as pec_fj_id,
                    sejour_remboursable_rum,
                    base_remboursement_rum_sauf_transition,
                    date_comptable,
                    COALESCE(operation_lamda,'0'),
					fides_detail
                FROM e_rsf_detail
                    JOIN c_rss ON rss_id = c_rss.oid_source
                    LEFT JOIN c_prestations ON prestation_id = c_prestations.oid_source
                    LEFT JOIN c_ghs ON ghs_id = c_ghs.oid_source
                    LEFT JOIN c_unites_medicales ON unite_medicale_id = c_unites_medicales.oid_source
                    LEFT JOIN c_pec_fj ON pec_fj_id = c_pec_fj.oid_source;
					
				-- EXPERT
				SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
                    SELECT p_expert_rss_controle.*, t_expert_controle.code AS expert_controle_code
                    FROM pmsi.p_expert_rss_controle
                    JOIN pmsi.t_expert_controle ON controle_id = t_expert_controle.oid 
                    JOIN pmsi.p_rss ON p_expert_rss_controle.rss_id = p_rss.oid 
                    ', 'temp e_expert_rss_controle'
                );
				
				INSERT INTO pmsi.p_expert_rss_controle(
					rss_id,
					no_rss,
					date_sortie,
					controle_id,
					date_signalement,
					no_test_datim,
					nb_rss,
					code_groupe,
					code_justificatif,
					cumul_base,
					coefficient_attendu,
					cumul_realise,
					cumul_attendu,
					borne_alerte,
					etat,
					date_correction
				)
				SELECT 
					p_rss.oid AS rss_id,
					e_expert_rss_controle.no_rss,
					e_expert_rss_controle.date_sortie,
					t_expert_controle.oid AS controle_id,
					e_expert_rss_controle.date_signalement,
					e_expert_rss_controle.no_test_datim,
					e_expert_rss_controle.nb_rss,
					e_expert_rss_controle.code_groupe,
					e_expert_rss_controle.code_justificatif,
					e_expert_rss_controle.cumul_base,
					e_expert_rss_controle.coefficient_attendu,
					e_expert_rss_controle.cumul_realise,
					e_expert_rss_controle.cumul_attendu,
					e_expert_rss_controle.borne_alerte,
					e_expert_rss_controle.etat,
					e_expert_rss_controle.date_correction
				FROM e_expert_rss_controle
				JOIN pmsi.t_expert_controle ON expert_controle_code = t_expert_controle.code
				JOIN pmsi.p_rss ON 
					e_expert_rss_controle.no_rss = p_rss.no_rss AND
					e_expert_rss_controle.date_sortie = p_rss.date_sortie AND
					p_rss.finess = '[FINESS]'
				;

                
            
                -- Simulations --
            
				SELECT base.cti_copy_table(
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    '
                    SELECT p_simulation_fg2223.*
                    FROM pmsi.p_simulation_fg2223
                        JOIN pmsi.p_rss ON 1=1
                            AND p_simulation_fg2223.rss_id = p_rss.oid
                            AND etat <> ''S''
                            AND (1!=1
                                OR (1=1
                                    AND p_rss.en_cours = ''0''
                                    AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A])
                                    )
                                OR (1=1
                                    AND p_rss.en_cours <> ''0''
                                    AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS])
                                    )
                                )
                    ',
                    'temp e_simulation_fg2223'
                    )
                ;


                INSERT INTO pmsi.p_simulation_fg2223
                    (
                        finess,
                        rss_id,
                        ghm_fg0_id,
                        ghs_fg0_id,
                        ghm_fg1_id,
                        ghs_fg1_id,
                        annee_sortie,
                        coefficient_mco_fg0,
                        coefficient_mco_fg1,
                        commentaire,
                        erreur,
                        est_envoye,
                        est_regroupe,
                        ghm_fg1_code,
                        ghs_fg1_borne_basse,
                        ghs_fg1_borne_haute,
                        ghs_fg1_code,
                        ghs_fg1_forfait_exb,
                        ghs_fg1_tarif_exb,
                        ghs_fg1_tarif_exh,
                        ghs_fg1_tarif_ghs,
                        ghs_minore_code,
                        ghs_minore_text,
                        montant_ant_fg0,
                        montant_ant_fg1,
                        montant_emi_fg0,
                        montant_emi_fg1,
                        montant_emi_fg1_deremboursees,
                        montant_eti_fg0,
                        montant_eti_fg1,
                        montant_eti_fg1_deremboursees,
                        montant_exb_fg0,
                        montant_exb_fg1,
                        montant_exh_fg0,
                        montant_exh_fg1,
                        montant_ghs_theorique_fg0,
                        montant_ghs_theorique_fg1,
                        montant_lpp_fg0,
                        montant_lpp_fg1,
                        montant_lpp_fg1_deremboursees,
                        montant_nn1_fg0,
                        montant_nn1_fg1,
                        montant_nn2_fg0,
                        montant_nn2_fg1,
                        montant_nn3_fg0,
                        montant_nn3_fg1,
                        montant_rap_fg0,
                        montant_rap_fg1,
                        montant_rea_fg0,
                        montant_rea_fg1,
                        montant_rep_fg0,
                        montant_rep_fg1,
                        montant_src_fg0,
                        montant_src_fg1,
                        montant_stf_fg0,
                        montant_stf_fg1,
                        montant_ucd_fg0,
                        montant_ucd_fg1,
                        montant_ucd_fg1_deremboursees,
                        nb_ant_fg0,
                        nb_ant_fg1,
                        nb_exb_fg1,
                        nb_exh_fg0,
                        nb_exh_fg1,
                        nb_nn1_fg0,
                        nb_nn1_fg1,
                        nb_nn2_fg0,
                        nb_nn2_fg1,
                        nb_nn3_fg0,
                        nb_nn3_fg1,
                        nb_rap_fg0,
                        nb_rap_fg1,
                        nb_rea_fg0,
                        nb_rea_fg1,
                        nb_rep_fg0,
                        nb_rep_fg1,
                        nb_sej_exb_fg0,
                        nb_sej_exb_fg1,
                        nb_src_fg0,
                        nb_src_fg1,
                        nb_stf_fg0,
                        nb_stf_fg1,
                        nb_ucd_fg0,
                        no_rss,
                        tarif_ant_fg1,
                        tarif_nn1_fg1,
                        tarif_nn2_fg1,
                        tarif_nn3_fg1,
                        tarif_rap_fg1,
                        tarif_rea_fg1,
                        tarif_src_fg1,
                        tarif_stf_fg1,
                        translation,
                        nb_sdc_fg1,
                        tarif_sdc_fg1,
                        nb_sdc_fg0,
                        tarif_sdc_fg0,
                        montant_sdc_fg1,
                        montant_sdc_fg0,
                        is_raac
                    )
                    SELECT
                        '[FINESS]' AS finess,
                        COALESCE(c_rss.oid,0) AS rss_id,
                        COALESCE(c_ghm_0.oid,0) AS ghm_fg0_id,
                        COALESCE(c_ghs_0.oid,0) AS ghs_fg0_id,
                        COALESCE(c_ghm_1.oid,0) AS ghm_fg1_id,
                        COALESCE(c_ghs_1.oid,0) AS ghs_fg1_id,
                        annee_sortie,
                        coefficient_mco_fg0,
                        coefficient_mco_fg1,
                        commentaire,
                        erreur,
                        est_envoye,
                        est_regroupe,
                        ghm_fg1_code,
                        ghs_fg1_borne_basse,
                        ghs_fg1_borne_haute,
                        ghs_fg1_code,
                        ghs_fg1_forfait_exb,
                        ghs_fg1_tarif_exb,
                        ghs_fg1_tarif_exh,
                        ghs_fg1_tarif_ghs,
                        ghs_minore_code,
                        ghs_minore_text,
                        montant_ant_fg0,
                        montant_ant_fg1,
                        montant_emi_fg0,
                        montant_emi_fg1,
                        montant_emi_fg1_deremboursees,
                        montant_eti_fg0,
                        montant_eti_fg1,
                        montant_eti_fg1_deremboursees,
                        montant_exb_fg0,
                        montant_exb_fg1,
                        montant_exh_fg0,
                        montant_exh_fg1,
                        montant_ghs_theorique_fg0,
                        montant_ghs_theorique_fg1,
                        montant_lpp_fg0,
                        montant_lpp_fg1,
                        montant_lpp_fg1_deremboursees,
                        montant_nn1_fg0,
                        montant_nn1_fg1,
                        montant_nn2_fg0,
                        montant_nn2_fg1,
                        montant_nn3_fg0,
                        montant_nn3_fg1,
                        montant_rap_fg0,
                        montant_rap_fg1,
                        montant_rea_fg0,
                        montant_rea_fg1,
                        montant_rep_fg0,
                        montant_rep_fg1,
                        montant_src_fg0,
                        montant_src_fg1,
                        montant_stf_fg0,
                        montant_stf_fg1,
                        montant_ucd_fg0,
                        montant_ucd_fg1,
                        montant_ucd_fg1_deremboursees,
                        nb_ant_fg0,
                        nb_ant_fg1,
                        nb_exb_fg1,
                        nb_exh_fg0,
                        nb_exh_fg1,
                        nb_nn1_fg0,
                        nb_nn1_fg1,
                        nb_nn2_fg0,
                        nb_nn2_fg1,
                        nb_nn3_fg0,
                        nb_nn3_fg1,
                        nb_rap_fg0,
                        nb_rap_fg1,
                        nb_rea_fg0,
                        nb_rea_fg1,
                        nb_rep_fg0,
                        nb_rep_fg1,
                        nb_sej_exb_fg0,
                        nb_sej_exb_fg1,
                        nb_src_fg0,
                        nb_src_fg1,
                        nb_stf_fg0,
                        nb_stf_fg1,
                        nb_ucd_fg0,
                        no_rss,
                        tarif_ant_fg1,
                        tarif_nn1_fg1,
                        tarif_nn2_fg1,
                        tarif_nn3_fg1,
                        tarif_rap_fg1,
                        tarif_rea_fg1,
                        tarif_src_fg1,
                        tarif_stf_fg1,
                        translation,
                        nb_sdc_fg1,
                        tarif_sdc_fg1,
                        nb_sdc_fg0,
                        tarif_sdc_fg0,
                        montant_sdc_fg1,
                        montant_sdc_fg0,
                        is_raac
                    FROM e_simulation_fg2223
                        JOIN c_rss ON rss_id = c_rss.oid_source
                        LEFT JOIN c_ghm c_ghm_0 ON ghm_fg0_id = c_ghm_0.oid_source
                        LEFT JOIN c_ghs c_ghs_0 ON ghs_fg0_id = c_ghs_0.oid_source
                        LEFT JOIN c_ghm c_ghm_1 ON ghm_fg1_id = c_ghm_1.oid_source
                        LEFT JOIN c_ghs c_ghs_1 ON ghs_fg1_id = c_ghs_1.oid_source
                ;  


				SELECT base.cti_copy_table(
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
                    '
                    SELECT p_simulation_fg2324.*
                    FROM pmsi.p_simulation_fg2324
                        JOIN pmsi.p_rss ON 1=1
                            AND p_simulation_fg2324.rss_id = p_rss.oid
                            AND etat <> ''S''
                            AND (1!=1
                                OR (1=1
                                    AND p_rss.en_cours = ''0''
                                    AND p_rss.mois_sortie IN ([MOISMODIFIES_MAT2A])
                                    )
                                OR (1=1
                                    AND p_rss.en_cours <> ''0''
                                    AND p_rss.mois_sortie IN ([MOISMODIFIES_ENCOURS])
                                    )
                                )
                    ',
                    'temp e_simulation_fg2324'
                    )
                ;

                INSERT INTO pmsi.p_simulation_fg2324
                    (
                        finess, 
                        rss_id, 
                        ghm_fg0_id, 
                        ghs_fg0_id, 
                        ghm_fg1_id,       
                        ghs_fg1_id, 
                        annee_sortie, 
                        coefficient_mco_fg0, 
                        coefficient_mco_fg1, 
                        commentaire, 
                        erreur, 
                        est_envoye, 
                        est_regroupe, 
                        ghm_fg1_code, 
                        ghs_fg1_borne_basse, 
                        ghs_fg1_borne_haute, 
                        ghs_fg1_code, 
                        ghs_fg1_forfait_exb, 
                        ghs_fg1_tarif_exb, 
                        ghs_fg1_tarif_exh, 
                        ghs_fg1_tarif_ghs, 
                        ghs_minore_code, 
                        ghs_minore_text,
                        montant_ant_fg0, 
                        montant_ant_fg1, 
                        montant_emi_fg0, 
                        montant_emi_fg1, 
                        montant_emi_fg1_deremboursees, 
                        montant_eti_fg0, 
                        montant_eti_fg1, 
                        montant_eti_fg1_deremboursees, 
                        montant_exb_fg0, 
                        montant_exb_fg1, 
                        montant_exh_fg0, 
                        montant_exh_fg1, 
                        montant_ghs_theorique_fg0, 
                        montant_ghs_theorique_fg1, 
                        montant_lpp_fg0, 
                        montant_lpp_fg1, 
                        montant_lpp_fg1_deremboursees, 
                        montant_nn1_fg0, 
                        montant_nn1_fg1, 
                        montant_nn2_fg0, 
                        montant_nn2_fg1, 
                        montant_nn3_fg0, 
                        montant_nn3_fg1, 
                        montant_rap_fg0, 
                        montant_rap_fg1, 
                        montant_rea_fg0, 
                        montant_rea_fg1, 
                        montant_rep_fg0, 
                        montant_rep_fg1, 
                        montant_src_fg0,
                        montant_src_fg1, 
                        montant_stf_fg0, 
                        montant_stf_fg1, 
                        montant_ucd_fg0, 
                        montant_ucd_fg1,
                        montant_ucd_fg1_deremboursees,
                        nb_ant_fg0, 
                        nb_ant_fg1, 
                        nb_exb_fg1, 
                        nb_exh_fg0, 
                        nb_exh_fg1, 
                        nb_nn1_fg0, 
                        nb_nn1_fg1, 
                        nb_nn2_fg0, 
                        nb_nn2_fg1, 
                        nb_nn3_fg0, 
                        nb_nn3_fg1, 
                        nb_rap_fg0, 
                        nb_rap_fg1, 
                        nb_rea_fg0, 
                        nb_rea_fg1, 
                        nb_rep_fg0, 
                        nb_rep_fg1, 
                        nb_sej_exb_fg0, 
                        nb_sej_exb_fg1,
                        nb_src_fg0, 
                        nb_src_fg1, 
                        nb_stf_fg0, 
                        nb_stf_fg1, 
                        nb_ucd_fg0, 
                        no_rss,
                        tarif_ant_fg1, 
                        tarif_nn1_fg1, 
                        tarif_nn2_fg1, 
                        tarif_nn3_fg1, 
                        tarif_rap_fg1, 
                        tarif_rea_fg1, 
                        tarif_src_fg1, 
                        tarif_stf_fg1, 
                        translation, 
                        nb_sdc_fg1, 
                        tarif_sdc_fg1, 
                        nb_sdc_fg0, 
                        tarif_sdc_fg0, 
                        montant_sdc_fg1, 
                        montant_sdc_fg0,
                        is_raac
                    )
                    SELECT
                        '[FINESS]' AS finess,
                        COALESCE(c_rss.oid,0) AS rss_id,
                        COALESCE(c_ghm_0.oid,0) AS ghm_fg0_id,
                        COALESCE(c_ghs_0.oid,0) AS ghs_fg0_id,
                        COALESCE(c_ghm_1.oid,0) AS ghm_fg1_id,
                        COALESCE(c_ghs_1.oid,0) AS ghs_fg1_id,
                        annee_sortie, 
                        coefficient_mco_fg0, 
                        coefficient_mco_fg1, 
                        commentaire, 
                        erreur, 
                        est_envoye, 
                        est_regroupe, 
                        ghm_fg1_code, 
                        ghs_fg1_borne_basse, 
                        ghs_fg1_borne_haute, 
                        ghs_fg1_code, 
                        ghs_fg1_forfait_exb, 
                        ghs_fg1_tarif_exb, 
                        ghs_fg1_tarif_exh, 
                        ghs_fg1_tarif_ghs, 
                        ghs_minore_code, 
                        ghs_minore_text,
                        montant_ant_fg0, 
                        montant_ant_fg1, 
                        montant_emi_fg0, 
                        montant_emi_fg1, 
                        montant_emi_fg1_deremboursees, 
                        montant_eti_fg0, 
                        montant_eti_fg1, 
                        montant_eti_fg1_deremboursees, 
                        montant_exb_fg0, 
                        montant_exb_fg1, 
                        montant_exh_fg0, 
                        montant_exh_fg1, 
                        montant_ghs_theorique_fg0, 
                        montant_ghs_theorique_fg1, 
                        montant_lpp_fg0, 
                        montant_lpp_fg1, 
                        montant_lpp_fg1_deremboursees, 
                        montant_nn1_fg0, 
                        montant_nn1_fg1, 
                        montant_nn2_fg0, 
                        montant_nn2_fg1, 
                        montant_nn3_fg0, 
                        montant_nn3_fg1, 
                        montant_rap_fg0, 
                        montant_rap_fg1, 
                        montant_rea_fg0, 
                        montant_rea_fg1, 
                        montant_rep_fg0, 
                        montant_rep_fg1, 
                        montant_src_fg0,
                        montant_src_fg1, 
                        montant_stf_fg0, 
                        montant_stf_fg1, 
                        montant_ucd_fg0, 
                        montant_ucd_fg1,
                        montant_ucd_fg1_deremboursees,
                        nb_ant_fg0, 
                        nb_ant_fg1, 
                        nb_exb_fg1, 
                        nb_exh_fg0, 
                        nb_exh_fg1, 
                        nb_nn1_fg0, 
                        nb_nn1_fg1, 
                        nb_nn2_fg0, 
                        nb_nn2_fg1, 
                        nb_nn3_fg0, 
                        nb_nn3_fg1, 
                        nb_rap_fg0, 
                        nb_rap_fg1, 
                        nb_rea_fg0, 
                        nb_rea_fg1, 
                        nb_rep_fg0, 
                        nb_rep_fg1, 
                        nb_sej_exb_fg0, 
                        nb_sej_exb_fg1,
                        nb_src_fg0, 
                        nb_src_fg1, 
                        nb_stf_fg0, 
                        nb_stf_fg1, 
                        nb_ucd_fg0, 
                        no_rss,
                        tarif_ant_fg1, 
                        tarif_nn1_fg1, 
                        tarif_nn2_fg1, 
                        tarif_nn3_fg1, 
                        tarif_rap_fg1, 
                        tarif_rea_fg1, 
                        tarif_src_fg1, 
                        tarif_stf_fg1, 
                        translation, 
                        nb_sdc_fg1, 
                        tarif_sdc_fg1, 
                        nb_sdc_fg0, 
                        tarif_sdc_fg0, 
                        montant_sdc_fg1, 
                        montant_sdc_fg0,
                        is_raac
                    FROM e_simulation_fg2324
                        JOIN c_rss ON rss_id = c_rss.oid_source
                        LEFT JOIN c_ghm c_ghm_0 ON ghm_fg0_id = c_ghm_0.oid_source
                        LEFT JOIN c_ghs c_ghs_0 ON ghs_fg0_id = c_ghs_0.oid_source
                        LEFT JOIN c_ghm c_ghm_1 ON ghm_fg1_id = c_ghm_1.oid_source
                        LEFT JOIN c_ghs c_ghs_1 ON ghs_fg1_id = c_ghs_1.oid_source
                ;  

            ]]></sqlcmd>
        </NODE>
        <NODE name="POST" label="Traitements complémentaires">
            <condition><![CDATA[
                "[MOISMODIFIES]" != "0"
            ]]></condition>
            <NODE name="CHECK" label="Test intégrité">
                
                <sqlcmd><![CDATA[
                    

                    DROP TABLE IF EXISTS c_checksum
                    ;
                    
                    CREATE TEMP TABLE c_checksum AS
                    SELECT 
                        p_rss.en_cours,
                        p_rss.mois_sortie, 
                        SUM(
                            1 +
                            COALESCE(p_rss.base_remboursement,0) + 
                            (COALESCE(p_rss.ca_ghs,0) + COALESCE(p_rss.ca_ghs_raac,0)) * 10 + 
                            COALESCE(p_rss.ca_exh,0) * 100 + 
                            COALESCE(p_rss.ca_exb,0) * 1000 + 
                            COALESCE(p_rss.t2a_facture,0) * 10000 + 
                            COALESCE(p_rss.dmi_facture,0) * 100000 + 
                            COALESCE(p_rss.phc_facture,0) * 1000000 +
                            COALESCE(p_rss.import_id,0) * 10000000 +
                            CASE WHEN p_rss.medecin_rss_id <> 0 THEN 100000000 ELSE 0 END +
                            base.cti_to_ascii(substr(t_prestations.code,1,3)) * 1000000000 +
                            COALESCE(p_rsf_detail.sejour_remboursable * GREATEST(p_rsf_detail.no_rum,1),0) * 10000000000 +
							COALESCE(base.cti_to_ascii(substr(t_actes.code, 1, 1) || substr(t_actes.code, 3, 1) || substr(t_actes.code, LENGTH(t_actes.code), 1)), 0) * 100000000000 +
							CASE WHEN COALESCE(p_rss_cardio.rss_id,0) <> 0 THEN 1000000000000 ELSE 0 END +
							CASE WHEN COALESCE(p_rss_cancero.rss_id,0) <> 0 THEN 10000000000000 ELSE 0 END 
                        ) AS key
                    FROM pmsi.p_rss
						LEFT JOIN pmsi.p_rsf_detail ON p_rss.oid = p_rsf_detail.rss_id AND
							COALESCE(fides_detail,0) = 0
						LEFT JOIN pmsi.p_rss_cardio ON p_rss.oid = p_rss_cardio.rss_id 
                        LEFT JOIN pmsi.p_rss_cancero ON p_rss.oid = p_rss_cancero.rss_id AND p_rss_cancero.cdc = '2022'
						LEFT JOIN pmsi.p_rss_actes ON p_rss.oid = p_rss_actes.rss_id
                        LEFT JOIN pmsi.t_prestations ON t_prestations.oid = p_rss.prestation_principale_id
					    LEFT JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id     
                    WHERE 1=1
                        AND p_rss.finess = '[FINESS]'
                        AND p_rss.etat <> 'S'
                        AND p_rss.no_rss <> 0
                        AND p_rss.mois_sortie >= [CONSO_PMSI_ANNEE_DEBUT]
                    GROUP BY 1,2
                ;
                    
                    
                    INSERT INTO e_checksum 
                    SELECT c_checksum.en_cours, c_checksum.mois_sortie, NULL
                    FROM c_checksum
                        LEFT JOIN e_checksum ON 1=1
                            AND e_checksum.mois_sortie = c_checksum.mois_sortie
                            AND e_checksum.en_cours = c_checksum.en_cours
                    WHERE e_checksum.mois_sortie IS NULL;
                    
                    CTISELECT_PROPERTY_READ 'MOISERRONES', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                    FROM e_checksum
                        LEFT JOIN c_checksum ON 1=1
                            AND e_checksum.mois_sortie = c_checksum.mois_sortie
                            AND e_checksum.en_cours = c_checksum.en_cours
                    WHERE e_checksum.key IS DISTINCT FROM c_checksum.key
                    ;

                    CTISELECT_PROPERTY_READ 'MOISERRONES_MAT2A', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                    FROM e_checksum
                            LEFT JOIN c_checksum ON 1=1
                                AND e_checksum.mois_sortie = c_checksum.mois_sortie
                                AND e_checksum.en_cours = c_checksum.en_cours
                    WHERE e_checksum.en_cours = '0' AND
                            e_checksum.key IS DISTINCT FROM c_checksum.key
                    ;
                        
                    CTISELECT_PROPERTY_READ 'MOISERRONES_ENCOURS', COALESCE(base.cti_group_concat(e_checksum.mois_sortie),'0')
                    FROM e_checksum
                        LEFT JOIN c_checksum ON 1=1
                            AND e_checksum.mois_sortie = c_checksum.mois_sortie
                            AND e_checksum.en_cours = c_checksum.en_cours
                    WHERE e_checksum.en_cours <> '0' AND
                            e_checksum.key IS DISTINCT FROM c_checksum.key
                    ;
                    
            
                ]]></sqlcmd>
            </NODE>
            <NODE name="CHECK" label="Erreur intégrité">
                <condition><![CDATA[
                    "[MOISERRONES]" != "0"
                ]]></condition>
                
                <sqlcmd><![CDATA[

                    echoerror Mois Erronés (mat2a) : [MOISERRONES_MAT2A], (fil de l'eau) : [MOISERRONES_ENCOURS];
            
                ]]></sqlcmd>
            </NODE>
        </NODE>
    </NODE>
    <NODE name="INIT" label="INITIALISATIONS">
        <NODE label="Initialisation tables">
            <sqlcmd><![CDATA[
                    
                    INSERT INTO base.t_specialites_medecin (oid, code, texte, texte_court) 
                    SELECT 0, '****', 'Non saisie' , 'Non saisie' 
                    WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin WHERE oid = 0);

                    INSERT INTO base.t_medecins(oid, code, nom, prenom, numero_ordre, specialite_id)
                    SELECT 0, '****', 'Non saisi' , '' ,'', 0
                    WHERE 0 NOT IN (SELECT oid FROM base.t_medecins WHERE oid = 0);

                    INSERT INTO pmsi.t_specialites_internes_medecin (oid, code, texte) 
                    SELECT 0, '****', 'Non saisie' 
                    WHERE 0 NOT IN (SELECT oid FROM pmsi.t_specialites_internes_medecin WHERE oid = 0);
                    
                    INSERT INTO pmsi.t_specialites_medecin (oid, code, texte) 
                    SELECT 0, '****', 'Non saisie' 
                    WHERE 0 NOT IN (SELECT oid FROM pmsi.t_specialites_medecin WHERE oid = 0);
                    
                    INSERT INTO pmsi.t_medecins (oid, code, nom, prenom) 
                    SELECT 0, '****', 'Non saisi', '' 
                    WHERE 0 NOT IN (SELECT oid FROM pmsi.t_medecins WHERE oid = 0);
                    
                    INSERT INTO pmsi.t_unites_medicales (oid, code, texte)
                    SELECT 0, '****', 'Non saisie' 
                    WHERE 0 NOT IN (SELECT oid FROM pmsi.t_unites_medicales WHERE oid = 0);
                    
                    INSERT INTO pmsi.t_unites_fonctionnelles (oid, code, texte)
                    SELECT 0, '****', 'Non saisie' 
                    WHERE 0 NOT IN (SELECT oid FROM pmsi.t_unites_fonctionnelles WHERE oid = 0);
                    
                    
                    INSERT INTO base.t_departements(oid, code, texte, texte_court) 
                    SELECT 0, '**', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECT oid FROM base.t_departements);
                    
                    INSERT INTO base.t_codes_postaux(oid, code, texte, texte_court, secteur_geographique_id, population, 
                        code_geographique_pmsi, longitude, latitude, departement_id, territoire_sante_id) 
                    SELECT 0, '*****', 'Non renseigné', 'Non renseigné', 0, 0, '', 0, 0, 0, 0 WHERE 0 NOT IN (SELECT oid FROM base.t_codes_postaux);
                    
                    INSERT INTO base.t_codes_geographiques_pmsi(oid, code, texte, texte_court, population, departement_id, territoire_sante_id) 
                    SELECT 0, '*****', 'Non renseigné', 'Non renseigné', 0, 0, 0 WHERE 0 NOT IN (SELECT oid FROM base.t_codes_geographiques_pmsi WHERE oid = 0);
                    
            ]]></sqlcmd>
        </NODE>
        <NODE label="Index médecins et patients">
            <sqlcmd><![CDATA[
        
                DROP FUNCTION IF EXISTS temp.t_medecins_key(nom text, prenom text) CASCADE;

                CREATE OR REPLACE FUNCTION temp.t_medecins_key(nom text, prenom text)
                  RETURNS text AS
                $BODY$

                DECLARE
                BEGIN
                RETURN base.cti_soundex_nom(nom || ' ' || CASE WHEN prenom <> '' THEN prenom ELSE nom END).,
                END.,
                $BODY$
                  LANGUAGE 'plpgsql' IMMUTABLE STRICT;


                CREATE INDEX i_medecins_key
                  ON pmsi.t_medecins
                  USING btree
                  (temp.t_medecins_key(nom,prenom));
                  
                DROP FUNCTION IF EXISTS temp.p_patients_key(nom text,prenom text,sexe text,date_naissance date) CASCADE;

                CREATE OR REPLACE FUNCTION temp.p_patients_key(nom text, prenom text, sexe text, date_naissance date)
                  RETURNS text AS
                $BODY$

                DECLARE
                BEGIN
                RETURN upper(translate(COALESCE(nom,'') || COALESCE(prenom,''), ' -', '')) || '|' || COALESCE(sexe,'') || '|' || COALESCE(date_naissance,'19620418').,
                END.,
                $BODY$
                  LANGUAGE 'plpgsql' IMMUTABLE STRICT;


                CREATE INDEX i_patients_key
                  ON pmsi.p_patients
                  USING btree
                  (temp.p_patients_key(nom,prenom,sexe,date_naissance));

                  
            ]]></sqlcmd>
        </NODE>
		<NODE label="Suppression données orphelines">
            <sqlcmd><![CDATA[
				-- Ménage pour tables partiellement générées ou sans reference
			   
               SELECT pmsi.cti_nettoyer_sejours(false);

			]]></sqlcmd>
        </NODE>
    </NODE>
    <NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
                

        <NODE label="Référencement des tables">
            <sqlcmd><![CDATA[
                
                TRUNCATE pmsi.p_oids;
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'finess', t_finess.oid FROM pmsi.p_rss JOIN base.t_finess ON p_rss.finess = t_finess.code GROUP BY 1,2; 

                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'medecins_rss', medecin_rss_id FROM pmsi.p_rss GROUP BY 1,2; 
                                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'medecins_acte', medecin_id FROM pmsi.p_rss_actes GROUP BY 1,2;
                
				INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'medecins_intervention', medecin_id FROM pmsi.p_rss_actes GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'diagnostics', diagnostic_id FROM pmsi.p_rss_diagnostics GROUP BY 1,2; 
                                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'actes', acte_id FROM pmsi.p_rss_actes GROUP BY 1,2; 
                                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'ghm', ghm_id FROM pmsi.p_rss GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'prestations', prestation_id FROM pmsi.p_rsf_detail GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'lpp', lpp_id FROM pmsi.p_rss_lpp GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'ucd', ucd_id FROM pmsi.p_rss_ucd GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'ghs', ghs_id FROM pmsi.p_rsf_detail GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'um', unite_medicale_id FROM pmsi.p_rss_rum GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'uf', unite_fonctionnelle_id FROM pmsi.p_rss_actes GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid)
                SELECT 'dursej', duree_sejour FROM pmsi.p_rss GROUP BY 1,2; 

                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'departement', oid FROM pmsi.t_departements 
                WHERE code in (SELECT substr(code_postal, 1, 2) FROM pmsi.p_rss GROUP BY 1) 
                GROUP BY 1,2; 
                
                INSERT INTO pmsi.p_oids (code_table, oid) 
                SELECT 'c_postaux', oid 
                FROM base.t_codes_postaux 
                WHERE code in (SELECT code_postal FROM pmsi.p_rss GROUP BY 1) 
                GROUP BY 1,2; 
                
                

                SELECT cti_cache_reload as log from cache.cti_cache_reload('iCTI_pmsi', true);
                
                    
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Tables répliquées - médecins">
            <sqlcmd><![CDATA[
                -- medecins
                DELETE FROM pmsi.t_medecins 
                WHERE 1=1 AND
                    oid NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table LIKE 'medecins_%' GROUP BY 1);
            ]]></sqlcmd>
        </NODE>
        <NODE label="Tables répliquées - patients">
            <sqlcmd><![CDATA[
                -- Patients
            
                DROP TABLE IF EXISTS w_rss_id CASCADE;
                CREATE TEMP TABLE w_rss_id AS
                SELECT
                p_rss.oid as rss_id, p_rss.patient_id, p_rss.sexe, p_rss.date_naissance, UPPER(nom) as nom, UPPER(prenom) as prenom, upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) || '|' || date_naissance || '|' || sexe AS key
                FROM pmsi.p_rss, pmsi.p_identites
                WHERE rss_id = p_rss.oid ;

                CREATE INDEX w_rss_id1 ON w_rss_id USING btree (key);
                CREATE INDEX w_rss_id2 ON w_rss_id USING btree (rss_id);
                CREATE INDEX w_rss_id3 ON w_rss_id USING btree (patient_id);

                DROP TABLE IF EXISTS w_patients_id CASCADE;
                CREATE TEMP TABLE w_patients_id AS
                SELECT
                    oid as patient_id, upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) || '|' || date_naissance || '|' || sexe AS key
                from pmsi.p_patients;

                CREATE INDEX w_patients_id1 ON w_patients_id USING btree (key);
                CREATE INDEX w_patients_id2 ON w_patients_id USING btree (patient_id);


                INSERT INTO pmsi.p_patients (nom, prenom, date_naissance, sexe)
                SELECT DISTINCT nom, prenom, date_naissance, sexe 
                FROM w_rss_id LEFT JOIN w_patients_id ON (w_rss_id.key = w_patients_id.key) 
                WHERE w_patients_id.key IS NULL;

                
                DELETE FROM pmsi.p_patients
                USING (
                    SELECT key, count(*), MAX(patient_id) as patient_id
                    FROM w_patients_id
                    GROUP BY 1
                    HAVING count(*) > 1
                ) subview
                WHERE p_patients.oid = subview.patient_id;



                DROP TABLE IF EXISTS w_patients_id CASCADE;
                CREATE TEMP TABLE w_patients_id AS
                SELECT
                    oid as patient_id, upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) || '|' || date_naissance || '|' || sexe AS key
                FROM pmsi.p_patients;

                CREATE INDEX w_patients_id1 ON w_patients_id USING btree (key);
                CREATE INDEX w_patients_id2 ON w_patients_id USING btree (patient_id);

                
                DROP TABLE IF EXISTS w_rss_patient;
                CREATE TEMP TABLE w_rss_patient AS
                SELECT w_rss_id.rss_id, w_patients_id.patient_id
                FROM w_rss_id, w_patients_id 
                WHERE w_rss_id.key = w_patients_id.key
                    AND w_rss_id.patient_id <> w_patients_id.patient_id; 

                UPDATE pmsi.p_rss SET patient_id = w_rss_patient.patient_id
                FROM w_rss_patient
                WHERE w_rss_patient.rss_id = p_rss.oid AND p_rss.patient_id <> w_rss_patient.patient_id;
            ]]></sqlcmd>
        </NODE>
        <NODE label="Tables répliquées - départements">
            <sqlcmd><![CDATA[
                INSERT INTO base.t_departements (code, texte, texte_court) 
                SELECT substr(code ,1, 2), substr(code ,1, 2), substr(code ,1, 2) FROM base.t_codes_postaux 
                WHERE substr(code ,1, 2) <> '97' AND 
                    substr(code ,1, 2) <> '98' AND 
                    substr(code ,1, 2) NOT IN (SELECT code FROM base.t_departements )
                GROUP BY 1,2,3;
            ]]></sqlcmd>
        </NODE>
        <NODE label="Tables répliquées - codes postaux">
            <sqlcmd><![CDATA[

                INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id) 
                SELECT code_postal, code_postal, code_postal, 
                    (SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 2)), substr(code_postal, 1 , 2) || '***'  , 0
                FROM pmsi.p_rss  
                WHERE code_postal <> '' AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux ) AND
                    substr(code_postal, 1 , 2) <> '97' AND substr(code_postal, 1 , 2) <> '98'
                GROUP BY 1,2,3,4,5; 
                    
                INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id) 
                SELECT code_postal, code_postal, code_postal, 
                    (SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 3)), substr(code_postal, 1 , 3) || '**', 0
                FROM pmsi.p_rss  
                WHERE code_postal <> '' AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux ) AND
                    substr(code_postal, 1 , 2) IN ('97', '98')
                GROUP BY 1,2,3,4,5; 
                
                INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id)                
                SELECT code_postal, code_postal, code_postal, 0, '*****' , 0
                FROM pmsi.p_rss 
                WHERE code_postal NOT IN (SELECT code FROM base.t_codes_postaux )
                GROUP BY 1,2,3,4,5;

                UPDATE pmsi.p_rss SET code_postal_id = t_codes_postaux.oid 
                FROM base.t_codes_postaux 
                WHERE code_postal = t_codes_postaux.code AND (code_postal_id = 0 OR code_postal_id IS NULL);
                
            ]]></sqlcmd>
        </NODE>
        <NODE label="Générations complémentaires">
            <sqlcmd><![CDATA[

                SELECT pmsi.cti_reorganize_medecins_c();

                SELECT pmsi.cti_reorganize_ghm_c();

                SELECT pmsi.cti_reorganize_actes_c();

                SELECT pmsi.cti_reorganize_durees_sejour_c();

                SELECT pmsi.cti_initialize_rss_etat();
                
                SELECT pmsi.cti_update_schema_classes('*ALL');
                
                SELECT base.cti_reorganize_codes_postaux_c('pmsi');
                
                SELECT pmsi.cti_generation_caghs_sans_coefficient();
                
            ]]></sqlcmd>
        </NODE>

        <NODE label="Insertion des Pôles">
				<sqlcmd><![CDATA[

					TRUNCATE pmsi.t_pole;

					INSERT INTO pmsi.t_pole (oid, code, texte, texte_court, section_id, section_code, section_texte)
					SELECT oid, code, texte, texte_court, section_id, section_code, section_texte
					FROM base.t_pole
					;

				]]></sqlcmd>
        </NODE>
        
        <NODE label="Dates de traitement">
            <sqlcmd><![CDATA[
                
                SELECT pmsi.cti_now('NOW','FORCE');
                SELECT pmsi.cti_now('NOWCLOTURE','FORCE');

            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Recréation statistiques BD">
            <sqlcmd><![CDATA[
                
                ANALYSE pmsi.t_medecins_c;
                ANALYSE pmsi.t_ghm_c; 
                ANALYSE pmsi.t_actes_c; 
                ANALYSE pmsi.p_rss;
                ANALYSE pmsi.p_identites;
                ANALYSE pmsi.p_rss_rum;
                ANALYSE pmsi.p_rss_diagnostics;
                ANALYSE pmsi.p_rss_actes;
                ANALYSE pmsi.p_rss_lpp;
                ANALYSE pmsi.p_rss_ucd;
                ANALYSE pmsi.p_rsf_total;
                ANALYSE pmsi.p_rsf_detail;
                ANALYSE pmsi.p_rss_cancero;
                ANALYSE pmsi.p_rss_cardio;

                    
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Expert">
            <condition><![CDATA[
                "[EXPERT]" == "1"
            ]]></condition>
            <sqlcmd><![CDATA[
                SELECT pmsi.cti_expert_execute_rules();
            ]]></sqlcmd>
        </NODE>
                
        <NODE label="Génération des essentiels">
            <condition><![CDATA[
                "[ESSENTIELS]" == "1"
            ]]></condition>
            <sqlcmd><![CDATA[
                SHELL ../../../modules/outils/dashboard/iCTI_aggregateCtiIndicators.exe;
                
            ]]></sqlcmd>
        </NODE>
    </NODE>
</ROOT>
