<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="PMSICOMPLEMENTS" label="RECUPERATION DES DONNEES COMPLEMENTAIRES PMSI">
		<NODE label="Tests initiaux">
			<sqlcmd><![CDATA[ 
                
				CTISELECT_PROPERTY_READ 'WITH_FACTU', count(*) 
				FROM information_schema.tables
				WHERE table_schema = 'prod_web100t' AND table_name = 'fac_fact_ligne' ;
                
				CTISELECT_PROPERTY_READ 'WITH_FACTU_RB2', CASE WHEN count(*) = 2 THEN 1 ELSE 0 END
                FROM information_schema.tables
				WHERE table_schema = 'prod_web100t' AND 
					table_name IN ('fac_fact_ligne','rb2_t4m') ;
                
			]]></sqlcmd>
		</NODE>
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[

				/**********************************************************************************
				 *                           REFERENCEMENT ETABLISSEMENT                          *
				 **********************************************************************************/
				-- Récupération des paramètres établissement
				
				-- EG utilisée dans les RUM (cas de FECAMP)
				DROP TABLE IF EXISTS w_eg;
				CREATE TEMP TABLE w_eg AS
				SELECT RES_EG
				FROM prod_web100t.DAT_RESUME
				JOIN prod_web100t.DAT_GROUPAGE ON RES_OID = GRP_RESUME
				WHERE GRP_FINESS = '[FINESS]' AND RES_EG <> 0
				GROUP BY 1;

				-- FINESS
				DROP TABLE IF EXISTS w_finess
				;

				CREATE TEMP TABLE w_finess AS
					SELECT
						fin.nd_code as finess,
						fin.nd_lib as texte,
						ets2.nd_code as code,
						ets2.nd_oid as oid,
						ets.fld_entitefacturation as entite_facturation_id
					FROM prod_web100t.sgn_nmcl_data as fin
					JOIN prod_web100t.nmcl_etablissement as ets ON ets.fld_finessgeo = fin.nd_oid
					JOIN prod_web100t.sgn_nmcl_data as ets2 ON ets2.nd_oid = ets.oid
					WHERE fin.nd_code = '[FINESS]' OR ets.oid IN (SELECT RES_EG FROM w_eg)
				;
				

				/**********************************************************************************
				 *                          MAJ SPECIALITES MEDECIN                               *
				 **********************************************************************************/

				-- Récupération des spécialites officielles
				DROP TABLE IF EXISTS w_specialite
				;
				CREATE TEMP TABLE w_specialite AS
					SELECT
						spe.nd_oid as oid,
						spe.nd_code as code,
						spe.nd_lib as texte
					FROM prod_web100t.sgn_nmcls as classe
					JOIN prod_web100t.SGN_NMCL_DATA as spe ON spe.ND_NMCL_OID = classe.NMCL_OID
					WHERE classe.NMCL_IDENT = 'SPECIALITEAMO'
				;

				-- Insertion des nouvelles spécialités officielles
				INSERT INTO pmsi.t_specialites_medecin(code, texte)
					SELECT code,texte
					FROM w_specialite
					WHERE code NOT IN (SELECT code FROM pmsi.t_specialites_medecin)
				;

				-- Màj des spécialités officielles créées via import PMSI
				UPDATE pmsi.t_specialites_medecin
				SET texte = w_specialite.texte
				FROM w_specialite
				WHERE t_specialites_medecin.code = w_specialite.code
					AND t_specialites_medecin.code = t_specialites_medecin.texte
				;

				-- Récupération des spécialites internes
				INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
					SELECT CASE WHEN length(code) = 2 THEN code || '..' ELSE code END,texte
					FROM w_specialite
					WHERE CASE WHEN length(code) = 2 THEN code || '..' ELSE code END NOT IN (SELECT code FROM pmsi.t_specialites_internes_medecin)
				;

				/**********************************************************************************
				 *                                MAJ MEDECINS                                    *
				 **********************************************************************************/
				-- Récupération des médecins
				DROP TABLE IF EXISTS w_medecin
				;

				CREATE TEMP TABLE w_medecin AS
					SELECT
						base.cti_group_array3(med.ND_OID) AS oid,
						trim(med.ND_CODE) AS code,
						max(med.ND_LIB) AS texte,
						max(med_detail.FLD_CODEADELI) AS adeli,
						max(coalesce(spe.ND_CODE,'')) AS specialite
					FROM prod_web100t.SGN_NMCLS AS classe_med
					JOIN prod_web100t.SGN_NMCL_DATA AS med ON med.ND_NMCL_OID = classe_med.NMCL_OID
					JOIN prod_web100t.NMCL_INTERVENANT AS med_detail ON med_detail.OID = med.ND_OID
					LEFT JOIN prod_web100t.SGN_NMCL_DATA AS spe ON spe.ND_OID = med_detail.FLD_SPECIALITE
					LEFT JOIN w_finess ON w_finess.oid = med.nd_etablissement
					WHERE
						classe_med.NMCL_IDENT = 'INTERVENANT'
					GROUP BY 2
				;

				CREATE INDEX w_medecin_i1
				  ON w_medecin
				  USING btree
				  (oid)
				;

				CREATE INDEX w_medecin_i2
				  ON w_medecin
				  USING btree
				  (code)
				;

				-- Insertion des nouveaux médecins
				-- @TODO Lier les spécialités établissement (= interne)
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				SELECT
					w_medecin.code,
					MAX(w_medecin.texte),
					'',
					MAX(spe.oid),
					MAX(w_medecin.adeli),
					0
				FROM w_medecin
				LEFT JOIN pmsi.t_specialites_medecin AS spe ON (spe.code = w_medecin.specialite)
				WHERE w_medecin.code NOT IN (SELECT code FROM pmsi.t_medecins WHERE code IS NOT NULL GROUP BY 1)
				GROUP BY 1
				ORDER BY 1;

				-- Mise à jour des médecins modifiés
				UPDATE pmsi.t_medecins
				SET nom = w_medecin.texte,
					prenom = ''
				FROM w_medecin
				WHERE
					t_medecins.code = w_medecin.code
					AND (
						t_medecins.nom IS DISTINCT FROM w_medecin.texte
						OR t_medecins.prenom IS DISTINCT FROM ''
					)
				;
				
				-- Spécialité interne par défaut
				UPDATE pmsi.t_medecins
					SET specialite_interne_id = t_specialites_internes_medecin.oid
				FROM pmsi.t_specialites_medecin 
				JOIN pmsi.t_specialites_internes_medecin ON 
						CASE WHEN length(t_specialites_medecin.code) = 2 THEN t_specialites_medecin.code || '..' ELSE t_specialites_medecin.code END = t_specialites_internes_medecin.code
				WHERE specialite_id = t_specialites_medecin.oid AND specialite_interne_id = 0 and specialite_id <> 0;

				
				SELECT pmsi.cti_reorganize_medecins_c()
				;

				/**********************************************************************************
				 *                             MAJ UNITES MEDICALES                               *
				 **********************************************************************************/
				-- Récupération données UM
				DROP TABLE IF EXISTS w_um
				;

				CREATE TEMP TABLE w_um AS
					SELECT
						data_um.ND_OID AS  oid,
						data_um.ND_CODE AS code,
						data_um.ND_LIB AS texte,
						substr(CASE WHEN length(auth.ND_CODE) > 0 THEN auth.ND_CODE ELSE '  ' END, 1, 3) as type_autorisation
					FROM prod_web100t.sgn_nmcls as classe_um
						JOIN prod_web100t.SGN_NMCL_DATA as data_um ON data_um.ND_NMCL_OID = classe_um.NMCL_OID
						JOIN prod_web100t.nmcl_unitemedicale as um ON um.oid = data_um.nd_oid
						LEFT JOIN prod_web100t.SGN_NMCL_DATA as auth ON auth.nd_oid = um.fld_autorisation
					WHERE
						data_um.nd_etablissement IN (SELECT oid FROM w_finess)
						AND classe_um.NMCL_IDENT = 'UNITEMEDICALE'
				;

				CREATE INDEX w_um_i1
				  ON w_um
				  USING btree
				  (oid)
				;

				CREATE INDEX w_um_i2
				  ON w_um
				  USING btree
				  (code)
				;

				-- Insertion des nouvelles UM
				INSERT INTO pmsi.t_unites_medicales(code, texte, type_autorisation)
					SELECT
						code,
						MAX(texte),
						MAX(type_autorisation)
					FROM w_um
					WHERE code NOT IN (SELECT code FROM pmsi.t_unites_medicales)
					GROUP BY 1
				;

				-- Màj libellés UM quand UM créée via import PMSI
				UPDATE pmsi.t_unites_medicales
				SET texte = w_um.texte
				FROM w_um
				WHERE
					t_unites_medicales.code = w_um.code
					AND (t_unites_medicales.texte = 'Unité ' || t_unites_medicales.code
						OR t_unites_medicales.texte = t_unites_medicales.code)
				;

				-- Màj autorisations UM
				UPDATE pmsi.t_unites_medicales
				SET type_autorisation = w_um.type_autorisation
				FROM w_um
				WHERE t_unites_medicales.code = w_um.code
				;
				

				/**********************************************************************************
				 *                             MAJ ETABLISSEMENTS                                 *
				 **********************************************************************************/
								
				DROP TABLE IF EXISTS w_SGN_NMCL_DATA;
				CREATE TEMP TABLE W_SGN_NMCL_DATA AS
				SELECT 
					NMCL_IDENT,
					ND_INVARIANT_OID,	
					(MAX(Array[ND_VALIDE_DE::text,ND_CODE]))[2] AS ND_CODE,
					(MAX(Array[ND_VALIDE_DE::text,ND_LIB]))[2] AS ND_LIB
				FROM prod_web100t.SGN_NMCL_DATA
					JOIN prod_web100t.SGN_NMCLS ON ND_NMCL_OID = NMCL_OID
				WHERE NMCL_IDENT = 'FINESS'
				GROUP BY 1,2;
	
				UPDATE base.t_etablissements
				SET
					texte = ND_LIB,
					texte_court = ND_LIB
				FROM 
					W_SGN_NMCL_DATA
				WHERE 1=1 AND
					ND_CODE =  t_etablissements.code AND 
					t_etablissements.code = t_etablissements.texte

			]]></sqlcmd>
		</NODE>
		<NODE label="Identités">
			<sqlcmd><![CDATA[
			
			
				-- Màj du n° administratif de séjour d'après PMSI
				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = RSS_NO_HOSPIT::text
				FROM prod_web100t.DAT_RESUME
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
				WHERE p_rss.no_rss = DAT_RESUME.RES_OID
					AND date(p_rss.date_sortie) = date(RES_DS_CALC)
					AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
					AND	no_sejour_administratif IS DISTINCT FROM RSS_NO_HOSPIT::text;


				-- Mise à jour n° séjour administratif pour les hors GHM
				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = DA_NUMERO
				FROM [SCHEMA].p_rsf_total
					JOIN prod_web100t.FAC_FACTURE ON base.cti_to_number(fac_FACTURE.fact_numero) = base.cti_to_number(p_rsf_total.no_facture) AND base.cti_to_number(p_rsf_total.no_facture) <> 0
					JOIN prod_web100t.DAT_DA on dat_da.da_oid = fac_FACTURE.fact_da
				WHERE  import_id = [IMPORT_ID]
					AND p_rss.oid = p_rsf_total.rss_id
					AND ghm_id = 0
					AND date(p_rss.date_sortie) = date(DA_DATE_FIN)
					AND no_sejour_administratif IS DISTINCT FROM DA_NUMERO
					 ;
					 
				/**********************************************************************************
				 *                             MAJ DES PATIENTS                                   *
				 **********************************************************************************/
                DROP TABLE IF EXISTS w_PATIENTS;
				CREATE TEMP TABLE w_PATIENTS AS
				SELECT 
					PAT_ID,
					REGEXP_REPLACE(PAT_IPP::text, '[,?]', '') AS PAT_IPP,
					CASE WHEN base.cti_to_number(REGEXP_REPLACE(PAT_IPP, '[,?]', '')) > 0 
						THEN REGEXP_REPLACE(PAT_IPP, '[,?]', '') 
						ELSE to_number('0' || REGEXP_REPLACE(PAT_IPP, '[,?]', ''),'0000000000') || '000' || PAT_ID END::bigint AS PAT_IPP_NUM,
					PAT_NOM,
					PAT_PRENOM,
					PAT_NOMNAISS,
					PAT_NAISSANCE,
					PAT_SEXE
				FROM prod_web100T.PATIENTS
				;
				
				CREATE INDEX w_PATIENTS_i1
				  ON w_PATIENTS
				  USING btree
				  (PAT_ID)
				;
				
				ANALYSE w_PATIENTS
				;
				
				-- Màj du n° de patient RSS AVEC GHM
				UPDATE [SCHEMA].p_rss
				SET no_patient = PAT_IPP_NUM
				FROM prod_web100t.DAT_RESUME
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_ID = DAT_RESUME.RES_PATIENT
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
				WHERE
					DAT_RESUME.RES_OID = p_rss.no_rss
					AND p_rss.import_id = [IMPORT_ID]
					AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
					AND PAT_IPP BETWEEN '0' AND '9999999999999999'
					AND ghm_id <> 0
					AND p_rss.date_sortie = res_ds_calc::date
					AND no_patient IS DISTINCT FROM PAT_IPP_NUM
				;

				-- Màj des n° de patient RSS SANS GHM
				UPDATE [SCHEMA].p_rss
				SET no_patient = PAT_IPP_NUM
				FROM prod_web100t.fac_FACTURE
					JOIN prod_web100t.dat_da on dat_da.da_oid = fac_FACTURE.fact_da
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_id = dat_da.da_patient
				WHERE
					dat_da.da_numero = p_rss.no_sejour_administratif
					AND base.cti_is_num(fac_FACTURE.fact_numero) 
					AND p_rss.import_id = [IMPORT_ID]
					AND PAT_IPP BETWEEN '0' AND '9999999999999999'
					AND ghm_id = 0
					--AND FACT_NUMERO NOT LIKE '%.%'
					AND position('.' in FACT_NUMERO) = 0
					AND p_rss.date_sortie = DA_DATE_FIN::date
					AND no_patient IS DISTINCT FROM PAT_IPP_NUM
				;

				
				-- Màj des noms, prénoms et nom de naissance des patients RSS AVEC GHM
				UPDATE [SCHEMA].p_identites
				SET
					nom = PAT_NOM,
					prenom = PAT_PRENOM,
					nom_naissance = PAT_NOMNAISS
				FROM [SCHEMA].p_rss
					JOIN prod_web100t.DAT_RESUME ON DAT_RESUME.RES_OID = p_rss.no_rss
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_ID = DAT_RESUME.RES_PATIENT
				WHERE
					p_identites.rss_id = p_rss.oid
					AND p_rss.import_id = [IMPORT_ID]
					AND p_identites.rss_id = p_rss.oid
					AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
					AND ghm_id <> 0
					AND p_rss.date_sortie = res_ds_calc::date
					AND (
						nom IS DISTINCT FROM PAT_NOM OR
						prenom IS DISTINCT FROM PAT_PRENOM OR
						nom_naissance IS DISTINCT FROM PAT_NOMNAISS
					)
				;

				-- Màj des noms, prénoms et nom de naissance des patients RSS SANS GHM
				UPDATE [SCHEMA].p_identites
				SET
					nom = PAT_NOM,
					prenom = PAT_PRENOM,
					nom_naissance = PAT_NOMNAISS
				FROM [SCHEMA].p_rss
					JOIN prod_web100t.dat_da ON dat_da.da_numero = p_rss.no_sejour_administratif 
					JOIN prod_web100t.fac_FACTURE ON dat_da.da_oid = fac_FACTURE.fact_da
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_id = dat_da.da_patient
				WHERE
					p_identites.rss_id = p_rss.oid
					AND base.cti_is_num(fac_FACTURE.fact_numero) 
					AND fac_FACTURE.fact_ef IN (select entite_facturation_id from w_finess)
					AND p_rss.import_id = [IMPORT_ID]
					AND ghm_id = 0
					--AND FACT_NUMERO NOT LIKE '%.%'
					AND position('.' in FACT_NUMERO) = 0
					AND p_rss.date_sortie = DA_DATE_FIN::date
					AND (
						nom IS DISTINCT FROM PAT_NOM OR
						prenom IS DISTINCT FROM PAT_PRENOM OR
						nom_naissance IS DISTINCT FROM PAT_NOMNAISS
					)
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Médecins RSS">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                          MAJ DES MEDECINS RSS                                  *
				 **********************************************************************************/
				-- Màj des medecins RSS pour les séjours AVEC GHM
				UPDATE [SCHEMA].p_rss
				SET medecin_rss_id = t_medecins.oid
				FROM prod_web100t.DAT_RESUME
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN prod_web100t.SGN_TREE_NODES on SGN_TREE_NODES.node_oid = DAT_RESUME.res_resp
					JOIN w_medecin on SGN_TREE_NODES.NODE_INVARIANT_OID = ANY(w_medecin.oid)
					JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
				WHERE
					p_rss.no_rss = DAT_RESUME.RES_OID
					AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
					AND ghm_id <> 0
					AND p_rss.date_sortie = res_ds_calc::date
					AND medecin_rss_id IS DISTINCT FROM t_medecins.oid
					AND p_rss.import_id = [IMPORT_ID]
				;
				
				
				-- D'après n° séjour	
				UPDATE [SCHEMA].p_rss
				SET medecin_rss_id = t_medecins.oid
				FROM prod_web100t.dat_da 
					JOIN prod_web100t.SGN_TREE_NODES on SGN_TREE_NODES.node_oid = dat_da.da_node_resp
					JOIN w_medecin on SGN_TREE_NODES.NODE_INVARIANT_OID = ANY(w_medecin.oid)
					JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
				WHERE
					p_rss.no_sejour_administratif = DA_NUMERO
					AND DA_EG_ENTREE IN (select oid from w_finess)
					AND medecin_rss_id = 0
					AND date_part('month',p_rss.date_sortie) = date_part('month',DA_DATE_FIN)
					AND medecin_rss_id IS DISTINCT FROM t_medecins.oid
					AND p_rss.import_id = [IMPORT_ID]
				;
					
					


			]]></sqlcmd>
		</NODE>
        <NODE label="Médecins actes externes">
            <condition><![CDATA[
                "[WITH_FACTU_RB2]" != "0"
            ]]></condition>
            <sqlcmd><![CDATA[ 
                
                -- Màj médecins actes CCAM RSS HORS GHM
                UPDATE [SCHEMA].p_rss_actes
                SET medecin_id = t_medecins.oid
                FROM [SCHEMA].p_rss
					JOIN prod_web100t.dat_sejour on sej_no_entree = p_rss.no_sejour_administratif
                    JOIN prod_web100t.fac_facture as fact on fact_da = sej_da
                    JOIN prod_web100t.fac_fact_ligne as li on li.li_facture = fact.fact_oid
                    JOIN prod_web100t.fac_fact_ligne_tier as flt on flt.flt_ligne_facture = li.li_ligne_maitre
                    JOIN prod_web100t.rb2_t4m as t4m on t4m.t4m_oid = li.li_oid
                    JOIN w_medecin ON flt.flt_intervenant = ANY(w_medecin.oid)
                    JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
                    JOIN pmsi.t_actes ON t_actes.code = substring(t4m.t4m_acteccam, 1, 7)
                WHERE
                    p_rss_actes.rss_id = p_rss.oid
                    AND p_rss_actes.acte_id = t_actes.oid
                    AND p_rss.ghm_id = 0
                    --AND FACT_NUMERO NOT LIKE '%.%'
                    AND position('.' in FACT_NUMERO) = 0
                    AND base.cti_is_num(fact.fact_numero) 
                    AND p_rss_actes.activite_ccam = t4m.t4m_activite
                    AND p_rss_actes.date_acte = flt.flt_date_fin::date
                    AND p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid
                    AND p_rss.import_id = [IMPORT_ID]
					;
            ]]></sqlcmd>
        </NODE>
        <NODE label="Médecins actes">
			<sqlcmd><![CDATA[
			/**********************************************************************************
			 *                        MAJ DES MEDECINS ACTES                                  *
			 **********************************************************************************/
			 

			-- Màj médecins actes CCAM RSS AVEC GHM, liaison sur ACT_CODE_PMSI si liaison sur DAT_ACTES.ACT_CODE ne marche pas
			UPDATE [SCHEMA].p_rss_actes SET
				medecin_id = t_medecins.oid,
				extension_ccam = CASE WHEN extension_ccam = '' THEN ACT_EXT_DOC ELSE extension_ccam END
			FROM prod_web100t.DAT_RESUME
				JOIN [SCHEMA].p_rss ON p_rss.no_rss = DAT_RESUME.RES_PARENT
				JOIN prod_web100t.DAT_ACTES ON DAT_RESUME.RES_OID = DAT_ACTES.ACT_RESUME
				JOIN pmsi.t_actes ON LEFT(DAT_ACTES.ACT_CODE_PMSI,7) = t_actes.code
				JOIN w_medecin ON ACT_EXECUTANT = ANY(w_medecin.oid)
				JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
			WHERE
				p_rss_actes.rss_id = p_rss.oid
				AND p_rss_actes.acte_id = t_actes.oid
				AND p_rss_actes.no_rum = DAT_RESUME.RES_INDEX
				AND p_rss_actes.activite_ccam = ACT_CODE_ACTIVITE
				AND p_rss_actes.date_acte = ACT_DATE::date
				AND (p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid OR extension_ccam IS DISTINCT FROM CASE WHEN extension_ccam = '' THEN ACT_EXT_DOC ELSE extension_ccam END)
				AND p_rss.import_id = [IMPORT_ID]
			;

			
			-- Màj des médecins RSS d'après les médecins actes si pas encore de médecin RSS dans p_rss 
			-- et qu'il y a des exécutants renseignés dans p_rss_actes
			-- On prend l'exécutant de l'acte avec le plus fort ICR
			DROP TABLE IF EXISTS w_executants;
			CREATE TEMP TABLE w_executants AS
			SELECT
				p_rss_actes.rss_id,
				(MAX(ARRAY[t_actes.icr_1, p_rss_actes.medecin_id]))[2] AS medecin_id
			FROM
				[SCHEMA].p_rss_actes
				JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id
				JOIN [SCHEMA].p_rss ON p_rss.oid = p_rss_actes.rss_id
			WHERE 1=1
				AND p_rss.medecin_rss_id = 0
				AND p_rss_actes.medecin_id != 0
				AND p_rss_actes.activite_ccam = '1'
			GROUP BY p_rss_actes.rss_id;
			
			UPDATE [SCHEMA].p_rss SET
				medecin_rss_id = w_executants.medecin_id
			FROM w_executants
			WHERE 1=1
				AND w_executants.rss_id = p_rss.oid
				AND p_rss.medecin_rss_id = 0;

			]]></sqlcmd>
		</NODE>
		<NODE label="Unités médicales externes">
			<sqlcmd><![CDATA[
				
				DROP TABLE IF EXISTS w_ext_um;
				CREATE TEMP TABLE w_ext_um AS
				SELECT p_rss.oid AS rss_id, MAX(MVT_UF_SOIN) AS MVT_UF_SOIN, MAX(ND_CODE) AS ND_CODE, MAX(ND_LIB) AS ND_LIB, 0::bigint AS unite_medicale_id
				FROM [SCHEMA].p_rss
					JOIN prod_web100t.dat_da ON p_rss.no_sejour_administratif = DA_NUMERO
					JOIN prod_web100t.DAT_SEJOUR ON SEJ_DA = DA_OID
					JOIN prod_web100t.REGUL_MOUVEMENTS ON PHASE_OID = MVT_SEJ_OID AND MVT_TYPE = 2
					JOIN prod_web100t.SGN_NMCL_DATA ON ND_INVARIANT_OID = MVT_UF_SOIN
				WHERE
					unite_medicale_principale_id = 0 AND
					p_rss.date_sortie = DA_DATE_FIN AND
					p_rss.ghm_id = 0
				GROUP BY 1;


				INSERT INTO pmsi.t_unites_medicales (code, texte)
				SELECT ND_CODE, ND_LIB
				FROM w_ext_um
				WHERE ND_CODE NOT IN (SELECT code FROM pmsi.t_unites_medicales)
				GROUP BY 1,2;

				UPDATE w_ext_um
				SET unite_medicale_id = t_unites_medicales.oid
				FROM pmsi.t_unites_medicales
				WHERE ND_CODE = t_unites_medicales.code;

				UPDATE [SCHEMA].p_rss
				SET unite_medicale_principale_id = unite_medicale_id
				FROM w_ext_um
				WHERE p_rss.oid = w_ext_um.rss_id;

				UPDATE [SCHEMA].p_rss_rum
				SET unite_medicale_id = w_ext_um.unite_medicale_id
				FROM w_ext_um
				WHERE p_rss_rum.rss_id = w_ext_um.rss_id;

				UPDATE [SCHEMA].p_rss_actes
				SET unite_medicale_id = w_ext_um.unite_medicale_id
				FROM w_ext_um
				WHERE p_rss_actes.rss_id = w_ext_um.rss_id;

				UPDATE [SCHEMA].p_rss_diagnostics
				SET unite_medicale_id = w_ext_um.unite_medicale_id
				FROM w_ext_um
				WHERE p_rss_diagnostics.rss_id = w_ext_um.rss_id;
			
		]]></sqlcmd>
		</NODE>
			
	</NODE>
	<NODE name="PMSIENCOURS" label="RECUPERATION DES DOSSIERS PMSI EN-COURS WEB100T">
        <NODE label="Tests initiaux">
			<sqlcmd><![CDATA[ 
                
				CTISELECT_PROPERTY_READ 'WITH_FACTU', count(*) 
				FROM information_schema.tables
				WHERE table_schema = 'prod_web100t' AND table_name = 'fac_fact_ligne' ;
				
				CTISELECT_PROPERTY_READ 'WITH_FACTU_RB2', CASE WHEN count(*) = 2 THEN 1 ELSE 0 END
                FROM information_schema.tables
				WHERE table_schema = 'prod_web100t' AND 
					table_name IN ('fac_fact_ligne','rb2_t4m') ;
                
			]]></sqlcmd>
		</NODE>
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                           REFERENCEMENT ETABLISSEMENT                          *
				 **********************************************************************************/
				-- Récupération des paramètres établissement
				
				-- EG utilisée dans les RUM (cas de FECAMP)
				DROP TABLE IF EXISTS w_eg;
				CREATE TEMP TABLE w_eg AS
				SELECT RES_EG
				FROM prod_web100t.DAT_RESUME
				JOIN prod_web100t.DAT_GROUPAGE ON RES_OID = GRP_RESUME
				WHERE GRP_FINESS = '[FINESS]' AND RES_EG <> 0
				GROUP BY 1;

				-- FINESS
				DROP TABLE IF EXISTS w_finess
				;

				CREATE TEMP TABLE w_finess AS
					SELECT
						fin.nd_code as finess,
						fin.nd_lib as texte,
						ets2.nd_code as code,
						ets2.nd_oid as oid,
						ets.fld_entitefacturation as entite_facturation_id
					FROM prod_web100t.sgn_nmcl_data as fin
					JOIN prod_web100t.nmcl_etablissement as ets ON ets.fld_finessgeo = fin.nd_oid
					JOIN prod_web100t.sgn_nmcl_data as ets2 ON ets2.nd_oid = ets.oid
					WHERE fin.nd_code = '[FINESS]' OR ets.oid IN (SELECT RES_EG FROM w_eg)
				;

				/**********************************************************************************
				 *                          MAJ SPECIALITES MEDECIN                               *
				 **********************************************************************************/

				-- Récupération des spécialites officielles
				DROP TABLE IF EXISTS w_specialite
				;
				CREATE TEMP TABLE w_specialite AS
				SELECT
					spe.nd_oid as oid,
					spe.nd_code as code,
					spe.nd_lib as texte
				from prod_web100t.sgn_nmcls as classe
				JOIN prod_web100t.SGN_NMCL_DATA as spe ON spe.ND_NMCL_OID = classe.NMCL_OID
				where classe.NMCL_IDENT = 'SPECIALITEAMO'
				;

				-- Insertion des nouvelles spécialités officielles
				INSERT INTO pmsi.t_specialites_medecin(code, texte)
				SELECT code,texte
				FROM w_specialite
				WHERE code NOT IN (SELECT code FROM pmsi.t_specialites_medecin)
				;

				-- Màj des spécialités officielles créées via import PMSI
				UPDATE pmsi.t_specialites_medecin
				SET texte = w_specialite.texte
				FROM w_specialite
				WHERE t_specialites_medecin.code = w_specialite.code
					AND t_specialites_medecin.code = t_specialites_medecin.texte
				;

				-- Récupération des spécialites internes
				INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
				SELECT CASE WHEN length(code) = 2 THEN code || '..' ELSE code END,texte
				FROM w_specialite
				WHERE CASE WHEN length(code) = 2 THEN code || '..' ELSE code END NOT IN (SELECT code FROM pmsi.t_specialites_internes_medecin)
				;

				/**********************************************************************************
				 *                                MAJ MEDECINS                                    *
				 **********************************************************************************/
				-- Récupération des médecins
				DROP TABLE IF EXISTS w_medecin
				;
				
				CREATE TEMP TABLE w_medecin AS
					SELECT
						base.cti_group_array3(med.ND_OID) AS oid,
						trim(med.ND_CODE) AS code,
						max(med.ND_LIB) AS texte,
						max(med_detail.FLD_CODEADELI) AS adeli,
						max(coalesce(spe.ND_CODE,'')) AS specialite
					FROM prod_web100t.SGN_NMCLS AS classe_med
					JOIN prod_web100t.SGN_NMCL_DATA AS med ON med.ND_NMCL_OID = classe_med.NMCL_OID
					JOIN prod_web100t.NMCL_INTERVENANT AS med_detail ON med_detail.OID = med.ND_OID
					LEFT JOIN prod_web100t.SGN_NMCL_DATA AS spe ON spe.ND_OID = med_detail.FLD_SPECIALITE
					LEFT JOIN w_finess ON w_finess.oid = med.nd_etablissement
					WHERE (w_finess.oid IS NOT NULL OR med.nd_etablissement = 0) AND
						classe_med.NMCL_IDENT = 'INTERVENANT'
					GROUP BY 2
				;

				CREATE INDEX w_medecin_i1
				  ON w_medecin
				  USING btree
				  (oid)
				;
				CREATE INDEX w_medecin_i2
				  ON w_medecin
				  USING btree
				  (code)
				;

				-- Insertion des nouveaux médecins
				-- @TODO Lier les spécialités établissement (= interne)
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
					SELECT
						w_medecin.code,
						w_medecin.texte,
						'',
						spe.oid,
						w_medecin.adeli,
						0
					FROM w_medecin
					LEFT JOIN pmsi.t_specialites_medecin AS spe ON (spe.code = w_medecin.specialite)
					WHERE w_medecin.code NOT IN (SELECT code FROM pmsi.t_medecins GROUP BY 1)
				;

				-- Mise à jour des médecins modifiés
				UPDATE pmsi.t_medecins
				SET nom = w_medecin.texte,
					prenom = ''
				FROM w_medecin
				WHERE
					t_medecins.code = w_medecin.code
					AND (
						t_medecins.nom IS DISTINCT FROM w_medecin.texte
						OR t_medecins.prenom IS DISTINCT FROM ''
					)
				;
				
				-- Spécialité interne par défaut
				UPDATE pmsi.t_medecins
					SET specialite_interne_id = t_specialites_internes_medecin.oid
				FROM pmsi.t_specialites_medecin 
				JOIN pmsi.t_specialites_internes_medecin ON 
						CASE WHEN length(t_specialites_medecin.code) = 2 THEN t_specialites_medecin.code || '..' ELSE t_specialites_medecin.code END = t_specialites_internes_medecin.code
				WHERE specialite_id = t_specialites_medecin.oid AND specialite_interne_id = 0 and specialite_id <> 0;

				
				SELECT pmsi.cti_reorganize_medecins_c()
				;

				/**********************************************************************************
				 *                             MAJ DES UNITES MEDICALES                           *
				 **********************************************************************************/
				-- Récupération données UM
				DROP TABLE IF EXISTS w_um
				;
				CREATE TEMP TABLE w_um AS
				SELECT
					data_um.ND_OID AS  oid,
					data_um.ND_CODE AS code,
					data_um.ND_LIB AS texte,
					substr(CASE WHEN length(auth.ND_CODE) > 0 THEN auth.ND_CODE ELSE '  ' END, 1, 3) as type_autorisation
				FROM prod_web100t.sgn_nmcls as classe_um
					JOIN prod_web100t.SGN_NMCL_DATA as data_um ON data_um.ND_NMCL_OID = classe_um.NMCL_OID
					JOIN prod_web100t.nmcl_unitemedicale as um ON um.oid = data_um.nd_oid
					LEFT JOIN prod_web100t.SGN_NMCL_DATA as auth ON auth.nd_oid = um.fld_autorisation
				WHERE
					data_um.nd_etablissement IN (SELECT oid FROM w_finess)
					AND classe_um.NMCL_IDENT = 'UNITEMEDICALE'
				;
				CREATE INDEX w_um_i1
				  ON w_um
				  USING btree
				  (oid)
				;
				CREATE INDEX w_um_i2
				  ON w_um
				  USING btree
				  (code)
				;

				-- Insertion des nouvelles UM
				INSERT INTO pmsi.t_unites_medicales(code, texte, type_autorisation)
				SELECT
					code,
					MAX(texte),
					MAX(type_autorisation)
				FROM w_um
				WHERE code NOT IN (SELECT code FROM pmsi.t_unites_medicales)
				GROUP BY 1
				;

				-- Màj libellés UM quand UM créée via import PMSI
				UPDATE pmsi.t_unites_medicales
				SET texte = w_um.texte
				FROM w_um
				WHERE
					t_unites_medicales.code = w_um.code
					AND (t_unites_medicales.texte = 'Unité ' || t_unites_medicales.code
						OR t_unites_medicales.texte = t_unites_medicales.code)
				;

				-- Màj autorisations UM
				UPDATE pmsi.t_unites_medicales
				SET type_autorisation = w_um.type_autorisation
				FROM w_um
				WHERE t_unites_medicales.code = w_um.code AND   
                    t_unites_medicales.type_autorisation = ''
				;

				/**********************************************************************************
				 *                           TABLE TEMP GHM                                       *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_ghm
				;

				CREATE TEMP TABLE w_ghm AS
					SELECT ND_OID AS  oid, CASE WHEN MAX(ND_CODE) NOT LIKE '90%' THEN MAX(ND_CODE) ELSE '99Z99Z' END AS code
					FROM prod_web100t.SGN_NMCL_DATA
						JOIN prod_web100t.SGN_NMCLS ON SGN_NMCLS.NMCL_OID = SGN_NMCL_DATA.ND_NMCL_OID
					WHERE SGN_NMCLS.NMCL_IDENT = 'GHM'
					GROUP BY ND_OID
				;

				INSERT INTO w_ghm
					SELECT ND_INVARIANT_OID AS  oid, MAX(ND_CODE) AS code
					FROM prod_web100t.SGN_NMCL_DATA
						JOIN prod_web100t.SGN_NMCLS ON SGN_NMCLS.NMCL_OID = SGN_NMCL_DATA.ND_NMCL_OID
					WHERE
						SGN_NMCLS.NMCL_IDENT = 'GHM'
						AND	ND_INVARIANT_OID <> ND_OID
						AND	ND_INVARIANT_OID NOT IN (SELECT oid FROM w_ghm)
					GROUP BY ND_INVARIANT_OID
				;

				CREATE INDEX w_ghm_i1
				  ON w_ghm
				  USING btree
				  (oid)
				 ;

				CREATE INDEX w_ghm_i2
				  ON w_ghm
				  USING btree
				  (code)
				 ;

				/**********************************************************************************
				 *                        		TABLE TEMP GHS                                    *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_ghs
				;

				CREATE TEMP TABLE w_ghs AS
					SELECT ND_OID AS  oid, MAX(to_number(ND_CODE,'0000')) AS code
					FROM prod_web100t.SGN_NMCL_DATA
						JOIN prod_web100t.SGN_NMCLS ON SGN_NMCLS.NMCL_OID = SGN_NMCL_DATA.ND_NMCL_OID
					WHERE SGN_NMCLS.NMCL_IDENT = 'GHS'
					GROUP BY ND_OID
				;

				INSERT INTO w_ghs
					SELECT ND_INVARIANT_OID AS  oid, MAX(to_number(ND_CODE,'0000')) AS code
					FROM prod_web100t.SGN_NMCL_DATA
						JOIN prod_web100t.SGN_NMCLS ON SGN_NMCLS.NMCL_OID = SGN_NMCL_DATA.ND_NMCL_OID
					WHERE
						SGN_NMCLS.NMCL_IDENT = 'GHS'
						AND	ND_INVARIANT_OID <> ND_OID
						AND	ND_INVARIANT_OID NOT IN (SELECT oid FROM w_ghs)
					GROUP BY ND_INVARIANT_OID
				;

				CREATE INDEX w_ghs_i1
				  ON w_ghs
				  USING btree
				  (oid)
				 ;

				CREATE INDEX w_ghs_i2
				  ON w_ghs
				  USING btree
				  (code)
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="RSS">
			<sqlcmd><![CDATA[
                /**********************************************************************************
				 *              PREPARATION TABLE PATIENTS						                  *
				 **********************************************************************************/
				 
			    DROP TABLE IF EXISTS w_PATIENTS;
				CREATE TEMP TABLE w_PATIENTS AS
				SELECT 
					PAT_ID,
					REGEXP_REPLACE(PAT_IPP::text, '[,?]', '') AS PAT_IPP,
					CASE WHEN base.cti_to_number(REGEXP_REPLACE(PAT_IPP, '[,?]', '')) > 0 
						THEN REGEXP_REPLACE(PAT_IPP, '[,?]', '') 
						ELSE to_number('0' || REGEXP_REPLACE(PAT_IPP, '[,?]', ''),'0000000000') || '000' || PAT_ID END::bigint AS PAT_IPP_NUM,
					PAT_NOM,
					PAT_PRENOM,
					PAT_NOMNAISS,
					PAT_NAISSANCE,
					PAT_SEXE
				FROM prod_web100T.PATIENTS
				;

				/**********************************************************************************
				 *              REFERENCEMENT DES RSS GROUPES DANS WEB100T						  *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_DAT_GROUPAGE
				;

				CREATE TEMP TABLE w_DAT_GROUPAGE AS
					SELECT
						GRP_RESUME AS w_GRP_RESUME,
						MAX(GRP_OID) AS w_GRP_OID,
						MAX(GRP_FINESS) AS w_GRP_FINESS
					FROM prod_web100t.DAT_GROUPAGE
					GROUP BY 1
				;

				CREATE INDEX w_DAT_GROUPAGE_i1
				  ON w_DAT_GROUPAGE
				  USING btree
				  (w_GRP_RESUME)
				;

				CREATE INDEX w_DAT_GROUPAGE_i2
				  ON w_DAT_GROUPAGE
				  USING btree
				  (w_GRP_OID)
				;

				/**********************************************************************************
				 *              REFERENCEMENT DES RSS DEJA EXISTANTS DANS i-CTI					  *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_DAT_RESUME_deja
				;

				CREATE TEMP TABLE w_DAT_RESUME_deja AS
					SELECT
						RES_HOSPIT AS w_RES_HOSPIT_deja,
						substr(mois_sortie,1,4) as annee
					FROM pmsi.p_rss
						JOIN prod_web100t.DAT_RESUME ON no_rss = DAT_RESUME.RES_OID AND
							date_trunc('month',p_rss.date_sortie) = date_trunc('month',RES_DS_CALC)
					GROUP BY 1,2
				;

				CREATE INDEX w_DAT_RESUME_deja_i1
				  ON w_DAT_RESUME_deja
				  USING btree
				  (w_RES_HOSPIT_deja)
				;
                
                INSERT INTO w_DAT_RESUME_deja
				SELECT
					RES_HOSPIT AS w_RES_HOSPIT_deja,
					substr(mois_sortie,1,4) as annee
					FROM prod_web100t.DAT_RESUME
					JOIN prod_web100t.DAT_HOSPIT ON RES_HOSPIT = HOSP_OID
					JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
					JOIN pmsi.p_rss ON RSS_NO_HOSPIT = no_sejour_administratif 
					LEFT JOIN w_DAT_RESUME_deja ON w_RES_HOSPIT_deja = RES_HOSPIT AND
						substr(mois_sortie,1,4) = annee
				WHERE date_trunc('month',date_sortie) = date_trunc('month',RES_DS_CALC) AND
					w_RES_HOSPIT_deja IS NULL
				GROUP BY 1,2
				;

				/**********************************************************************************
				 *             REFERENCEMENT DES RSS A INSERER DANS iCTI						  *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_rss
				;

				CREATE TEMP TABLE w_rss AS
					SELECT
						DAT_RESUME.RES_HOSPIT,
						MAX(DAT_RESUME.RES_OID) AS RES_OID,
						MAX(DAT_RESUME.RES_DS_CALC) AS RES_DS,
						MAX(DAT_RESUME.RES_DE_CALC) AS RES_DE,
						MAX(DAT_RESUME.RES_PATIENT) AS RES_PATIENT,
						MAX(w_GRP_FINESS) AS finess,
						MAX(w_GRP_OID) AS GRP_OID,
						MAX(COALESCE(DA_OID,0)) AS DA_OID,
						MAX(DAT_RUM.RUM_AGE_GEST::numeric) AS RUM_AGE_GEST,
						MAX(DAT_RUM.RUM_DERNIERES_REGLES::date) AS RUM_DERNIERES_REGLES,
						MAX(DAT_DA.DA_DIM_VALID) AS w_DA_DIM_VALID,
						MAX(CASE WHEN DAT_RUM.RUM_RESCRIT_TARIFAIRE = 1 THEN 1 WHEN DAT_RUM.RUM_RESCRIT_TARIFAIRE = 0 THEN 2 ELSE 0 END) AS w_rescrit_tarif_id,
						MAX(CASE WHEN DAT_RUM.RUM_CONTEXTE_PATIENT_CALC = 1 THEN 1 WHEN DAT_RUM.RUM_CONTEXTE_PATIENT_CALC = 0 THEN 2 ELSE 0 END) AS w_contexte_pat_id,
						MAX(CASE WHEN DAT_RUM.RUM_ADMINISTRATION_RH_CALC = 1 THEN 1 WHEN DAT_RUM.RUM_ADMINISTRATION_RH_CALC = 0 THEN 2 ELSE 0 END) AS w_adm_prod_reshospi_id,
						MAX(COALESCE(DAT_RUM.RUM_CAT_NB_INTERVENTIONS_CALC,0)) AS w_nb_intervention_id,
						MAX(CASE WHEN DAT_RUM.RUM_ADNP_CALC = 1 THEN 1 WHEN DAT_RUM.RUM_ADNP_CALC = 0 THEN 2 ELSE 0 END) AS w_np_id,
						MAX(COALESCE(RES_REF.RES_URGENCE_CALC,0)) AS PASSAGE_URGENCES_OID,
						MAX(DAT_RUM.RUM_RAAC) AS raac,
						nextval('pmsi.s_rss'::regclass) AS rss_id
					FROM prod_web100t.DAT_RESUME
						JOIN w_DAT_GROUPAGE ON RES_OID = w_GRP_RESUME
						JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
						JOIN prod_web100t.DAT_HOSPIT ON RES_HOSPIT = HOSP_OID
						JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
						LEFT JOIN prod_web100t.DAT_RESUME RES_REF ON RES_REF.RES_PARENT = DAT_RESUME.RES_OID
						LEFT JOIN prod_web100t.DAT_RUM on DAT_RUM.RUM_OID = RES_REF.RES_OID
						LEFT JOIN prod_web100t.DAT_DA ON DA_NUMERO = RSS_NO_HOSPIT
						LEFT JOIN w_DAT_RESUME_deja ON 1=1
							AND DAT_RESUME.RES_HOSPIT = w_RES_HOSPIT_deja
							AND w_DAT_RESUME_deja.annee = to_char(DAT_RESUME.RES_DS_CALC, 'YYYY')
					WHERE 1=1
						AND DAT_RESUME.RES_DS_CALC BETWEEN '[ANNEE]0101' AND ('[ANNEE]1231'::date + '10 years'::interval)::date
						AND DAT_RESUME.RES_OID > 0
						AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
						AND w_RES_HOSPIT_deja IS NULL
					GROUP BY 1
                    HAVING MAX(w_GRP_FINESS) = '[FINESS]'
					ORDER BY 2
				;

				CREATE INDEX w_rss_i1
				  ON w_rss
				  USING btree
				  (RES_OID)
				;

				CREATE INDEX w_rss_i2
				  ON w_rss
				  USING btree
				  (GRP_OID)
				;

				CREATE INDEX w_rss_i3
				  ON w_rss
				  USING btree
				  (RES_PATIENT)
				;
				
				CREATE INDEX w_rss_i4
				  ON w_rss
				  USING btree
				  (DA_OID)
				;
                
                DROP TABLE IF EXISTS w_SGN_NMCL_DATA;
                CREATE TEMP TABLE W_SGN_NMCL_DATA AS
                SELECT 
                    DISTINCT ND_INVARIANT_OID,
                    first_value(ND_CODE) OVER w as ND_CODE,
                    first_value(ND_LIB) OVER w as ND_LIB
                FROM prod_web100t.SGN_NMCL_DATA
                    JOIN prod_web100t.SGN_NMCLS ON ND_NMCL_OID = NMCL_OID
                WHERE SGN_NMCLS.NMCL_IDENT = 'ERREURMCO'
                WINDOW w AS (PARTITION BY ND_INVARIANT_OID ORDER BY ND_VALIDE_DE DESC)
                ORDER BY ND_CODE
                    ;
                
				/**********************************************************************************
				 *  			         INSERTION DES NOUVEAUX RSS							      *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss (
						finess,
						oid,
						no_rss,
						no_patient,
						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,
						no_rum_principal,
						unite_medicale_principale_id,
						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,
						age_gestationnel,
						date_dernieres_regles,
						from_oid,
						rescrit_tarif_id,
						contexte_pat_id,
						adm_prod_reshospi_id,
						nb_intervention_id,
						np_id,
						raac_id,
						passage_urgences_code
						)
					SELECT
						w_rss.finess AS finess,
						w_rss.rss_id AS oid,
						w_rss.RES_OID AS no_rss,
						PAT_IPP_NUM AS no_patient,
						'' AS version_groupage,
						PATIENTS.PAT_NAISSANCE AS date_naissance,
						PATIENTS.PAT_SEXE AS sexe,
						DAT_RESUME.RES_DE_CALC AS date_entree,
						DAT_RESUME.RES_DS_CALC AS date_sortie,
						substr(DAT_RESUME.RES_ME_PMSI,1,1) AS mode_entree,
						substr(DAT_RESUME.RES_ME_PMSI,2,1) AS provenance,
						substr(DAT_RESUME.RES_MS_PMSI,1,1) AS mode_sortie,
						substr(DAT_RESUME.RES_MS_PMSI,2,1) AS destination,
						DAT_INFO_PATIENT.PAT_CODE_POSTAL AS code_postal,
						0 AS poids_bebe,
						0 AS igs2,
						'' AS cma,
						substr(w_ghm.code , 3 , 1) AS groupe_ghm,
						CASE
							WHEN RES_DS_CALC > RES_DE_CALC
								THEN date(RES_DS_CALC) - date(RES_DE_CALC)
							ELSE 0
						END AS duree_sejour,
						CASE
							WHEN substr(w_ghm.code,1,2) = '28'
								THEN RES_SEANCES
							ELSE 1
						END AS nb_rsa,
						CASE
							WHEN RES_DS_CALC > PATIENTS.PAT_NAISSANCE
								THEN trunc((date(RES_DE_CALC) - date(PATIENTS.PAT_NAISSANCE)) / 365.25,0)
							ELSE 0
						END AS age,
						'' AS supprime,
						now() AS date_import,
						RSS_NBRE_RUM AS nb_rum,
						'' AS secteur,
						COALESCE(RSS_NO_HOSPIT::text,''::text) AS no_sejour_administratif,
						CASE
							WHEN substr(w_ghm.code,1,2) = '28'
								THEN RES_SEANCES
							ELSE 0
						END AS nb_seances,
						'' AS ghm_fg9,
						COALESCE(t_ghm.oid, 0) AS ghm_id,
						COALESCE(t_medecins.oid,0) AS medecin_rss_id,
						COALESCE(t_ghs.oid, 0) AS ghs_id,
						date_part('year', RES_DS_CALC) * 100 + date_part('month', RES_DS_CALC) AS mois_sortie,
						0 AS diagnostic_principal_id,
						0 AS diagnostic_relie_id,
						1 AS no_rum_principal,
						0 AS unite_medicale_principale_id,
						-1 AS import_id,
						'' AS etat,
						0 AS acte_principal_id,
						0 AS code_postal_id,
						0 AS patient_id,
						0 AS prestation_principale_id,
						'' AS severite_fg11_simulation_code,
						'1' AS en_cours,
						CASE
							WHEN length(w_ghm.code) = 6 AND substr(w_ghm.code,1,2) <> '90' AND substr(w_ghm.code,1,2) <> '99' AND GRP_CORRECT = 1 AND w_DA_DIM_VALID IS DISTINCT FROM NULL
								THEN 'V'
							WHEN length(w_ghm.code) = 6 AND substr(w_ghm.code,1,2) <> '90' AND substr(w_ghm.code,1,2) <> '99'
								THEN 'G'
							ELSE 'S'
						END AS en_cours_etat,
						0 AS base_remboursement,
						0 AS sejour_facture,
						0 AS honoraires_factures,
						0 AS t2a_facture,
						0 AS dmi_facture,
						0 AS phc_facture,
						0 AS ca_ghs_theorique,
						0 AS nb_ghs,
						0 AS ca_ghs,
						0 AS nb_exb,
						0 AS ca_exb, 
						0 AS nb_exh,
						0 AS ca_exh,
						0 AS nb_si,
						0 AS ca_si,
						0 AS nb_sur,
						0 AS ca_sur,
						0 AS nb_rea,
						0 AS ca_rea,
						0 AS nb_neonat,
						0 AS ca_neonat,
						'' AS traitement_epmsi,
						COALESCE(CASE WHEN w_SGN_NMCL_DATA.ND_CODE ~'[A-Z][0-9]*' THEN substring(w_SGN_NMCL_DATA.ND_CODE,2) ELSE w_SGN_NMCL_DATA.ND_CODE END,'') AS code_retour_groupage,
						0 AS comite_medical_id,
						'0' AS rehosp_meme_ghm,
						COALESCE(RUM_AGE_GEST, 0),
						RUM_DERNIERES_REGLES,
						0 AS from_oid,
						w_rescrit_tarif_id,
						w_contexte_pat_id,
						w_adm_prod_reshospi_id,
						w_nb_intervention_id,
						w_np_id,
						COALESCE(t_raac.oid, 0),
						COALESCE(t_passage_urgences.code, '')
					FROM prod_web100t.DAT_RESUME
						JOIN w_rss ON (DAT_RESUME.RES_OID = w_rss.RES_OID)
						JOIN w_PATIENTS PATIENTS ON (w_rss.RES_PATIENT = PATIENTS.PAT_ID)
						JOIN prod_web100t.DAT_INFO_PATIENT ON (w_rss.RES_PATIENT = DAT_INFO_PATIENT.PAT_OID)
						JOIN prod_web100t.DAT_GROUPAGE ON w_rss.GRP_OID = DAT_GROUPAGE.GRP_OID
						LEFT JOIN prod_web100t.DAT_RSS ON w_rss.RES_OID = RSS_OID
						LEFT JOIN w_ghm ON w_ghm.oid = GRP_GHM
						LEFT JOIN w_ghs ON w_ghs.oid = GRP_CODE_GHS
						LEFT JOIN pmsi.t_ghm ON (w_ghm.code = t_ghm.code)
						LEFT JOIN pmsi.t_ghs ON (w_ghs.code = t_ghs.code)
						LEFt JOIN prod_web100t.SGN_TREE_NODES ON NODE_OID = RES_RESP
						LEFT JOIN w_medecin ON SGN_TREE_NODES.NODE_INVARIANT_OID = ANY(w_medecin.oid)
						LEFT JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
						LEFT JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = GRP_ERROR
						LEFT JOIN pmsi.t_raac ON t_raac.code = w_rss.raac
						LEFT JOIN pmsi.t_passage_urgences ON t_passage_urgences.oid = w_rss.PASSAGE_URGENCES_OID
					WHERE w_rss.finess =  '[FINESS]'
				;
				
				UPDATE pmsi.p_rss
				SET no_rum_principal = RES_INDEX
				FROM prod_web100t.DAT_RSS
				JOIN prod_web100t.DAT_RESUME ON RSS_OID_RUM_CLASSANT = RES_OID
				WHERE p_rss.no_rss = RSS_OID AND
					en_cours = '1' AND
					RES_INDEX > 1
				;

				/**********************************************************************************
				 *           REAFFECTATION DES RSS MERE ASSOCIES AUX BEBES (CMD 14 et 15)		  *
				 **********************************************************************************/

				
				-- On récupère les no_rss des bébé et mère qui sont liés ensemble
				DROP TABLE IF EXISTS w_BB;

				CREATE TEMP TABLE w_BB AS (
					SELECT DAT_RESUME.RES_OID AS NO_RSS_BB, DAT_RESUME.RES_NUM AS NO_ADMINISTRATIF_BB, DAT_RUM.RUM_OID AS RUM_OID_BB, DAT_RUM.RUM_MERE_OID 
						FROM prod_web100t.DAT_RESUME
						LEFT JOIN prod_web100t.DAT_RESUME RES_REF ON RES_REF.RES_PARENT = DAT_RESUME.RES_OID 
						LEFT JOIN prod_web100t.DAT_RUM on DAT_RUM.RUM_OID = RES_REF.RES_OID
					WHERE DAT_RUM.RUM_MERE_OID <> 0
					AND DAT_RESUME.RES_DS_CALC BETWEEN '[ANNEE]0101' AND ('[ANNEE]1231'::date + '10 years'::interval)::date					);
					
					
				DROP TABLE IF EXISTS w_BB_MERE;

				CREATE TEMP TABLE w_BB_MERE AS (
					SELECT NO_RSS_BB, NO_ADMINISTRATIF_BB, RES_MERE.RES_OID AS NO_RSS_MERE, RES_MERE.RES_NUM AS NO_ADMINISTRATIF_MERE
					FROM w_bb  
						JOIN prod_web100t.DAT_RUM RUM_MERE ON w_bb.RUM_MERE_OID = RUM_MERE.RUM_OID
						JOIN prod_web100t.DAT_RESUME RES_REF_MERE ON RES_REF_MERE.RES_OID = RUM_MERE.RUM_OID
						JOIN prod_web100t.DAT_RESUME RES_MERE ON RES_REF_MERE.RES_PARENT = RES_MERE.RES_OID
						ORDER BY 1
				)
				;

				-- On assigne le rss_id de la mère dans la ligne rss du bébé
				WITH w_ids AS(
					SELECT no_rss_bb , oid as w_rss_mere_id
					FROM w_BB_MERE
					JOIN pmsi.p_rss ON NO_RSS_MERE = no_rss
					WHERE import_id = -1 
				)
				UPDATE pmsi.p_rss
				SET rss_mere_id = w_rss_mere_id
					FROM w_ids
					WHERE p_rss.no_rss = w_ids.no_rss_bb
					AND w_rss_mere_id IS DISTINCT FROM rss_mere_id
					AND import_id = -1 
				;


				INSERT INTO pmsi.p_rss_leg (finess, no_rsa, rss_id, code_retour_id, nombre)
				SELECT
					finess
					, 0 AS no_rsa
					, p_rss.oid AS rss_id
					, t_codes_retour_groupeur.oid
					, 1
				FROM prod_web100t.DAT_RESUME
					JOIN prod_web100t.DAT_GROUPAGE ON DAT_RESUME.RES_OID = DAT_GROUPAGE.GRP_RESUME
					JOIN prod_web100t.DAT_RSS ON DAT_RESUME.RES_OID = RSS_OID
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = GRP_ERROR
					JOIN pmsi.t_codes_retour_groupeur ON t_codes_retour_groupeur.type || t_codes_retour_groupeur.code = w_SGN_NMCL_DATA.ND_CODE
					JOIN pmsi.p_rss ON RSS_NO_HOSPIT::text = no_sejour_administratif
				WHERE GRP_ERROR IS NOT NULL
					AND import_id = -1
					AND finess = '[FINESS]'
				;

				-- transferts d'établissements 
				DROP TABLE IF EXISTS w_SGN_NMCL_DATA;
				CREATE TEMP TABLE W_SGN_NMCL_DATA AS
				SELECT 
					NMCL_IDENT,
					ND_INVARIANT_OID,	
					(MAX(Array[ND_VALIDE_DE::text,ND_CODE]))[2] AS ND_CODE,
					(MAX(Array[ND_VALIDE_DE::text,ND_LIB]))[2] AS ND_LIB
				FROM prod_web100t.SGN_NMCL_DATA
					JOIN prod_web100t.SGN_NMCLS ON ND_NMCL_OID = NMCL_OID
				WHERE NMCL_IDENT = 'FINESS'
				GROUP BY 1,2;
				
				INSERT INTO base.t_etablissements (code, texte, texte_court)
				SELECT
					ND_CODE,
					ND_LIB,
					ND_LIB
				FROM 
					w_SGN_NMCL_DATA
				WHERE 1=1 AND
					NMCL_IDENT = 'FINESS' AND
					ND_INVARIANT_OID IN (SELECT DISTINCT MVT_AUTRE_ETS FROM prod_web100t.REGUL_MOUVEMENTS) AND
					ND_CODE NOT IN (SELECT CODE FROM base.t_etablissements)
				;
				
				/**********************************************************************************
				 *            	 ETABLISSEMENT PROVENANCE ET DESTINATION (TRANSFERT)              *
				 **********************************************************************************/

				-- Insertion des établissement de provenance et destination dans p_rss_transfert
				-- Traitement en commun réalisé dans import_rss_rsf_encours.php (generation_rum_post_traitements())
				-- Grâce à la table w_TRANSFERTS
				
				DROP TABLE IF EXISTS temp.w_TRANSFERTS;
				CREATE TABLE temp.w_TRANSFERTS AS 
				SELECT
					p_rss.oid AS rss_id,
					import_id,
					COALESCE(MIN(CASE WHEN MVT_TYPE = 1 THEN t_etablissements.oid ELSE null END),0) AS prov_id,
					COALESCE(MIN(CASE WHEN MVT_TYPE = 2 THEN t_etablissements.oid ELSE null END),0) AS dest_id
				FROM
					pmsi.p_rss
					JOIN prod_web100t.DAT_SEJOUR ON SEJ_NO_ENTREE = no_sejour_administratif
					JOIN prod_web100t.REGUL_MOUVEMENTS ON MVT_SEJ_OID = PHASE_OID
					JOIN w_SGN_NMCL_DATA ON MVT_AUTRE_ETS = ND_INVARIANT_OID AND NMCL_IDENT = 'FINESS'
					LEFT JOIN base.t_etablissements ON ND_CODE = code
				WHERE 1=1 AND 
					MVT_AUTRE_ETS != 0 AND
					etat != 'S'
				GROUP BY 1,2
				;
					
				
			]]></sqlcmd>
		</NODE>
		<NODE label="Identités">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES PATIENTS                                   *
				 **********************************************************************************/
				INSERT INTO pmsi.p_identites(
						finess,
						rss_id,
						no_rss,
						nom,
						prenom,
						nom_naissance)
				SELECT
						w_rss.finess AS finess,
						w_rss.rss_id AS rss_id,
						w_rss.RES_OID AS no_rss,
						PAT_NOM AS nom,
						PAT_PRENOM AS prenom,
						PAT_NOMNAISS AS nom_naissance
				FROM w_rss
					JOIN w_PATIENTS PATIENTS ON (w_rss.RES_PATIENT = PATIENTS.PAT_ID)
				;

				-- Màj du n° de patient RSS AVEC GHM
				UPDATE pmsi.p_rss
				SET no_patient = PAT_IPP_NUM
				FROM prod_web100t.DAT_RESUME
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_ID = DAT_RESUME.RES_PATIENT
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
				WHERE
					DAT_RESUME.RES_OID = p_rss.no_rss
					AND DEF_TYPE_RESUME.TR_IDENT = 'RSS'
					AND PAT_IPP BETWEEN '0' AND '9999999999999999'
					AND ghm_id <> 0
					AND p_rss.date_sortie = res_ds_calc::date
					AND no_patient IS DISTINCT FROM PAT_IPP_NUM
				;

				-- Màj des n° de patient RSS SANS GHM
				UPDATE pmsi.p_rss
				SET no_patient = PAT_IPP_NUM
				FROM prod_web100t.fac_FACTURE
					JOIN prod_web100t.dat_da on dat_da.da_oid = fac_FACTURE.fact_da
					JOIN w_PATIENTS PATIENTS ON PATIENTS.PAT_id = dat_da.da_patient
				WHERE
					dat_da.da_numero = p_rss.no_sejour_administratif
					AND base.cti_is_num(fac_FACTURE.fact_numero) 
					AND PAT_IPP BETWEEN '0' AND '9999999999999999'
					AND ghm_id = 0
					AND position('.' in FACT_NUMERO) = 0
					AND p_rss.date_sortie = DA_DATE_FIN::date
					AND no_patient IS DISTINCT FROM PAT_IPP_NUM
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Rum">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES RUMS                                       *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss_rum(
					finess,
					rss_id,
					no_rss,
					no_rum,
					date_entree,
					date_sortie,
					mode_entree,
					provenance,
					mode_sortie,
					destination,
					passage_urgences_code,
					duree_sejour,
					nb_seances,
					unite_medicale,
					diagnostic_principal_id,
					diagnostic_relie_id,
					unite_medicale_id,
					type_autorisation,
					igs2,
					type_autorisation_lit_dedie,
					supplement_code
					)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					DAT_RESUME.RES_INDEX AS no_rum,
					DAT_RESUME.RES_DE_CALC AS date_entree,
					DAT_RESUME.RES_DS_CALC AS date_sortie,
					substr(DAT_RESUME.RES_ME_PMSI,1,1) AS mode_entree,
					substr(DAT_RESUME.RES_ME_PMSI,2,1) AS provenance,
					substr(DAT_RESUME.RES_MS_PMSI,1,1) AS mode_sortie,
					substr(DAT_RESUME.RES_MS_PMSI,2,1) AS destination,
					COALESCE(t_passage_urgences.code, '') AS passage_urgences_code,
					CASE WHEN DAT_RESUME.RES_DS_CALC > DAT_RESUME.RES_DE_CALC THEN date(DAT_RESUME.RES_DS_CALC) - date(DAT_RESUME.RES_DE_CALC) ELSE 0 END AS duree_sejour,
					RES_SEANCES AS nb_seances,
					substr(w_um.code,1,4) AS unite_medicale,
					COALESCE(t_diagnostics.oid,0) AS diagnostic_principal_id,
					COALESCE(t_diagnostics_relies.oid,0) AS diagnostic_relie_id,
					COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id,
					'' AS type_autorisation,
					RUM_IGS2 AS igs2,
					'' AS type_autorisation_lit_dedie,
					'' AS supplement_code
				FROM prod_web100t.DAT_RESUME
					JOIN w_rss ON (DAT_RESUME.RES_PARENT = w_rss.RES_OID)
					JOIN prod_web100t.DAT_RUM ON DAT_RESUME.RES_OID = RUM_OID
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					LEFT JOIN prod_web100t.DAT_DIAGS DAT_DIAGS_p ON RUM_DP = DAT_DIAGS_p.DIAG_OID
					LEFT JOIN prod_web100t.SGN_NMCL_DATA SGN_NMCL_DATA_p ON DAT_DIAGS_p.DIAG_CODE = SGN_NMCL_DATA_p.ND_OID
					LEFT JOIN prod_web100t.DAT_DIAGS DAT_DIAGS_r ON RUM_DR = DAT_DIAGS_r.DIAG_OID
					LEFT JOIN prod_web100t.SGN_NMCL_DATA SGN_NMCL_DATA_r ON DAT_DIAGS_r.DIAG_CODE = SGN_NMCL_DATA_r.ND_OID
					LEFT JOIN w_um ON RES_UM = w_um.oid
					LEFT JOIN pmsi.t_unites_medicales ON (w_um.code = t_unites_medicales.code)
					LEFT JOIN pmsi.t_diagnostics ON (replace(SGN_NMCL_DATA_p.ND_CODE,'.','') = t_diagnostics.code)
					LEFT JOIN pmsi.t_diagnostics t_diagnostics_relies ON (replace(SGN_NMCL_DATA_r.ND_CODE,'.','') = t_diagnostics_relies.code)
					LEFT JOIN pmsi.t_passage_urgences ON t_passage_urgences.oid = DAT_RESUME.RES_URGENCE_CALC
				WHERE DEF_TYPE_RESUME.TR_IDENT = 'RUM'
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Diagnostics">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES DIAGS                                      *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss_diagnostics(
						finess,
						rss_id,
						no_rss,
						no_rum,
						diagnostic_id,
						type_diagnostic,
						type_diagnostic_rss,
						imprecis,
						unite_medicale,
						unite_medicale_id
						)
				SELECT
						w_rss.finess AS finess,
						w_rss.rss_id AS rss_id,
						w_rss.RES_OID AS no_rss,
						RES_INDEX AS no_rum,
						COALESCE(t_diagnostics.oid,0) AS diagnostic_id,
						CASE
							WHEN DIAG_TYPE = 1 THEN 'DP'
							WHEN DIAG_TYPE = 2 THEN 'DR'
							WHEN DIAG_TYPE = 7 THEN 'DD'
							ELSE 'DA'
						END AS type_diagnostic,
						CASE
							WHEN RSS_OID_RUM_CLASSANT = DAT_RESUME.RES_OID AND DIAG_TYPE = 1 THEN 'DP'
							WHEN DIAG_TYPE = 2 THEN 'DR'
							WHEN DIAG_TYPE = 7 THEN 'DD'
							ELSE 'DA'
						END AS type_diagnostic_rss,
						'' AS imprecis,
						substr(w_um.code,1,4) AS unite_medicale,
						COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id
				FROM prod_web100t.DAT_RESUME
					JOIN w_rss ON (DAT_RESUME.RES_PARENT = w_rss.RES_OID)
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN prod_web100t.DAT_RUM ON DAT_RESUME.RES_OID = RUM_OID
					JOIN prod_web100t.DAT_DIAGS DAT_DIAGS ON DAT_RESUME.RES_OID = DAT_DIAGS.DIAG_RESUME
					JOIN prod_web100t.SGN_NMCL_DATA ON DAT_DIAGS.DIAG_CODE = ND_OID
					LEFT JOIN pmsi.t_diagnostics ON (replace(ND_CODE,'.','') = t_diagnostics.code)
					LEFT JOIN prod_web100t.DAT_RSS ON w_rss.RES_OID = RSS_OID
					LEFT JOIN w_um ON RES_UM = w_um.oid
					LEFT JOIN pmsi.t_unites_medicales ON (w_um.code = t_unites_medicales.code)
				WHERE DEF_TYPE_RESUME.TR_IDENT = 'RUM'
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Actes">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES ACTES                                      *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss_actes(
					finess,
					rss_id,
					no_rss,
					no_rum,
					unite_medicale,
					unite_medicale_id,
					date_acte,
					medecin_id,
					acte_id,
					nombre,
					phase_ccam,
					activite_ccam,
					extension_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					remboursement_excp_ccam,
					association_nonprevue_ccam
					)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					RES_INDEX AS no_rum,
					substr(w_um.code,1,4) AS unite_medicale,
					COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id,
					date(ACT_DATE) AS date_acte,
					COALESCE(t_medecins.oid,0) AS medecin_id,
					COALESCE(t_actes.oid,0) AS acte_id,
					ACT_QUANTITE AS nombre,
					'0' AS phase_ccam,
					ACT_CODE_ACTIVITE AS activite_ccam,
					substr(ACT_EXT_DOC,1,1) AS extension_ccam,
					substr(ACT_MODIFICATEURS,1,1) AS modificateur_ccam_1,
					substr(ACT_MODIFICATEURS,2,1) AS modificateur_ccam_2,
					substr(ACT_MODIFICATEURS,3,1) AS modificateur_ccam_3,
					substr(ACT_MODIFICATEURS,4,1) AS modificateur_ccam_4,
					ACT_REMBOURSEMENT AS remboursement_excp_ccam,
					ACT_ASSOCIATION AS association_nonprevue_ccam
				FROM prod_web100t.DAT_RESUME
					JOIN w_rss ON (DAT_RESUME.RES_PARENT = w_rss.RES_OID)
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN prod_web100t.DAT_RUM ON DAT_RESUME.RES_OID = RUM_OID
					JOIN prod_web100t.DAT_ACTES ON DAT_RESUME.RES_OID = DAT_ACTES.ACT_RESUME
					JOIN prod_web100t.SGN_NMCL_DATA ON DAT_ACTES.ACT_CODE = ND_OID
					JOIN pmsi.t_actes ON SPLIT_PART(SGN_NMCL_DATA.ND_CODE, '.', 1) = t_actes.code
					LEFT JOIN w_um ON RES_UM = w_um.oid
					LEFT JOIN pmsi.t_unites_medicales ON (w_um.code = t_unites_medicales.code)
					LEFT JOIN w_medecin ON ACT_EXECUTANT = ANY(w_medecin.oid)
					LEFt JOIN pmsi.t_medecins ON t_medecins.code = w_medecin.code
				WHERE DEF_TYPE_RESUME.TR_IDENT = 'RUM'
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Factures">
            <condition><![CDATA[
                "[WITH_FACTU]" != "0"
            ]]></condition>
			<sqlcmd><![CDATA[

				/**********************************************************************************
				 *                      		 MAJ DES FACTURES                                 *
				 **********************************************************************************/

				DROP TABLE IF EXISTS w_FAC_FACT_TIER;
				CREATE TEMP TABLE w_FAC_FACT_TIER AS
				SELECT
					FT_DA,
					MAX(FT_OID) AS FT_OID,
					(MAX(Array[FT_OID,FT_FACTURE]))[2] AS FT_FACTURE
				FROM prod_web100t.FAC_FACT_TIER
					JOIN w_rss ON (FT_DA = w_rss.DA_OID)
				WHERE FT_TYPE_TIER = 'AMO' AND
					FT_TOTAL_ETS > 0
				GROUP BY 1;

				ALTER TABLE w_FAC_FACT_TIER ADD CONSTRAINT w_FAC_FACT_TIER_pkey PRIMARY KEY(FT_DA);


				DROP TABLE IF EXISTS w_FAC_B2_TIER;
				CREATE TEMP TABLE w_FAC_B2_TIER AS
				SELECT 
					w_rss.rss_id,
					B2T_LIGNE,
					MAX(B2T_QUANTITE) AS B2T_QUANTITE,
					base.cti_division(
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric,
						MAX(B2T_QUANTITE)::numeric
					) AS B2T_PU,
					SUM(B2T_TOTAL_TTC) AS B2T_TOTAL,
					round(base.cti_division(
						SUM(CASE WHEN B2T_TYPE_TIER = 'AMO' THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(CASE WHEN B2T_TYPE_TIER = 'AMO' THEN B2T_DEPASSEMENT ELSE 0 END)::numeric,
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric
					) * 100,0) AS B2T_TAUX_AMO
				FROM prod_web100t.FAC_B2_TIER
					JOIN w_rss ON B2T_DA = w_rss.DA_OID
				GROUP BY 1,2
				ORDER BY 1;
				
				CREATE INDEX w_FAC_B2_TIER_i1
				  ON w_FAC_B2_TIER
				  USING btree
				  (B2T_LIGNE)
				;




				INSERT INTO pmsi.p_rsf_total(
					finess,
					rss_id,
					no_rss,
					code_pec,
					rang_beneficiaire,
					regime,
					nature_pec,
					justificatif_exo,
					no_facture,
					code_regularisation,
					matricule_assure,
					cle_matricule_assure,
					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,
					ca_ghs_theorique,
					taux_remboursement
					)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					'1' AS code_pec,
					'' AS rang_beneficiaire,
					'' AS regime,
					'' AS nature_pec,
					'' AS justificatif_exo,
					MAX(FACT_NUMERO) AS no_facture,
					'1' AS code_regularisation,
					'' AS matricule_assure,
					'' AS cle_matricule_assure,
					base.cti_sum_distinct_on(ARRAY[LI_OID::numeric,COALESCE(round((B2T_PU * B2T_QUANTITE)::numeric,2),FLT_TOTAL_TTC)]) AS base_remboursement,
					base.cti_sum_distinct_on(ARRAY[LI_OID::numeric,FLT_TOTAL_TTC]) AS sejour_facture,
					base.cti_sum_distinct_on(ARRAY[LI_OID::numeric,FLT_TOTAL_TTC]) AS sejour_remboursable,
					MAX(FACT_TOTAL_HO) AS honoraires_factures,
					MAX(FACT_TOTAL_HO) AS honoraires_remboursable,
					0 AS t2a_facture,
					0 AS dmi_facture,
					0 AS phc_facture,
					0 AS participation_assure_avant_oc,
					0 AS sejour_remboursable_2,
					0 AS honoraires_remboursable_2,
					0 AS montant_dmi_ghs2006,
					0 AS nb_si,
					0 AS ca_si,
					0 AS nb_sur,
					0 AS ca_sur,
					0 AS nb_rea,
					0 AS ca_rea,
					0 AS nb_neonat,
					0 AS ca_neonat,
					0 AS nb_exh,
					0 AS ca_exh,
					0 AS nb_exb,
					0 AS ca_exb,
					0 AS nb_ghs,
					0 AS ca_ghs,
					0 AS ca_ghs_theorique,
					0 AS taux_remboursement
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
					JOIN prod_web100t.FAC_FACTURE ON w_FAC_FACT_TIER.FT_FACTURE = FACT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN pmsi.t_prestations ON FLT_CODE_PREST = t_prestations.code
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE AND w_rss.rss_id = w_FAC_B2_TIER.rss_id
					JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
				WHERE date(FLT_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie
				GROUP BY 1,2,3
				;

				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)
				SELECT
					p_rss.finess, p_rss.no_rss, '', '', '', '', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, p_rss.oid, 0
				FROM pmsi.p_rss
				LEFT JOIN pmsi.p_rsf_total ON (p_rsf_total.rss_id = p_rss.oid)
				WHERE
					en_cours = '1'
					AND p_rsf_total.rss_id IS NULL
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Factures PMSI">
            <condition><![CDATA[
                "[WITH_FACTU]" == "0"
            ]]></condition>
			<sqlcmd><![CDATA[

				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)
				SELECT
					p_rss.finess, p_rss.no_rss, '', '', '', '', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0,
					0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, p_rss.oid, 0
				FROM pmsi.p_rss
				LEFT JOIN pmsi.p_rsf_total ON (p_rsf_total.rss_id = p_rss.oid)
				WHERE
					en_cours = '1'
					AND p_rsf_total.rss_id IS NULL
				;

			]]></sqlcmd>
		</NODE>
		<NODE label="Prestations">
            <condition><![CDATA[
                "[WITH_FACTU]" != "0"
            ]]></condition>
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DU DETAIL DES FACTURES						  *
				 **********************************************************************************/
				
				DROP TABLE IF EXISTS w_LI;
				CREATE TEMP TABLE w_LI AS
				SELECT 
					DISTINCT FLT_LIGNE_FACTURE AS LI_OID
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
				WHERE FLT_DATE_DEBUT BETWEEN RES_DE AND RES_DS;

				INSERT INTO pmsi.p_rsf_detail(
					finess,
					rss_id,
					no_rss,
					nature,
					mt,
					dmt,
					date_debut,
					date_fin,
					nombre,
					coefficient,
					prix_unitaire,
					base_remboursement,
					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,
					type,
					coefficient_geo,
					est_ligne_rss,
					est_ligne_rum,
					no_rum,
					unite_medicale_id,
					base_remboursement_rum
				)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					'' AS nature,
					'' AS mt,
					'' AS dmt,
					date(FLT_DATE_DEBUT) AS date_debut,
					date(FLT_DATE_FIN) AS date_fin,
					COALESCE(B2T_QUANTITE,1) AS nombre,
					1 AS coefficient,
					COALESCE(B2T_PU,FLT_TOTAL_TTC) AS prix_unitaire,
					COALESCE(round((B2T_PU * B2T_QUANTITE)::numeric,2),FLT_TOTAL_TTC) AS base_remboursement,
					COALESCE(B2T_TAUX_AMO,100) AS taux_remboursement,
					FLT_TOTAL_TTC AS sejour_facture,
					FLT_TOTAL_TTC AS sejour_remboursable,
					0 AS compteur,
					'' AS ligne_t2a,
					'' AS pec_fj,
					1 AS coefficient_mco,
					0 AS sejour_remboursable_2,
					0 AS ghs_id,
					0 AS sejour_rembourse_noemie,
					'' AS nature_noemie,
					COALESCE(t_prestations.oid, 0) AS prestation_id,
					'B' AS type,
					0 AS coefficient_geo,
					'1' AS est_ligne_rss,
					'0' AS est_ligne_rum,
					1 AS no_rum,
					0 AS unite_medicale_id,
					0 AS base_remboursement_rum
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN pmsi.t_prestations ON FLT_CODE_PREST = t_prestations.code
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE AND w_rss.rss_id = w_FAC_B2_TIER.rss_id
					JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
					WHERE date(FLT_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie
				ORDER BY w_rss.RES_OID
				;

				INSERT INTO pmsi.p_rsf_detail(
					finess,
					rss_id,
					no_rss,
					nature,
					mt,
					dmt,
					date_debut,
					date_fin,
					nombre,
					coefficient,
					prix_unitaire,
					base_remboursement,
					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,
					type,
					coefficient_geo,
					est_ligne_rss,
					est_ligne_rum,
					no_rum,
					unite_medicale_id,
					base_remboursement_rum
				)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					'' AS nature,
					'' AS mt,
					'' AS dmt,
					date(FLT_DATE_DEBUT) AS date_debut,
					date(FLT_DATE_FIN) AS date_fin,
					COALESCE(B2T_QUANTITE,1) AS nombre,
					1 AS coefficient,
					COALESCE(B2T_PU,FLT_TOTAL_TTC) AS prix_unitaire,
					COALESCE(round((B2T_PU * B2T_QUANTITE)::numeric,2),FLT_TOTAL_TTC) AS base_remboursement,
					COALESCE(B2T_TAUX_AMO,100) AS taux_remboursement,
					FLT_TOTAL_TTC AS sejour_facture,
					FLT_TOTAL_TTC AS sejour_remboursable,
					0 AS compteur,
					'' AS ligne_t2a,
					'' AS pec_fj,
					1 AS coefficient_mco,
					0 AS sejour_remboursable_2,
					0 AS ghs_id,
					0 AS sejour_rembourse_noemie,
					'' AS nature_noemie,
					COALESCE(t_prestations.oid, 0) AS prestation_id,
					'B' AS type,
					0 AS coefficient_geo,
					'1' AS est_ligne_rss,
					'0' AS est_ligne_rum,
					1 AS no_rum,
					0 AS unite_medicale_id,
					0 AS base_remboursement_rum
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN pmsi.t_prestations ON FLT_CODE_PREST = t_prestations.code
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE AND w_rss.rss_id = w_FAC_B2_TIER.rss_id
					LEFT JOIN w_LI ON w_LI.LI_OID = FAC_FACT_LIGNE.LI_OID
					JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
				WHERE date(FLT_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie AND
					w_LI.LI_OID IS NULL
				ORDER BY w_rss.RES_OID
				;

				----------  CORRECTIF TARIF GHS FACTURE  ----------------
				-- Tarif GHS = GHS (AMO) + FORFAIT JOURNALIER (PATIENT)
				-- Quand le dossier est facturé (non envoyé pmsi), le forfait journalier est compliqué à récupérer 
				-- Nous ne récupérons seulement le ghs payé par l'AMO
				-- On fait en sorte de calculer la bonne base remboursement et le bon prix unitaire pour coller au mieux avec le tarif que l'on récupère quand il sera transmis au pmsi
				-- On ne s'occupe pas pour l'instant des bornes hautes et basses 

				DROP TABLE IF EXISTS w_correction;
				CREATE TEMP TABLE w_correction AS
					SELECT rss_id,
					p_rsf_detail.CTID AS from_ctid,
					coefficient_mco,
					prix_unitaire AS prix_unitaire_avant,
					CASE
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_1 AND p_rss.date_sortie <= t_ghs.date_fin_prive_1 THEN t_ghs.tarif_ghs_prive_1
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_2 AND p_rss.date_sortie <= t_ghs.date_fin_prive_2 THEN t_ghs.tarif_ghs_prive_2
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_3 AND p_rss.date_sortie <= t_ghs.date_fin_prive_3 THEN t_ghs.tarif_ghs_prive_3
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_4 AND p_rss.date_sortie <= t_ghs.date_fin_prive_4 THEN t_ghs.tarif_ghs_prive_4
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_5 AND p_rss.date_sortie <= t_ghs.date_fin_prive_5 THEN t_ghs.tarif_ghs_prive_5
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_6 AND p_rss.date_sortie <= t_ghs.date_fin_prive_6 THEN t_ghs.tarif_ghs_prive_6
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_7 AND p_rss.date_sortie <= t_ghs.date_fin_prive_7 THEN t_ghs.tarif_ghs_prive_7
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_8 AND p_rss.date_sortie <= t_ghs.date_fin_prive_8 THEN t_ghs.tarif_ghs_prive_8
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_9 AND p_rss.date_sortie <= t_ghs.date_fin_prive_9 THEN t_ghs.tarif_ghs_prive_9
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9
					ELSE 0::numeric
					END AS prix_unitaire_theorique,
					p_rsf_detail.base_remboursement AS base_remboursement_avant,
					round(CASE
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_1 AND p_rss.date_sortie <= t_ghs.date_fin_prive_1 THEN t_ghs.tarif_ghs_prive_1
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_2 AND p_rss.date_sortie <= t_ghs.date_fin_prive_2 THEN t_ghs.tarif_ghs_prive_2
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_3 AND p_rss.date_sortie <= t_ghs.date_fin_prive_3 THEN t_ghs.tarif_ghs_prive_3
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_4 AND p_rss.date_sortie <= t_ghs.date_fin_prive_4 THEN t_ghs.tarif_ghs_prive_4
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_5 AND p_rss.date_sortie <= t_ghs.date_fin_prive_5 THEN t_ghs.tarif_ghs_prive_5
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_6 AND p_rss.date_sortie <= t_ghs.date_fin_prive_6 THEN t_ghs.tarif_ghs_prive_6
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_7 AND p_rss.date_sortie <= t_ghs.date_fin_prive_7 THEN t_ghs.tarif_ghs_prive_7
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_8 AND p_rss.date_sortie <= t_ghs.date_fin_prive_8 THEN t_ghs.tarif_ghs_prive_8
					WHEN type_etablissement = '1' AND p_rss.date_sortie >= t_ghs.date_debut_prive_9 AND p_rss.date_sortie <= t_ghs.date_fin_prive_9 THEN t_ghs.tarif_ghs_prive_9
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_1 AND p_rss.date_sortie <= t_ghs.date_fin_public_1 THEN t_ghs.tarif_ghs_public_1
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_2 AND p_rss.date_sortie <= t_ghs.date_fin_public_2 THEN t_ghs.tarif_ghs_public_2
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_3 AND p_rss.date_sortie <= t_ghs.date_fin_public_3 THEN t_ghs.tarif_ghs_public_3
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_4 AND p_rss.date_sortie <= t_ghs.date_fin_public_4 THEN t_ghs.tarif_ghs_public_4
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_5 AND p_rss.date_sortie <= t_ghs.date_fin_public_5 THEN t_ghs.tarif_ghs_public_5
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_6 AND p_rss.date_sortie <= t_ghs.date_fin_public_6 THEN t_ghs.tarif_ghs_public_6
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_7 AND p_rss.date_sortie <= t_ghs.date_fin_public_7 THEN t_ghs.tarif_ghs_public_7
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_8 AND p_rss.date_sortie <= t_ghs.date_fin_public_8 THEN t_ghs.tarif_ghs_public_8
					WHEN type_etablissement <> '1' AND p_rss.date_sortie >= t_ghs.date_debut_public_9 AND p_rss.date_sortie <= t_ghs.date_fin_public_9 THEN t_ghs.tarif_ghs_public_9
					ELSE 0::numeric
					END * p_rsf_detail.coefficient_mco,2) AS base_remboursement_theorique,
					(p_rss.date_sortie - p_rss.date_entree) * 20 AS montant_forfait_theorique
					FROM pmsi.p_rsf_detail
					JOIN pmsi.p_rss On rss_id = p_rss.oid
					JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
					JOIN pmsi.t_ghs ON p_rss.ghs_id = t_ghs.oid
					JOIN base.t_finess ON p_rss.finess = t_finess.code
					WHERE en_cours = '1' AND
					t_prestations.code = 'GHS' AND
					est_ligne_rss = '1' AND
					prix_unitaire = p_rsf_detail.base_remboursement	
				;

				ANALYSE w_correction
				;

				UPDATE pmsi.p_rsf_detail SET
					prix_unitaire = prix_unitaire_theorique,
					base_remboursement = 
						CASE WHEN (
								(base_remboursement_avant + montant_forfait_theorique) = base_remboursement_theorique OR
								(base_remboursement_avant + montant_forfait_theorique + 24) = base_remboursement_theorique OR
								base_remboursement_avant = base_remboursement_theorique
								) THEN base_remboursement_theorique ELSE p_rsf_detail.base_remboursement END
					,
					sejour_facture = 
						CASE WHEN (
								(base_remboursement_avant + montant_forfait_theorique) = base_remboursement_theorique OR
								(base_remboursement_avant + montant_forfait_theorique + 24) = base_remboursement_theorique OR
								base_remboursement_avant = base_remboursement_theorique
								) THEN base_remboursement_theorique ELSE p_rsf_detail.base_remboursement END
				FROM w_correction
				WHERE p_rsf_detail.rss_id = w_correction.rss_id AND
					p_rsf_detail.CTID = w_correction.from_CTID
					;


			]]></sqlcmd>
		</NODE>
		<NODE label="Prestations PMSI">
            <condition><![CDATA[
                "[WITH_FACTU]" == "0"
            ]]></condition>
			<sqlcmd><![CDATA[ 
			
				/**********************************************************************************
				 *                             MAJ DU DETAIL DES FACTURES						  *
				 **********************************************************************************/
				
				WITH w_prest AS (
					SELECT
						w_rss.finess as finess,
						w_rss.rss_id as rss_id,
						w_rss.res_oid as no_rss,
						''::text AS nature,
						''::text AS mt,
						''::text AS dmt,
						DAT_PRESTATIONS.PREST_DATE_DEBUT as date_debut,
						DAT_PRESTATIONS.PREST_DATE_FIN as date_fin,
						COALESCE(DAT_PRESTATIONS.PREST_QUANTITE, 1) as nombre,
						COALESCE(DAT_PRESTATIONS.PREST_COEFF, 1) as coefficient,
						COALESCE(DAT_PRESTATIONS.PREST_PU, 0) as prix_unitaire,
						COALESCE(DAT_PRESTATIONS.PREST_TOTAL, 0) as base_remboursement,
						100::integer as taux_remboursement,
						COALESCE(DAT_PRESTATIONS.PREST_TOTAL, 0) as sejour_facture,
						COALESCE(DAT_PRESTATIONS.PREST_TOTAL, 0) as sejour_remboursable,
						0 AS compteur,
						'' AS ligne_t2a,
						'' AS pec_fj,
						1 AS coefficient_mco,
						0 AS sejour_remboursable_2,
						0 AS ghs_id,
						0 AS sejour_rembourse_noemie,
						'' AS nature_noemie,
						'B' AS type,
						0 AS coefficient_geo,
						'1' AS est_ligne_rss,
						'0' AS est_ligne_rum,
						1::integer as no_rum,
						0::integer as base_remboursement_rum,
						regexp_replace(DAT_PRESTATIONS.PREST_TYPE, 'DIAL.', 'D09') as PREST_TYPE,
						w_um.code as um_code
					FROM prod_web100T.DAT_PRESTATIONS
						JOIN w_rss ON w_rss.RES_OID = DAT_PRESTATIONS.PREST_RESUME
						LEFT JOIN w_um ON w_um.oid = DAT_PRESTATIONS.PREST_UM
						JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
						LEFT JOIN w_um ON w_um.oid = DAT_PRESTATIONS.PREST_UM
					WHERE date(DAT_PRESTATIONS.PREST_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie
						AND DAT_PRESTATIONS.PREST_INDEX > 1
						AND DAT_PRESTATIONS.PREST_TYPE NOT IN ('GHS', 'EXH', 'EXB')
				)
				INSERT INTO pmsi.p_rsf_detail (
					finess,
					rss_id,
					no_rss,
					nature,
					mt,
					dmt,
					date_debut,
					date_fin,
					nombre,
					coefficient,
					prix_unitaire,
					base_remboursement,
					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,
					type,
					coefficient_geo,
					est_ligne_rss,
					est_ligne_rum,
					no_rum,
					unite_medicale_id,
					base_remboursement_rum
				)
				SELECT
					w_prest.finess,
					w_prest.rss_id,
					w_prest.no_rss,
					w_prest.nature,
					w_prest.mt,
					w_prest.dmt,
					w_prest.date_debut,
					w_prest.date_fin,
					w_prest.nombre,
					w_prest.coefficient,
					w_prest.prix_unitaire,
					w_prest.base_remboursement,
					w_prest.taux_remboursement,
					w_prest.sejour_facture,
					w_prest.sejour_remboursable,
					w_prest.compteur,
					w_prest.ligne_t2a,
					w_prest.pec_fj,
					w_prest.coefficient_mco,
					w_prest.sejour_remboursable_2,
					w_prest.ghs_id,
					w_prest.sejour_rembourse_noemie,
					w_prest.nature_noemie,
					COALESCE(t_prestations.oid, 0) as prestation_id,
					w_prest.type,
					w_prest.coefficient_geo,
					w_prest.est_ligne_rss,
					w_prest.est_ligne_rum,
					w_prest.no_rum,
					COALESCE(t_unites_medicales.oid, 0) as unite_medicale_id,
					0::integer as base_remboursement_rum
				FROM
					w_prest
					LEFT JOIN pmsi.t_prestations ON t_prestations.code = w_prest.PREST_TYPE
					LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = w_prest.um_code
				;
				
				UPDATE pmsi.p_rsf_detail SET
					no_rum = p_rss_rum.no_rum
				FROM
					w_rss, pmsi.p_rss_rum
				WHERE 1=1
					AND w_rss.rss_id = p_rsf_detail.rss_id
					AND p_rss_rum.rss_id = w_rss.rss_id
					AND p_rsf_detail.unite_medicale_id = p_rss_rum.unite_medicale_id
					AND p_rsf_detail.date_debut BETWEEN p_rss_rum.date_entree and p_rss_rum.date_sortie
					AND p_rsf_detail.date_fin BETWEEN p_rss_rum.date_entree and p_rss_rum.date_sortie
					AND p_rss_rum.no_rum IS DISTINCT FROM p_rsf_detail.no_rum
				;


			]]></sqlcmd>
		</NODE>
		<NODE label="LPP">
            <condition><![CDATA[
                "[WITH_FACTU]" != "0"
            ]]></condition>
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES LPP                                        *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss_lpp(
					finess,
					rss_id,
					no_rss,
					rang,
					date_lpp,
					lpp_id,
					nombre,
					prix_unitaire,
					montant_facture,
					non_pris_en_compte
				)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					1 AS rang,
					date(FLT_DATE_DEBUT) AS date_lpp,
					COALESCE(t_lpp.oid, 0) AS lpp_id,
					COALESCE(B2T_QUANTITE,1) AS nombre,
					COALESCE(B2T_PU,FLT_TOTAL_TTC) AS prix_unitaire,
					COALESCE(FLT_TOTAL_TTC)  AS montant_facture,
					'0' AS non_pris_en_compte
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN prod_web100t.ART_ARTICLES ON FLT_ARTICLE = ART_OID AND ART_CLASS = 'LPP'
					JOIN pmsi.t_lpp ON (ART_CODE = t_lpp.code)
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE AND w_rss.rss_id = w_FAC_B2_TIER.rss_id
					JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
				WHERE date(FLT_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie;

			]]></sqlcmd>
		</NODE>
		<NODE label="UCD">
            <condition><![CDATA[
                "[WITH_FACTU]" != "0"
            ]]></condition>
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES UCD                                        *
				 **********************************************************************************/
				INSERT INTO pmsi.p_rss_ucd(
					finess,
					rss_id,
					no_rss,
					rang,
					date_ucd,
					ucd_id,
					nombre,
					coefficient_fractionnement,
					prix_unitaire_achat,
					prix_unitaire_ecart_indemnisable,
					montant_ecart_indemnisable,
					montant_facture,
					non_pris_en_compte
				)
				SELECT
					w_rss.finess AS finess,
					w_rss.rss_id AS rss_id,
					w_rss.RES_OID AS no_rss,
					1 AS rang,
					date(FLT_DATE_DEBUT) AS date_ucd,
					COALESCE(t_ucd.oid,0) AS ucd_id,
					COALESCE(B2T_QUANTITE,1) AS nombre,
					0 AS coefficient_fractionnement,
					0 AS prix_unitaire_achat,
					0 AS prix_unitaire_ecart_indemnisable,
					0 AS montant_ecart_indemnisable,
					COALESCE(B2T_PU,FLT_TOTAL_TTC) AS montant_facture,
					'0' AS non_pris_en_compte
				FROM w_FAC_FACT_TIER
					JOIN w_rss ON FT_DA = w_rss.DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_IS_ETS = 1
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN prod_web100t.ART_ARTICLES ON FLT_ARTICLE = ART_OID AND ART_CLASS = 'UCD'
					JOIN pmsi.t_ucd ON (ART_CODE = t_ucd.code)
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE AND w_rss.rss_id = w_FAC_B2_TIER.rss_id
					JOIN pmsi.p_rss ON w_rss.rss_id = p_rss.oid
				WHERE date(FLT_DATE_DEBUT) BETWEEN p_rss.date_entree AND p_rss.date_sortie
				;
			]]></sqlcmd>
		</NODE>
		<NODE label="Facturation SHS">
			<condition><![CDATA[
				"[ADMPROVIDER]" == "shs" || "[ADMPROVIDER]" == "SHS"
			]]></condition>
			<sqlcmd><![CDATA[
			
				-- RSF total
				DROP TABLE IF EXISTS w_rsf_shs;
				CREATE TEMP TABLE w_rsf_shs AS
				SELECT 
						p_rss.oid AS rss_id, 
						MFDOSS,
						MAX(to_char(MFDOSS,'FM00000000')) AS no_facture, 
						SUM(MFMTFA) AS base_remboursement, 
						SUM(MFMTFA) AS sejour_facture, 
						SUM(MFMFA1) AS sejour_remboursable, 
						SUM(MFMFAM) AS participation_assure_avant_oc
				FROM pmsi.p_rss
					JOIN pmsi.p_rsf_total ON rss_id = p_rss.oid AND p_rsf_total.base_remboursement = 0
					JOIN prod_shs.[ACTIVITESCHEMA]_MFP01CLI ON to_char(MFDOSS,'FM00000000') = p_rss.no_sejour_administratif AND MFDCPL = 0
					JOIN prod_shs.[ACTIVITESCHEMA]_TRP01 ON TRCENR = 'A51' AND 
						TRCSER = MFCSER AND TRCRUB = substr(to_char(MFRUPR,'FM0000'),2,3)
					JOIN pmsi.t_prestations ON CASE WHEN MFRUPR IN (111,112) THEN 'GHS' ELSE TRPRSA END = t_prestations.code
				WHERE en_cours = '1' AND
					(MFMFA1 <> 0 OR t_prestations.code IN ('GHS', 'EXH', 'PII', 'PH1', 'PH8', 'SRC', 'REA', 'ATU', 'FFM', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'AP2', 'FPI'))
				GROUP BY 1,2;
				
				UPDATE pmsi.p_rsf_total SET
					no_facture = w_rsf_shs.no_facture,
					base_remboursement = w_rsf_shs.base_remboursement,
					sejour_facture = w_rsf_shs.sejour_facture,
					sejour_remboursable = w_rsf_shs.sejour_remboursable,
					participation_assure_avant_oc = w_rsf_shs.participation_assure_avant_oc
				FROM w_rsf_shs
				WHERE w_rsf_shs.rss_id = p_rsf_total.rss_id;



				-- Hors GHS
				INSERT INTO pmsi.p_rsf_detail(
						finess, 
						rss_id, 
						no_rss, 
						nature, 
						mt, 
						dmt, 
						date_debut, 
						date_fin, 
						nombre, 
						coefficient, 
						prix_unitaire, 
						base_remboursement, 
						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, 
						type, 
						coefficient_geo, 
						est_ligne_rss, 
						est_ligne_rum, 
						no_rum, 
						unite_medicale_id, 
						base_remboursement_rum)
				SELECT 
						p_rss.finess, 
						p_rss.oid AS rss_id, 
						p_rss.no_rss, 
						'' AS nature, 
						'' AS mt, 
						'' AS dmt, 
						p_rss.date_entree AS date_debut, 
						p_rss.date_sortie AS date_fin, 
						MFNBRE AS nombre, 
						1 AS coefficient, 
						MFPRUA AS prix_unitaire, 
						MFMTFA AS base_remboursement, 
						MFTFA1 AS taux_remboursement, 
						MFMTFA AS sejour_facture, 
						MFMFA1 AS sejour_remboursable, 
						0 AS compteur, 
						'' AS ligne_t2a, 
						'' AS pec_fj, 
						1 AS coefficient_mco, 
						0 AS sejour_remboursable_2, 
						COALESCE(t_ghs.oid, 0) AS ghs_id,
						0 AS sejour_rembourse_noemie, 
						'' AS nature_noemie, 
						COALESCE(t_prestations.oid, 0) AS prestation_id, 
						'B' AS type, 
						0 AS coefficient_geo, 
						'1' AS est_ligne_rss, 
						'0' AS est_ligne_rum, 
						1 AS no_rum, 
						0 AS unite_medicale_id, 
						0 AS base_remboursement_rum
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI MFP01CLI
					JOIN w_rsf_shs ON MFP01CLI.MFDOSS = w_rsf_shs.MFDOSS AND MFDCPL = 0 
					JOIN pmsi.p_rss ON w_rsf_shs.rss_id = p_rss.oid
					JOIN prod_shs.[ACTIVITESCHEMA]_TRP01 ON TRCENR = 'A51' AND 
						TRCSER = MFCSER AND TRCRUB = substr(to_char(MFRUPR,'FM0000'),2,3)
					JOIN pmsi.t_prestations ON CASE WHEN MFRUPR IN (111,112) THEN 'GHS' WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END = t_prestations.code
					LEFT JOIN pmsi.t_ghs ON to_number(CASE WHEN MFCGHS BETWEEN '0000' AND '9999' THEN MFCGHS ELSE '9999' END,'0000') = t_ghs.code
				WHERE (MFMFA1 <> 0 AND t_prestations.code NOT IN ('GHS') OR 
						t_prestations.code IN ('EXH', 'PII', 'PH1', 'PH8', 'SRC', 'REA', 'ATU', 'FFM', 'SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'AP2', 'FPI') OR
						t_prestations.code IN ('GHS') AND MFCGHS = 9605
						);
				
	
				-- GHS
				INSERT INTO pmsi.p_rsf_detail(
						finess, 
						rss_id, 
						no_rss, 
						nature, 
						mt, 
						dmt, 
						date_debut, 
						date_fin, 
						nombre, 
						coefficient, 
						prix_unitaire, 
						base_remboursement, 
						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, 
						type, 
						coefficient_geo, 
						est_ligne_rss, 
						est_ligne_rum, 
						no_rum, 
						unite_medicale_id, 
						base_remboursement_rum)
				SELECT 
						p_rss.finess, 
						p_rss.oid AS rss_id, 
						p_rss.no_rss, 
						'' AS nature, 
						'' AS mt, 
						'' AS dmt, 
						p_rss.date_entree AS date_debut, 
						p_rss.date_sortie AS date_fin, 
						1 AS nombre, 
						1 AS coefficient, 
						MAX(MFPRUA) AS prix_unitaire, 
						SUM(MFMTFA) AS base_remboursement, 
						MAX(MFTFA1) AS taux_remboursement, 
						SUM(MFMTFA) AS sejour_facture, 
						SUM(MFMFA1) AS sejour_remboursable, 
						0 AS compteur, 
						'' AS ligne_t2a, 
						'' AS pec_fj, 
						1 AS coefficient_mco, 
						0 AS sejour_remboursable_2, 
						COALESCE(t_ghs.oid, 0) AS ghs_id,
						0 AS sejour_rembourse_noemie, 
						'' AS nature_noemie, 
						COALESCE(t_prestations.oid, 0) AS prestation_id, 
						'B' AS type, 
						0 AS coefficient_geo, 
						'1' AS est_ligne_rss, 
						'0' AS est_ligne_rum, 
						1 AS no_rum, 
						0 AS unite_medicale_id, 
						0 AS base_remboursement_rum
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI MFP01CLI
					JOIN w_rsf_shs ON MFP01CLI.MFDOSS = w_rsf_shs.MFDOSS AND MFDCPL = 0 
					JOIN pmsi.p_rss ON w_rsf_shs.rss_id = p_rss.oid
					JOIN prod_shs.[ACTIVITESCHEMA]_TRP01 ON TRCENR = 'A51' AND 
						TRCSER = MFCSER AND TRCRUB = substr(to_char(MFRUPR,'FM0000'),2,3)
					JOIN pmsi.t_prestations ON CASE WHEN MFRUPR IN (111,112) THEN 'GHS' WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END = t_prestations.code
					LEFT JOIN pmsi.t_ghs ON to_number(CASE WHEN MFCGHS BETWEEN '0000' AND '9999' THEN MFCGHS ELSE '9999' END,'0000') = t_ghs.code
				WHERE t_prestations.code IN ('GHS') AND MFCGHS <> 9605
				GROUP BY 1,2,3,7,8,21,24;

			]]></sqlcmd>
		</NODE>
		
		<NODE label="Numéro RUM">
			<sqlcmd><![CDATA[
				/**********************************************************************************
				 *                             MAJ DES RUM avec des trous dans les numéros                                     *
				 **********************************************************************************/
				DROP TABLE IF EXISTS w_rum_index;
				CREATE TEMP TABLE w_rum_index AS
				SELECT *
				FROM
				(
				SELECT rss_id, no_rum, row_number() OVER (PARTITION BY rss_id ORDER BY no_rum) AS no_rum_new
								FROM pmsi.p_rss_rum
								JOIN pmsi.p_rss ON rss_id = p_rss.oid
								WHERE en_cours = '1'
				) subview
				WHERE no_rum <> no_rum_new
				;
				
				ANALYSE w_rum_index
				;

				UPDATE pmsi.p_rss_actes p_rss_table
				SET no_rum = no_rum_new
				FROM w_rum_index
				WHERE p_rss_table.rss_id = w_rum_index.rss_id AND
					p_rss_table.no_rum = w_rum_index.no_rum
				;

				UPDATE pmsi.p_rss_diagnostics p_rss_table
				SET no_rum = no_rum_new
				FROM w_rum_index
				WHERE p_rss_table.rss_id = w_rum_index.rss_id AND
					p_rss_table.no_rum = w_rum_index.no_rum
				;

				UPDATE pmsi.p_rsf_detail p_rss_table
				SET no_rum = no_rum_new
				FROM w_rum_index
				WHERE p_rss_table.rss_id = w_rum_index.rss_id AND
					p_rss_table.no_rum = w_rum_index.no_rum
				;

				UPDATE pmsi.p_rss p_rss_table
				SET no_rum_principal = no_rum_new
				FROM w_rum_index
				WHERE p_rss_table.oid = w_rum_index.rss_id AND
					p_rss_table.no_rum_principal = w_rum_index.no_rum
				;

				UPDATE pmsi.p_rss_rum p_rss_table
				SET no_rum = no_rum_new
				FROM w_rum_index
				WHERE p_rss_table.rss_id = w_rum_index.rss_id AND
					p_rss_table.no_rum = w_rum_index.no_rum
				;
			]]></sqlcmd>
		</NODE>
		
		
	</NODE>
	
	
	
	<NODE name="PMSIETAT" label="RECUPERATION ETAT DES DOSSIERS">
			
		<NODE label="Initialisation">
			<sqlcmd><![CDATA[
			
				-- Séjours non groupés
				INSERT INTO pmsi.t_ghm(
					code,
					texte,
					mco,
					aso,
					severite,
					cmd_id,
					ghm5_id,
					ligne_oap_id,
					cas_id)
				SELECT
					'99Z99Z' AS code,
					'Séjours sortis non groupés' AS texte,
					'?' AS mco,
					'?' AS aso,
					'Z' AS severite,
					COALESCE((SELECT oid FROM pmsi.t_cmd WHERE code = '99'),0) AS cmd_id,
					COALESCE((SELECT oid FROM pmsi.t_ghm5 WHERE code = '99Z99'),0) AS ghm5_id,
					0 AS ligne_oap_id,
					COALESCE((SELECT oid FROM base.t_cas WHERE code = '?'),0) AS cas_id
				WHERE '99Z99Z' NOT IN (SELECT code FROM pmsi.t_ghm)
				UNION
				SELECT
					'99Z98Z' AS code,
					'GHM indisponible' AS texte,
					'?' AS mco,
					'?' AS aso,
					'Z' AS severite,
					COALESCE((SELECT oid FROM pmsi.t_cmd WHERE code = '99'),0) AS cmd_id,
					COALESCE((SELECT oid FROM pmsi.t_ghm5 WHERE code = '99Z98'),0) AS ghm5_id,
					0 AS ligne_oap_id,
					COALESCE((SELECT oid FROM base.t_cas WHERE code = '?'),0) AS cas_id
				WHERE '99Z98Z' NOT IN (SELECT code FROM pmsi.t_ghm);
					
			
				
				SELECT pmsi.cti_initialize_rss_etat();
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Etat des dossiers">
			<sqlcmd><![CDATA[
			
			
				DROP TABLE IF EXISTS w_DAT_GROUPAGE;
				CREATE TEMP TABLE w_DAT_GROUPAGE AS 
				SELECT
					RES_OID,
					date(MAX(DAT_RESUME.RES_DS_CALC)) AS RES_DS,
					date(MAX(GRP_DATE)) AS GRP_DATE,
					MAX(DAT_RESUME.RES_PATIENT) AS RES_PATIENT,
					MAX(DA_OID) AS DA_OID
				FROM prod_web100t.DAT_RESUME
					JOIN prod_web100t.DAT_GROUPAGE ON RES_OID = GRP_RESUME
					JOIN prod_web100t.DEF_TYPE_RESUME ON DEF_TYPE_RESUME.TR_OID = DAT_RESUME.RES_TYPE
					JOIN prod_web100t.DAT_HOSPIT ON RES_HOSPIT = HOSP_OID
					JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
					LEFT JOIN prod_web100t.DAT_DA ON DA_NUMERO = RSS_NO_HOSPIT
				WHERE
					DAT_RESUME.RES_OID > 0 AND
					DEF_TYPE_RESUME.TR_IDENT = 'RSS'
				GROUP BY 1;
					



				ALTER TABLE w_DAT_GROUPAGE ADD CONSTRAINT w_DAT_GROUPAGE_pkey PRIMARY KEY(RES_OID);


				UPDATE pmsi.p_rss_etat
				SET date_groupage = CASE WHEN GRP_DATE >= date_sortie THEN GRP_DATE ELSE '20991231' END
				FROM pmsi.p_rss
				JOIN w_DAT_GROUPAGE ON no_rss = RES_OID AND date_trunc('month',date_sortie) = date_trunc('month',RES_DS)
				WHERE p_rss_etat.rss_id = p_rss.oid AND
					date_groupage IS DISTINCT FROM CASE WHEN GRP_DATE >= date_sortie THEN GRP_DATE ELSE '20991231' END;
					
					
					
					
				DROP TABLE IF EXISTS w_FAC_FACTURE;
				CREATE TEMP TABLE w_FAC_FACTURE AS
				SELECT p_rss.oid AS rss_id, p_rss.date_sortie, date(MAX(FACT_DATE)) AS FACT_DATE
				FROM prod_web100t.DAT_DA
						JOIN prod_web100t.FAC_FACTURE ON FACT_DA = DA_OID
						JOIN pmsi.p_rss ON DA_NUMERO = no_sejour_administratif
						WHERE  date_trunc('month',date_sortie) = date_trunc('month',DA_DATE_FIN)
						GROUP BY 1,2;
					
				ALTER TABLE w_FAC_FACTURE ADD CONSTRAINT w_FAC_FACTURE_pkey PRIMARY KEY(rss_id);


				UPDATE pmsi.p_rss_etat
				SET date_facture = CASE WHEN FACT_DATE >= date_sortie AND FACT_DATE <> '20991231' THEN FACT_DATE ELSE '20991231' END,
					est_facture = CASE WHEN FACT_DATE >= date_sortie AND FACT_DATE <> '20991231' THEN '1' ELSE '0' END
				FROM w_FAC_FACTURE
				WHERE p_rss_etat.rss_id = w_FAC_FACTURE.rss_id AND
					(
					date_facture IS DISTINCT FROM CASE WHEN FACT_DATE >= date_sortie AND FACT_DATE <> '20991231' THEN FACT_DATE ELSE '20991231' END
					OR
					est_facture IS DISTINCT FROM CASE WHEN FACT_DATE >= date_sortie AND FACT_DATE <> '20991231' THEN '1' ELSE '0' END
					);	
					

					
				UPDATE pmsi.p_rss_etat
				SET est_groupe = '1', est_valide = '1'
				WHERE est_facture = '1' AND
					(est_groupe = '0' OR est_valide = '0') ;


				UPDATE pmsi.p_rss_etat
				SET date_groupage = date_facture
				WHERE date_facture < date_groupage AND 
					date_facture <> '20991231' AND
					date_groupage <> '20991231';


				UPDATE pmsi.p_rss_etat
				SET date_groupage = '20991231'
				WHERE date_groupage <> '20991231' AND
					est_groupe IN ('0','9');
					
					
				UPDATE pmsi.p_rss
				SET ghm_id = t_ghm_99Z98Z.oid
				FROM pmsi.p_rss_etat, pmsi.t_ghm, pmsi.t_ghm t_ghm_99Z98Z
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					p_rss.ghm_id = t_ghm.oid AND
					t_ghm_99Z98Z.code = '99Z98Z' AND
					est_facture = '1' AND
					t_ghm.code = '99Z99Z' AND
					p_rss.oid NOT IN (
						SELECT rss_id 
						FROM pmsi.p_rsf_detail
						JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
						WHERE t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'AP2', 'FPI', 'FFM', 'ATU')
						);
					
				UPDATE pmsi.p_rss
				SET ghm_id = 0
				FROM pmsi.p_rss_etat, pmsi.t_ghm, pmsi.t_ghm t_ghm_99Z98Z
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					p_rss.en_cours = '1' AND
					p_rss.ghm_id = t_ghm.oid AND
					t_ghm_99Z98Z.code = '99Z98Z' AND
					est_facture = '1' AND
					t_ghm.code = '99Z99Z' AND
					p_rss.oid NOT IN (
						SELECT rss_id 
						FROM pmsi.p_rsf_detail
						JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
						WHERE t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'AP2', 'FPI', 'FFM', 'ATU')
						);
					
				UPDATE pmsi.p_rss
				SET ghm_id = t_ghm_99Z99Z.oid
				FROM pmsi.p_rss_etat, pmsi.t_ghm, pmsi.t_ghm t_ghm_99Z99Z
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					p_rss.ghm_id = t_ghm.oid AND
					t_ghm_99Z99Z.code = '99Z99Z' AND
					en_cours = '1' AND
					t_ghm.code LIKE '90%';
					
				UPDATE pmsi.p_rss
				SET ghm_id = 0
				FROM pmsi.p_rss_etat, pmsi.t_ghm
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					p_rss.en_cours = '1' AND
					p_rss.ghm_id = t_ghm.oid AND
					est_facture = '1' AND
					(t_ghm.code = '99Z99Z' OR ghm_id = 0) AND
					p_rss.oid IN (
						SELECT rss_id 
						FROM pmsi.p_rsf_detail
						JOIN pmsi.t_prestations ON prestation_id = t_prestations.oid
						WHERE t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'APE', 'AP2', 'FPI', 'FFM', 'ATU')
						);
					
					
				UPDATE pmsi.p_rss
				SET en_cours_etat = 'F'
				FROM pmsi.p_rss_etat
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					en_cours = '1' AND
					en_cours_etat IS DISTINCT FROM 'F' AND
					est_facture = 1 ;

										
			]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Etat de la facturation SHS">
			<condition><![CDATA[
				"[ADMPROVIDER]" == "shs" || "[ADMPROVIDER]" == "SHS"
			]]></condition>
			<sqlcmd><![CDATA[
			
			
				DROP TABLE IF EXISTS w_ADP01;
				CREATE TEMP TABLE w_ADP01 AS
				SELECT ADDOSS AS ADDOSS_base,
					to_char(ADDOSS,'FM00000000') AS ADDOSS, 
					CASE WHEN ADDOSS >= 10000000 THEN to_char(ADDOSS,'FM00000000') ELSE to_char(ADDOSS,'FM0000000') END AS ADDOSS2, 
					MAX(to_date(
					CASE 
						WHEN ADCFAC = '1' AND ADDTFA <> 0 THEN to_char(ADDTFA,'FM00000000') 
						WHEN ADCFAC = '1' AND ADDTFA = 0 THEN to_char(now(),'YYYYMMDD')
						ELSE '20991231' END,'YYYYMMDD')) AS ADDTFA
				FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H 
				WHERE ADADAV IN ('0','3')
				GROUP BY 1,2;

				ALTER TABLE w_ADP01 ADD CONSTRAINT w_ADP01_pkey PRIMARY KEY(ADDOSS);
				

				INSERT INTO w_ADP01
				SELECT ADDOSS AS ADDOSS_base,
					to_char(ADDOSS,'FM00000000') AS ADDOSS, 
					CASE WHEN ADDOSS >= 10000000 THEN to_char(ADDOSS,'FM00000000') ELSE to_char(ADDOSS,'FM0000000') END AS ADDOSS2, 
					MAX(to_date(
					CASE 
						WHEN ADCFAC = '1' AND ADDTFA <> 0 THEN to_char(ADDTFA,'FM00000000') 
						WHEN ADCFAC = '1' AND ADDTFA = 0 THEN to_char(now(),'YYYYMMDD')
						ELSE '20991231' END,'YYYYMMDD')) AS ADDTFA
				FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P 
				WHERE ADADAV IN ('0','3') AND
					ADDOSS NOT  IN (SELECT ADDOSS_base FROM w_ADP01)
				GROUP BY 1,2;


				INSERT INTO w_ADP01
				SELECT ADDOSS AS ADDOSS_base,
					to_char(ADDOSS,'FM00000000') AS ADDOSS, 
					CASE WHEN ADDOSS >= 10000000 THEN to_char(ADDOSS,'FM00000000') ELSE to_char(ADDOSS,'FM0000000') END AS ADDOSS2, 
					MAX(to_date(
					CASE 
						WHEN ADCFAC = '1' AND ADDTFA <> 0 THEN to_char(ADDTFA,'FM00000000') 
						WHEN ADCFAC = '1' AND ADDTFA = 0 THEN to_char(now(),'YYYYMMDD')
						ELSE '20991231' END,'YYYYMMDD')) AS ADDTFA
				FROM prod_shs.[ACTIVITESCHEMA]_ADP01
				WHERE ADADAV IN ('0','3') AND
					ADDOSS NOT  IN (SELECT ADDOSS_base FROM w_ADP01)
				GROUP BY 1,2;




				UPDATE pmsi.p_rss_etat
				SET date_facture = CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN ADDTFA ELSE '20991231' END,
					est_facture = CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN '1' ELSE '0' END
				FROM pmsi.p_rss
				JOIN w_ADP01 ON ADDOSS = no_sejour_administratif
				WHERE p_rss_etat.rss_id = p_rss.oid AND
					(
					date_facture IS DISTINCT FROM CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN ADDTFA ELSE '20991231' END
					OR
					est_facture IS DISTINCT FROM CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN '1' ELSE '0' END
					);

				UPDATE pmsi.p_rss_etat
				SET date_facture = CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN ADDTFA ELSE '20991231' END,
					est_facture = CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN '1' ELSE '0' END
				FROM pmsi.p_rss
				JOIN w_ADP01 ON ADDOSS2 = no_sejour_administratif
				WHERE p_rss_etat.rss_id = p_rss.oid AND
					(
					date_facture IS DISTINCT FROM CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN ADDTFA ELSE '20991231' END
					OR
					est_facture IS DISTINCT FROM CASE WHEN ADDTFA >= date_sortie AND ADDTFA <> '20991231' THEN '1' ELSE '0' END
					);


				UPDATE pmsi.p_rss_etat
				SET est_groupe = '1', est_valide = '1'
				WHERE est_facture = '1' AND
					(est_groupe = '0' OR est_valide = '0') ;


				UPDATE pmsi.p_rss_etat
				SET date_groupage = date_facture
				WHERE date_facture < date_groupage AND 
					date_facture <> '20991231' AND
					date_groupage <> '20991231';


				UPDATE pmsi.p_rss_etat
				SET date_groupage = '20991231'
				WHERE date_groupage <> '20991231' AND
					est_groupe IN ('0','9');


				UPDATE pmsi.p_rss
				SET en_cours_etat = 'F'
				FROM pmsi.p_rss_etat
				WHERE p_rss.oid = p_rss_etat.rss_id AND
					en_cours = '1' AND
					en_cours_etat IS DISTINCT FROM 'F' AND
					est_facture = 1 ;

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

</ROOT>
