<?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(
                            p_rss.oid +
                            p_rss.no_rss + 
                            (COALESCE(p_rss.ca_ghs,0) + 
                            COALESCE(CASE WHEN p_rss.mois_sortie >= 202101 THEN p_rss.ca_ghs_raac ELSE 0 END,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 +
							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)) * 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(
                            p_rss.oid - fp('idx')::bigint +
                            p_rss.no_rss + 
                            (COALESCE(p_rss.ca_ghs,0) + 
                            COALESCE(CASE WHEN p_rss.mois_sortie >= 202101 THEN p_rss.ca_ghs_raac ELSE 0 END,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 +
							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)) * 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]' OR
						p_rss.oid BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
						)
                        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 '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])
					OR '[MOISFORCES]' = '999999'
                ;

                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])
					OR '[MOISFORCES]' = '999999'
                ;
                    
                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])
					OR '[MOISFORCES]' = '999999'
                ;
                
                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[
            
				DELETE FROM pmsi.p_consolidation_translation WHERE from_database ILIKE '[DBNAME]';

                -- CMD --
                SELECT merge_table('pmsi.t_cmd'::text);
                  
                -- GHM5 --  
                SELECT merge_table('pmsi.t_ghm5'::text);
                
                -- Lignes OAP --
                SELECT merge_table('pmsi.t_lignes_oap'::text);
                ;
                
                -- Groupes activité --
                SELECT merge_table('pmsi.t_groupes_activite'::text);
                
                -- GHM --
                SELECT merge_table('pmsi.t_ghm'::text);
                
                -- GHS --
				SELECT merge_table('pmsi.t_ghs'::text);
				
                -- Gestes marqueurs --
                SELECT merge_table('pmsi.t_gestes_marqueurs'::text);
				
				-- IPA --
                SELECT merge_table('base.t_ipa'::text);
				
                -- Regroupements CCAM --
                SELECT merge_table('pmsi.t_ccam_regroupements'::text);
				
                -- Actes --
                SELECT merge_table('pmsi.t_actes'::text);
				
                -- Prestations --
                SELECT merge_table('pmsi.t_prestations'::text);
				
                -- Codes retour groupeur --
                SELECT merge_table('pmsi.t_codes_retour_groupeur'::text);
				
				 -- Codes géographiques pmsi --
                SELECT merge_table('base.t_codes_geographiques_pmsi'::text);
				
                -- Prise en charge du forfait journalier --
                SELECT merge_table('base.t_pec_fj'::text);

                -- Grands régimes --
				SELECT merge_table('base.t_grands_regimes'::text);

                -- Exonération ticket modérateur --
                SELECT merge_table('base.t_exoneration_tm'::text);

                -- Nature d'assurance --
                SELECT merge_table('base.t_nature_assurance'::text);

                -- Prise en charge --
                SELECT merge_table('base.t_pec'::text);

                -- Type de contrat organisme complémentaire --
				SELECT merge_table('base.t_type_contrat_oc'::text);

                -- Motif de non facturation --
                SELECT merge_table('base.t_motif_non_facturation'::text);

                -- Facturation 18 euros --
                SELECT merge_table('base.t_facturation_18euros'::text);

                -- LPP DANS BASE--
                SELECT merge_table('base.t_lpp'::text);

                -- UCD DANS BASE--
                SELECT merge_table('base.t_ucd'::text);
                
				-- LPP --
                SELECT merge_table('pmsi.t_lpp'::text);

                -- UCD --
				SELECT merge_table('pmsi.t_ucd'::text);
              
                -- Types Autorisations --
                SELECT merge_table('pmsi.t_types_autorisations'::text);
                    
                -- Modes E/S --
				SELECT merge_table('base.t_modes_entree'::text);
				SELECT merge_table('base.t_modes_sortie'::text);
				SELECT merge_table('base.t_provenances_entree'::text);
				SELECT merge_table('base.t_destinations_sortie'::text);
              
                -- Diagnostics --                       
                SELECT merge_table('pmsi.t_diagnostics'::text);
              
                -- Spécialités (base) --
                SELECT merge_table('base.t_specialites_medecin'::text);
              
                -- 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(t_specialites_medecin_cor.cible_id,0)
                FROM e_medecins_base
                LEFT JOIN temp.t_specialites_medecin_cor ON e_medecins_base.specialite_id = t_specialites_medecin_cor.source_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
                    t_medecins.specialite_id = COALESCE(t_specialites_medecin_cor.cible_id,0)
                WHERE e_medecins_base.oid <> 0 AND
                    t_medecins.oid IS NULL;
                
                DROP TABLE IF EXISTS temp.c_medecins_base;
                CREATE TABLE temp.c_medecins_base AS
                SELECT e_medecins_base.oid AS source_id, MIN(coalesce(t_medecins.oid,0)) AS cible_id
                FROM e_medecins_base 
                    LEFT JOIN temp.t_specialites_medecin_cor ON source_id = 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 
                        t_specialites_medecin_cor.cible_id =  t_medecins.specialite_id
                GROUP BY 1;
                
                ALTER TABLE temp.c_medecins_base ADD CONSTRAINT c_medecins_base_pkey PRIMARY KEY(source_id);
                
                                        
                -- Spécialités --
                SELECT merge_table('pmsi.t_specialites_medecin'::text);
                SELECT merge_table('pmsi.t_specialites_internes_medecin'::text);
                
                -- 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');
                
                  
                --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
                    code = '[PREFIX]_'||e_medecins.code,
					nom = e_medecins.nom,
					prenom = e_medecins.prenom,
					no_adeli = e_medecins.no_adeli,
					medecin_id = COALESCE(c_medecins_base.cible_id,0),
                    specialite_id = t_specialites_medecin_cor.cible_id,
                    specialite_interne_id = t_specialites_internes_medecin_cor.cible_id
                FROM e_medecins
                    LEFT JOIN temp.c_medecins_base ON e_medecins.medecin_id = c_medecins_base.source_id
                    LEFT JOIN temp.t_specialites_medecin_cor ON e_medecins.specialite_id = t_specialites_medecin_cor.source_id
                    LEFT JOIN temp.t_specialites_internes_medecin_cor ON e_medecins.specialite_interne_id = t_specialites_internes_medecin_cor.source_id
                WHERE 1=1 
                    AND t_medecins.oid = 0
                    AND (e_medecins.oid + [IPX]) = t_medecins.oid
                    AND (
                        t_medecins.code IS DISTINCT FROM '[PREFIX]_'||e_medecins.code OR
						t_medecins.nom IS DISTINCT FROM e_medecins.nom OR
						t_medecins.prenom IS DISTINCT FROM e_medecins.prenom OR
						t_medecins.no_adeli IS DISTINCT FROM e_medecins.no_adeli OR
						t_medecins.medecin_id <> COALESCE(c_medecins_base.cible_id,0) OR
                        t_medecins.specialite_id <> t_specialites_medecin_cor.cible_id OR
                        t_medecins.specialite_interne_id <> t_specialites_internes_medecin_cor.cible_id
                        )
                ;
                
                INSERT INTO pmsi.t_medecins (
					oid,
                    code,
                    nom,
                    prenom,
                    specialite_id,
                    no_adeli,
                    statut,
                    medecin_reference_id,
                    specialite_interne_id,
                    identifiant_annuaire,
                    medecin_id
                )
                SELECT
					e_medecins.oid + [IPX],
                    '[PREFIX]_'||e_medecins.code,
                    nom,
                    COALESCE(prenom, ''::text),
                    COALESCE(t_specialites_medecin_cor.cible_id,0) AS specialite_id,
                    no_adeli,
                    statut,
                    0 AS medecin_reference_id,
                    COALESCE(t_specialites_internes_medecin_cor.cible_id,0) AS specialite_interne_id,
                    identifiant_annuaire,
                    COALESCE(c_medecins_base.cible_id,0) AS medecin_id
                FROM e_medecins
                LEFT JOIN temp.t_specialites_medecin_cor ON specialite_id = t_specialites_medecin_cor.source_id
                LEFT JOIN temp.t_specialites_internes_medecin_cor ON specialite_interne_id = t_specialites_internes_medecin_cor.source_id
                LEFT JOIN temp.c_medecins_base ON medecin_id = c_medecins_base.source_id
                WHERE e_medecins.oid <> 0 AND 
                    (e_medecins.oid + [IPX]) NOT IN (SELECT oid FROM pmsi.t_medecins)
                ;
                    
                DROP TABLE IF EXISTS temp.t_medecins_cor;
                CREATE TABLE temp.t_medecins_cor AS
                SELECT e_medecins.oid AS source_id, 
                    t_medecins.oid AS cible_id
                FROM e_medecins 
                    JOIN pmsi.t_medecins ON (e_medecins.oid + [IPX]) = t_medecins.oid
                ;

                ALTER TABLE temp.t_medecins_cor ADD CONSTRAINT c_medecins_pkey PRIMARY KEY(source_id);

                -- Unités médicales --
                SELECT merge_prod('pmsi.t_unites_medicales'::text,'AND oid != 0');
                
				UPDATE pmsi.t_unites_medicales
				SET 
					texte = texte || '([FINESS])'
				FROM temp.t_unites_medicales_cor
				WHERE oid = cible_id
				;
				
                -- Unités fonctionnelles --
                SELECT merge_prod('pmsi.t_unites_fonctionnelles'::text,'AND oid != 0');
				
				UPDATE pmsi.t_unites_fonctionnelles
				SET 
					texte = texte || '([FINESS])'
				FROM temp.t_unites_medicales_cor
				WHERE oid = cible_id
				;
				
				
                -- Codes postaux gérés dans post --
                                        
            ]]></sqlcmd>
			<NODE label="Listes et classes (Montant)">
				<condition><![CDATA[
					"[SENSPARAMETRE_CLASSE]" == "M"
				]]></condition>
				<sqlcmd><![CDATA[
				
					-- Listes
				
					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								t_listes.oid,
								t_listes.code,
								t_listes_tables.code AS table_code,
								''0''::text AS ok_liste
							FROM pmsi.t_listes
							JOIN pmsi.t_listes_tables ON t_listes.table_id = t_listes_tables.oid
							WHERE t_listes.oid IN (SELECt liste_id FROM pmsi.t_listes_contenu) AND
								contenu_by_code <> ''1'' AND t_listes.code <> ''''
						', 'temp e_listes'
					);
					
					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT * FROM pmsi.t_listes_contenu
						', 'temp e_listes_contenu'
					);
					
					UPDATE e_listes
					SET ok_liste = '1'
					WHERE table_code IN ('MEDECIN','UF','UM') AND
						code IN (SELECT code FROM pmsi.t_listes)
					;


					DELETE FROM pmsi.t_listes_contenu
					WHERE liste_id IN 
						(
						SELECT t_listes.oid
						FROM pmsi.t_listes
						JOIN pmsi.t_listes_tables ON t_listes.table_id = t_listes_tables.oid
						JOIN e_listes ON t_listes.code = e_listes.code AND 
							t_listes_tables.code = table_code
						WHERE ok_liste = '1'
						) AND
						to_id BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
					;
					
					
					INSERT INTO pmsi.t_listes_contenu (liste_id, to_id)
					SELECT 
						t_listes.oid,
						fp('idx')::bigint + to_id
					FROM e_listes_contenu
					JOIN e_listes ON e_listes_contenu.liste_id = e_listes.oid
					JOIN pmsi.t_listes ON t_listes.code = e_listes.code
					JOIN pmsi.t_listes_tables ON t_listes.table_id = t_listes_tables.oid AND t_listes_tables.code = e_listes.table_code
					WHERE ok_liste = '1'
					;
					
					
					
					
					-- Classes
					
					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								t_classes.oid,
								t_classes.code,
								t_listes_tables.code AS table_code,
								''0''::text AS ok_classe
							FROM pmsi.t_classes
							JOIN pmsi.t_listes_tables ON t_classes.table_id = t_listes_tables.oid
							WHERE t_classes.oid IN (SELECT classe_id 
										FROM pmsi.t_classes_sections 
										JOIN pmsi.t_classes_sections_elements ON section_id = t_classes_sections.oid
										) AND
								contenu_by_code <> ''1'' AND
								t_classes.code <> ''''
						', 'temp e_classes'
					);
					
					
					UPDATE e_classes
					SET ok_classe = '1'
					WHERE table_code IN ('MEDECIN','UF','UM') AND
						code IN (SELECT code FROM pmsi.t_classes)
					;
					


					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								classe_id,
								t_classes_sections.oid,
								t_classes_sections.code,
								t_classes_sections.texte
							FROM pmsi.t_classes_sections
							
						', 'temp e_classes_sections'
					);


					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								section_id,
								t_classes_sections_elements.to_id
							FROM pmsi.t_classes_sections_elements
							
						', 'temp e_classes_sections_elements'
					);


					INSERT INTO pmsi.t_classes_sections (code, texte, classe_id)
					SELECT e_classes_sections.code, e_classes_sections.texte, t_classes.oid
					FROM e_classes_sections
					JOIN e_classes ON e_classes_sections.classe_id = e_classes.oid AND e_classes.ok_classe = '1'
					JOIN pmsi.t_listes_tables ON e_classes.table_code = t_listes_tables.code
					JOIN pmsi.t_classes ON e_classes.code = t_classes.code AND t_classes.table_id = t_listes_tables.oid
					LEFT JOIN pmsi.t_classes_sections ON t_classes.oid = t_classes_sections.classe_id AND 
						t_classes_sections.code = e_classes_sections.code
						WHERE t_classes_sections.oid IS NULL
					;


					DELETE FROM pmsi.t_classes_sections_elements
						WHERE section_id IN 
						(
						SELECT t_classes_sections.oid
						FROM pmsi.t_classes
						JOIN pmsi.t_listes_tables ON t_classes.table_id = t_listes_tables.oid
						JOIN e_classes ON t_classes.code = e_classes.code AND 
							t_listes_tables.code = table_code
						JOIN pmsi.t_classes_sections ON t_classes_sections.classe_id = t_classes.oid
						WHERE ok_classe = '1'
						) AND
						to_id BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
						;


					INSERT INTO pmsi.t_classes_sections_elements (section_id, to_id)
					SELECT
						t_classes_sections.oid,
						p_consolidation_translation.to_id
					FROM e_classes_sections_elements
					JOIN e_classes_sections ON e_classes_sections_elements.section_id = e_classes_sections.oid
					JOIN e_classes ON e_classes.oid = e_classes_sections.classe_id AND ok_classe = '1'
					JOIN pmsi.t_classes ON e_classes.code = t_classes.code 
					JOIN pmsi.t_listes_tables ON t_classes.table_id = t_listes_tables.oid AND 
						e_classes.table_code = t_listes_tables.code
					JOIN pmsi.t_classes_sections ON t_classes_sections.classe_id = t_classes.oid AND
						t_classes_sections.code = e_classes_sections.code
					JOIN pmsi.p_consolidation_translation ON '[DBNAME]' = from_database 
						AND p_consolidation_translation.table_code = t_listes_tables.code
						AND from_id = e_classes_sections_elements.to_id
					GROUP BY 1,2
					;
				
				
			]]></sqlcmd>
			</NODE>
			
			<NODE label="Listes et classes (Descendant)">
				<condition><![CDATA[
					"[SENSPARAMETRE_CLASSE]" == "D"
				]]></condition>
				<sqlcmd><![CDATA[
				
					-- Listes
					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								t_listes.oid,
								t_listes.code,
								t_listes_tables.code AS table_code,
								''0''::text AS ok_liste
							FROM pmsi.t_listes
							JOIN pmsi.t_listes_tables ON t_listes.table_id = t_listes_tables.oid
							WHERE t_listes.code <> '''' AND contenu_by_code <> ''1''
						', 'temp e_listes'
					);
					
					UPDATE e_listes
					SET ok_liste = '1'
					WHERE table_code IN ('MEDECIN','RUBRIQUE','ETAGE','SERVICE_F','UF') AND 
						code IN (SELECT code FROM pmsi.t_listes)
					;
					
					-- Recopie contenu vers environnement établissement
					SELECT dblink_exec('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
						(
						SELECT base.cti_group_concat_without_sep(sqlcmd)
						FROM
							(
							SELECT '1', 'DELETE FROM pmsi.t_listes_contenu WHERE liste_id IN ('||
							(SELECT base.cti_group_concat(oid::text) FROM e_listes WHERE ok_liste = '1')||
							')., ' AS sqlcmd
							UNION
							SELECT '2', 'INSERT INTO pmsi.t_listes_contenu(liste_id, to_id) VALUES('||e_listes.oid||', '||t_listes_contenu.to_id - fp('idx')::bigint||')., '
							FROM pmsi.t_listes
							JOIN pmsi.t_listes_tables On t_listes.table_id = t_listes_tables.oid
							JOIN e_listes ON e_listes.code = t_listes.code AND
								e_listes.table_code = t_listes_tables.code
							JOIN pmsi.t_listes_contenu ON t_listes.oid = t_listes_contenu.liste_id AND
								to_id BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
							WHERE ok_liste = '1'
							ORDER BY 1
							) subview
						),
						true);
						
						
					-- classes
					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								t_classes.oid,
								t_classes.code,
								t_listes_tables.code AS table_code,
								''0''::text AS ok_classe
							FROM pmsi.t_classes
							JOIN pmsi.t_listes_tables ON t_classes.table_id = t_listes_tables.oid
							WHERE contenu_by_code <> ''1'' AND t_classes.code <> ''''
						', 'temp e_classes'
					);

					SELECT base.cti_copy_table('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', '
						SELECT 
								classe_id,
								t_classes_sections.oid,
								t_classes_sections.code,
								t_classes_sections.texte
							FROM pmsi.t_classes_sections
							
						', 'temp e_classes_sections'
					);



					UPDATE e_classes
					SET ok_classe = '1'
					WHERE code NOT LIKE 'CTI%'
					;

					SELECT dblink_exec('dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]', 
					(
					SELECT base.cti_group_concat_without_sep(sqlcmd)
					FROM
						(
						SELECT '1', 'DELETE FROM pmsi.t_classes_sections_elements WHERE section_id IN ('||
						(SELECT base.cti_group_concat(e_classes_sections.oid::text) FROM e_classes_sections JOIN e_classes ON e_classes.oid = e_classes_sections.classe_id WHERE ok_classe = '1')||
						')., ' AS sqlcmd
						UNION
						SELECT '2', 'INSERT INTO pmsi.t_classes_sections_elements(section_id, to_id) VALUES('||e_classes_sections.oid||', '||t_classes_sections_elements.to_id - fp('idx')::bigint || ')., '
						FROM pmsi.t_classes
						JOIN pmsi.t_classes_sections ON t_classes_sections.classe_id = t_classes.oid
						JOIN pmsi.t_classes_sections_elements ON t_classes_sections_elements.section_id = t_classes_sections.oid
						JOIN pmsi.t_listes_tables ON t_classes.table_id = t_listes_tables.oid
						JOIN e_classes ON t_classes.code = e_classes.code AND
							e_classes.table_code = t_listes_tables.code AND
							ok_classe = '1'
						JOIN e_classes_sections ON e_classes_sections.code = t_classes_sections.code AND
							e_classes_sections.classe_id = e_classes.oid
						WHERE t_classes_sections_elements.to_id BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
					ORDER BY 1
						) subview
					),
					true)
					;

				
			]]></sqlcmd>
			</NODE>   
	   </NODE>
        <NODE name="PRODUCTION" label="Production">
            <condition><![CDATA[
                "[MOISMODIFIES]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[
                -- coorections des oid des rss
					
				
				-- 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]' OR
						oid BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
						) 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]))
                ;
				
				SELECT base.cti_copy_table
                    (
                    'dbname=[DBNAME] port=[DBPORT] host=[DBHOST] user=[DBUSERNAME] password=[DBPASSWORD]',
                    'SELECT no_rss, date_sortie
                     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 w_rss_modifies_src'
                    )
                ;
				
                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_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_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_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_rss_rea USING w_rss_modifies WHERE p_rss_rea.oid = w_rss_modifies.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_ipa 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_etude_impact_cma USING w_rss_modifies WHERE rss_id = oid;
            
				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 w_rss_modifies WHERE rss_id = oid;

                DELETE FROM pmsi.p_rss USING w_rss_modifies WHERE p_rss.oid = w_rss_modifies.oid;
                
                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;
                        
                -- Patients --
				SELECT merge_prod('pmsi.p_patients','AND 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])))');
                 
                -- RSS --
                SELECT merge_prod('pmsi.p_rss','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])) 
                        AND etat <> ''''S''''
                        AND p_rss.no_rss <> 0');
                
                UPDATE pmsi.p_rss
                SET no_rss = 0-oid
                WHERE no_rss = 0
                ;
                
                -- identités --
                SELECT merge_prod('pmsi.p_identites','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
                
                -- ETAT --
				SELECT merge_prod('pmsi.p_rss_etat','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
				
				-- RUM --
                SELECT merge_prod('pmsi.p_rss_rum','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
				
                -- Diagnostics --
				SELECT merge_prod('pmsi.p_rss_diagnostics','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
            
                -- Actes --
                SELECT merge_prod('pmsi.p_rss_actes','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');

                -- LPP --
                 SELECT merge_prod('pmsi.p_rss_lpp','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');

                -- Erreurs de groupage --
                SELECT merge_prod('pmsi.p_rss_leg','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
                
                -- UCD --
				SELECT merge_prod('pmsi.p_rss_ucd','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
						
                -- TRANSFERTS --
                SELECT merge_prod('pmsi.p_rss_transferts','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
            
                -- Cancero --
                SELECT merge_prod('pmsi.p_rss_cancero','AND cdc = ''''2022''''
                AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');

                -- Cardio --
                SELECT merge_prod('pmsi.p_rss_cardio','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');

                -- Factures --
				SELECT merge_prod('pmsi.p_rsf_total','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
                
                SELECT merge_prod('pmsi.p_rsf_detail','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
				DROP TABLE IF EXISTS w_rsf_tmp_[FINESS];
				create  table w_rsf_tmp_[FINESS] as select * from pmsi.p_rsf_total where left(rss_id,3) = '530';
				DROP TABLE IF EXISTS w_rsf_det_tmp_[FINESS];
				create  table w_rsf_det_tmp_[FINESS] as select * from pmsi.p_rsf_detail where left(rss_id,3) = '530';
				-- Etudes
				
				SELECT merge_prod('pmsi.p_rss_rea','AND oid IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
						
				SELECT merge_prod('pmsi.p_rss_src','AND oid IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
						
				SELECT merge_prod('pmsi.p_rss_ipa','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');	
						
				SELECT merge_prod('pmsi.p_rss_gm','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');	
						
				SELECT merge_prod('pmsi.p_etude_impact_cma','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');		


                -- Simulations --

				SELECT merge_prod('pmsi.p_simulation_fg2223','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');
				SELECT merge_prod('pmsi.p_simulation_fg2324','AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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])))');

             
            ]]></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(
                            p_rss.oid - fp('idx')::bigint +
                            p_rss.no_rss + 
                            (COALESCE(p_rss.ca_ghs,0) + 
                            COALESCE(CASE WHEN p_rss.mois_sortie >= 202101 THEN p_rss.ca_ghs_raac ELSE 0 END,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 +
							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)) * 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]' OR
						p_rss.oid BETWEEN fp('idx')::bigint AND (fp('idx')::bigint + 999999999999)
						)
                        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="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 '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 'ghm', ghm_production_id 
                FROM pmsi.p_rss 
                WHERE ghm_production_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ghm')
                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 '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">
            <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);
                    
                -- 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;

            
                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;
    
    
                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 IS DISTINCT FROM t_codes_postaux.oid
				;
                
                INSERT INTO pmsi.p_oids (code_table, oid)
                SELECT 'dursej', duree_sejour FROM pmsi.p_rss GROUP BY 1,2; 
                
				
                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_rss_transferts;
				ANALYSE pmsi.p_rss_cancero;
				ANALYSE pmsi.p_rss_cardio;
                ANALYSE pmsi.p_rsf_total;
                ANALYSE pmsi.p_rsf_detail;
                
                    
            ]]></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>
