<?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_TRUM_ID_MEDE'
						,count(*)
					FROM pg_attribute
					WHERE attrelid = (
							SELECT relid
							FROM pg_stat_user_tables
							WHERE schemaname = 'prod_hm'
								AND relname = 'pms_rum'
							)
						AND attname = 'trum_id_mede';
			]]></sqlcmd>
		</NODE>		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[

				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, specialite_interne_id, no_adeli)
				SELECT 
					CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
					MEDE_NOM_USU, 
					COALESCE(MEDE_PRENOM,'') AS MEDE_PRENOM, 
					COALESCE(t_specialites_medecin.oid,0),
					COALESCE(t_specialites_internes_medecin.oid,0),
					COALESCE(MEDI_ADELI,'') AS MEDI_ADELI
				FROM prod_hm.IDE_MEDECIN 
					LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI, MAX(MEDI_ID_CAGE) AS MEDI_ID_CAGE FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB = [ETAB] GROUP BY 1) subview 
						ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
					LEFT JOIN prod_hm.BAS_CATALOGUE_GEN ON (MEDI_ID_CAGE = CAGE_ID_CAGE)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = CAGE_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = CAGE_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON (CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code)
				WHERE 
					MEDE_ID_MEDE IN (SELECT TRSS_ID_MEDE FROM prod_hm.PMS_RSS JOIN prod_hm.IDE_SEJOUR ON (TRSS_ID_SEJO_D = SEJO_ID_SEJO) WHERE SEJO_ID_ETAB_CON = [ETAB] GROUP BY 1)
					AND t_medecins.oid IS NULL;
					
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, specialite_interne_id, no_adeli)
				SELECT 
					CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
					MEDE_NOM_USU, 
					COALESCE(MEDE_PRENOM,'') AS MEDE_PRENOM, 
					COALESCE(t_specialites_medecin.oid,0),
					COALESCE(t_specialites_internes_medecin.oid,0),
					COALESCE(MEDI_ADELI,'') AS MEDI_ADELI
				FROM prod_hm.IDE_MEDECIN 
					LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI, MAX(MEDI_ID_CAGE) AS MEDI_ID_CAGE  FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB = [ETAB] GROUP BY 1) subview 
						ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
					LEFT JOIN prod_hm.BAS_CATALOGUE_GEN ON (MEDI_ID_CAGE = CAGE_ID_CAGE)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = CAGE_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = CAGE_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON (CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code)
				WHERE 
					MEDE_ID_MEDE IN (SELECT SEJO_ID_MEDE_COURANT FROM prod_hm.IDE_SEJOUR WHERE SEJO_ID_ETAB_CON = [ETAB] GROUP BY 1)
					AND t_medecins.oid IS NULL;	
					

				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, specialite_interne_id, no_adeli)
				SELECT 
					CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
					MEDE_NOM_USU, 
					COALESCE(MEDE_PRENOM,'') AS MEDE_PRENOM, 
					COALESCE(t_specialites_medecin.oid,0),
					COALESCE(t_specialites_internes_medecin.oid,0),
					COALESCE(MEDI_ADELI,'') AS MEDI_ADELI
				FROM prod_hm.IDE_MEDECIN 
					LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI, MAX(MEDI_ID_CAGE) AS MEDI_ID_CAGE  FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB = [ETAB] GROUP BY 1) subview 
						ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
					LEFT JOIN prod_hm.BAS_CATALOGUE_GEN ON (MEDI_ID_CAGE = CAGE_ID_CAGE)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = CAGE_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = CAGE_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON (CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code)
				WHERE 
					MEDE_ID_MEDE IN (SELECT LFAC_ID_MEDE_EXE from prod_hm.FAC_LIGNE_FACTURE where LFAC_ID_ETAB_D = [ETAB] AND LFAC_ID_MEDE_EXE > 0 GROUP BY 1)
					AND t_medecins.oid IS NULL;

				INSERT INTO pmsi.t_unites_medicales(code, texte)
				SELECT UNME_CODE, UNME_LIBELLE
				FROM prod_hm.SAD_UM
				WHERE 
					UNME_ID_ETAB = [ETAB] AND
					UNME_CODE NOT IN (SELECT code FROM pmsi.t_unites_medicales)
                ORDER BY UNME_CODE;
                    
                -- Remplacement des Unités médicales par les Unités Fonctionnelles pour les externes
                INSERT INTO pmsi.t_divers (code, texte, valeur, description)
                SELECT
                    'EXT_UF_UM',
                    'Remplacer les UM par les UF pour les externes (HM)',
                    'UM',
                    'UF:unites fonctionnelles, UM:unités médicales'
                WHERE 'EXT_UF_UM' NOT IN (SELECT code FROM pmsi.t_divers);
                ;
                    
				INSERT INTO pmsi.t_unites_medicales(code, texte)
				SELECT UNFO_CODE, UNFO_LIBELLE
				FROM 
                    prod_hm.BAS_UF
                    JOIN pmsi.t_divers ON t_divers.code = 'EXT_UF_UM'
				WHERE 1=1
					AND UNFO_ID_ETAB = [ETAB]
					AND UNFO_CODE NOT IN (SELECT code FROM pmsi.t_unites_medicales)
					AND UNFO_ID_UNME > 0
					AND t_divers.valeur = 'UF'
				ORDER BY 1;
				
				INSERT INTO pmsi.t_prestations(code, texte, texte_court)
				SELECT 
					LFAC_LET_CLE,
					LFAC_LET_CLE,
					LFAC_LET_CLE
				FROM prod_hm.FAC_LIGNE_FACTURE
				WHERE LFAC_ID_PRSE <> 0 AND LFAC_LET_CLE NOT IN (select code from pmsi.t_prestations)
				GROUP BY 1,2,3;
				
				SELECT pmsi.cti_reorganize_medecins_c();
								
				-- maj des établissements insérés juste avec le finess
				UPDATE base.t_etablissements
				SET
					texte = ETEX_NOM,
					texte_court = ETEX_NOM
				FROM 
					prod_hm.IDE_ETABLISSEMENT_EXTERIEUR
				WHERE 1=1 AND
					ETEX_CODE =  t_etablissements.code AND 
					t_etablissements.code = t_etablissements.texte
				;
								
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Identités">
			<sqlcmd><![CDATA[
				
				-- Choix du medecin si plusieurs medecins (parametre dans activite)
				SELECT base.cti_execute('
				UPDATE PROD_HM.IDE_SEJOUR
				SET SEJO_ID_MEDE_COURANT = subview.MESE_ID_MEDE
				FROM
				(
				SELECT MESE_ID_SEJO, (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint AS MESE_ID_MEDE, MAX(SEJO_ID_MEDE_COURANT) AS SEJO_ID_MEDE_COURANT
				FROM prod_hm.IDE_MED_VENUE
				JOIN PROD_HM.IDE_SEJOUR ON MESE_ID_SEJO = SEJO_ID_SEJO
				JOIN prod_hm.BAS_CATALOGUE_PERS ON MESE_ID_CAPE = CAPE_ID_CAPE
				JOIN prod_hm.IDE_MEDECIN  ON MESE_ID_MEDE = MEDE_ID_MEDE
				JOIN activite.t_divers ON t_divers.code = ''HM_MULTIMED'' AND t_divers.valeur = ''1''
				WHERE CAPE_CODE = ''1''
				GROUP BY 1
				HAVING (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint <> MAX(SEJO_ID_MEDE_COURANT)
				) subview
				WHERE SEJO_ID_SEJO = MESE_ID_SEJO
				',1)
				WHERE 't_divers' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'activite')
				;
			
				DROP TABLE IF EXISTS w_PMS_RSS;
				CREATE TEMP TABLE w_PMS_RSS AS
				SELECT TRSS_ID_TRSS, TRSS_NUMERO, MAX(TRSS_ID_MEDE) AS TRSS_ID_MEDE, MAX(TRUM_DAT_SOR_RUM) AS TRSS_DAT_SOR, MAX(TRUM_ID_SEJO) AS TRSS_ID_SEJO
				FROM prod_hm.pms_rss 
					JOIN prod_hm.PMS_RUM ON TRSS_ID_TRSS = TRUM_ID_TRSS

				GROUP BY 1,2;

				CREATE INDEX w_PMS_RSS_i1 ON w_PMS_RSS USING btree (TRSS_NUMERO);



				UPDATE [SCHEMA].p_rss SET no_sejour_administratif = SEJO_NUM_SEJ
				FROM w_PMS_RSS
					JOIN prod_hm.ide_sejour ON trss_id_sejo = sejo_id_sejo
				WHERE p_rss.no_rss = TRSS_NUMERO AND 
					p_rss.date_sortie = date(TRSS_DAT_SOR) AND
					ghm_id <> 0 AND SEJO_DAT_SUP IS NULL AND
					sejo_num_sej IS NOT NULL AND 
					no_sejour_administratif <> SEJO_NUM_SEJ;

			
				UPDATE [SCHEMA].p_rss SET no_sejour_administratif = SEJO_NUM_SEJ
				FROM prod_hm.FAC_FACTURE
					JOIN prod_hm.IDE_SEJOUR ON FACT_ID_SEJO = SEJO_ID_SEJO
				WHERE p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) AND
					ghm_id = 0 AND
                    FACT_NUM_FAC NOT LIKE 'P%' AND
					FACT_NUM_FAC LIKE '%' || no_sejour_administratif AND SEJO_DAT_SUP IS NULL AND
					FACT_NUM_FAC IS NOT NULL AND no_sejour_administratif <> SEJO_NUM_SEJ;
				

				UPDATE [SCHEMA].p_rss SET no_sejour_administratif = SEJO_NUM_SEJ
				FROM prod_hm.IDE_SEJOUR 
				WHERE 
					p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) AND
					SEJO_NUM_SEJ LIKE '%' || no_sejour_administratif AND SEJO_DAT_SUP IS NULL AND
					no_sejour_administratif <> SEJO_NUM_SEJ;
					
					
				UPDATE [SCHEMA].p_identites SET nom = PATI_NOM_USU, prenom = PATI_PRENOM, nom_naissance = CASE WHEN PATI_NOM_NAI <> PATI_NOM_USU THEN PATI_NOM_NAI ELSE '' END
				FROM [SCHEMA].p_rss
					JOIN prod_hm.IDE_SEJOUR ON no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL AND p_rss.date_sortie = date(SEJO_DAT_FIN)
					JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
				WHERE 
					p_identites.rss_id = p_rss.oid AND
					(
						nom IS DISTINCT FROM PATI_NOM_USU OR 
						prenom IS DISTINCT FROM PATI_PRENOM OR 
						nom_naissance IS DISTINCT FROM (CASE WHEN PATI_NOM_NAI <> PATI_NOM_USU THEN PATI_NOM_NAI ELSE '' END)
					)
                ;
					
                UPDATE [SCHEMA].p_rss 
                    SET no_patient = COALESCE(NULLIF(TRIM(IDE_PATIENT.PATI_NIP), ''), '0')::bigint
                FROM prod_hm.IDE_SEJOUR
                    JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
                WHERE 1=1
                AND no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL 
                AND p_rss.date_sortie = date(SEJO_DAT_FIN)                
                AND no_patient IS DISTINCT FROM IDE_PATIENT.PATI_NIP
                ;
				
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Médecins RSS">
			<sqlcmd><![CDATA[

				UPDATE [SCHEMA].p_rss SET medecin_rss_id = t_medecins.oid
				FROM w_PMS_RSS
					JOIN prod_hm.IDE_MEDECIN ON TRSS_ID_MEDE = MEDE_ID_MEDE
					JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE p_rss.no_rss = TRSS_NUMERO AND ghm_id <> 0 AND 
					p_rss.date_sortie = date(TRSS_DAT_SOR) AND
					medecin_rss_id <> t_medecins.oid;
					
					
				UPDATE [SCHEMA].p_rss SET medecin_rss_id = t_medecins.oid
				FROM prod_hm.IDE_SEJOUR
					JOIN prod_hm.IDE_MEDECIN ON SEJO_ID_MEDE_COURANT = MEDE_ID_MEDE
					JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE 1=1
					AND no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL 
					AND p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) 
					AND t_medecins.oid <> medecin_rss_id;
					
					
				UPDATE [SCHEMA].p_rss SET medecin_rss_id = t_medecins.oid
				FROM prod_hm.IDE_SEJOUR
					JOIN prod_hm.IDE_MEDECIN ON SEJO_ID_MEDE_COURANT = MEDE_ID_MEDE
					JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL AND 
					p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) AND
					ghm_id = 0 AND
					t_medecins.oid <> medecin_rss_id;
					
                -- Sans critère sur date de sortie, cas des séjours modifiés depuis la création du lot importé
                UPDATE [SCHEMA].p_rss SET medecin_rss_id = t_medecins.oid
                FROM prod_hm.IDE_SEJOUR
                    JOIN prod_hm.IDE_MEDECIN ON SEJO_ID_MEDE_COURANT = MEDE_ID_MEDE
                    JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
                WHERE 1=1
                    AND no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL 
                    AND p_rss.date_entree = date(SEJO_DAT_DEB)
                    AND ghm_id != 0
                    AND medecin_rss_id = 0;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Médecins actes">
			<sqlcmd><![CDATA[

				UPDATE [SCHEMA].p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM pmsi.t_actes,
					[SCHEMA].p_rss,
					prod_hm.PMS_RSS
					JOIN prod_hm.PMS_RUM ON TRSS_ID_TRSS = TRUM_ID_TRSS
					JOIN prod_hm.IDE_SEJOUR ON TRUM_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTES_SAISIS ON ASAI_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTIVITE_SAISIES ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN prod_hm.IDE_MEDECIN ON ACSA_ID_MEDE = MEDE_ID_MEDE 
					JOIN pmsi.t_medecins ON CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code
				WHERE ghm_id <> 0
					AND TRSS_NUMERO = p_rss.no_rss 
					AND p_rss.date_sortie = date(SEJO_DAT_FIN)
					AND p_rss_actes.rss_id = p_rss.oid
					AND p_rss_actes.date_acte = date(ACSA_DAT_EXE_DEB)
					AND (p_rss_actes.activite_ccam = ACSA_COD_ACT_D OR p_rss_actes.activite_ccam = '1' AND ACSA_COD_ACT_D = 0)
					AND p_rss_actes.acte_id = t_actes.oid
					AND (t_actes.code = ACSA_CODE_D || COALESCE(ACSA_COD_ACT_DESC, ''::text) OR t_actes.code = ACSA_CODE_D)
					AND p_rss_actes.medecin_id <> t_medecins.oid;
					
					
				UPDATE [SCHEMA].p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM pmsi.t_actes,
					[SCHEMA].p_rss,
					prod_hm.IDE_SEJOUR 
					JOIN prod_hm.SAD_ACTES_SAISIS ON ASAI_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTIVITE_SAISIES ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN prod_hm.IDE_MEDECIN ON ACSA_ID_MEDE = MEDE_ID_MEDE 
					JOIN pmsi.t_medecins ON CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code
				WHERE ghm_id = 0 and
					no_sejour_administratif = SEJO_NUM_SEJ
					AND p_rss.date_sortie = date(SEJO_DAT_FIN)
					AND p_rss_actes.rss_id = p_rss.oid
					AND p_rss_actes.date_acte = date(ACSA_DAT_EXE_DEB)
					AND (p_rss_actes.activite_ccam = ACSA_COD_ACT_D OR p_rss_actes.activite_ccam = '1' AND ACSA_COD_ACT_D = 0)
					AND p_rss_actes.acte_id = t_actes.oid
					AND (t_actes.code = ACSA_CODE_D || COALESCE(ACSA_COD_ACT_DESC, ''::text) OR t_actes.code = ACSA_CODE_D)
					AND p_rss_actes.medecin_id <> t_medecins.oid;

		
			]]></sqlcmd>
		</NODE>
		<NODE label="Médecins RUM">
            <condition><![CDATA[
                "[WITH_TRUM_ID_MEDE]" != "0"
            ]]></condition>
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_PMS_RUM;
				CREATE TEMP TABLE w_PMS_RUM AS
				SELECT TRSS_ID_TRSS, TRSS_NUMERO,TRUM_NUMERO,  TRUM_ID_MEDE, TRUM_DAT_SOR_RUM , TRUM_ID_SEJO
				FROM prod_hm.pms_rss 
					JOIN prod_hm.PMS_RUM ON TRSS_ID_TRSS = TRUM_ID_TRSS
				GROUP BY 1,2,3,4,5,6;

				UPDATE [SCHEMA].p_rss_rum SET medecin_rum_id = t_medecins.oid
				FROM w_PMS_RUM
					JOIN prod_hm.IDE_MEDECIN ON TRUM_ID_MEDE = MEDE_ID_MEDE
					JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE p_rss_rum.no_rss = TRSS_NUMERO AND 
					  p_rss_rum.date_sortie = date(TRUM_DAT_SOR_RUM) AND
					  (medecin_rum_id is null or medecin_rum_id = 0);
			]]></sqlcmd>
		</NODE>
		
		<NODE label="UM externes">
			<sqlcmd><![CDATA[
				
				DROP TABLE IF EXISTS w_um_ext;
				CREATE TEMP TABLE w_um_ext AS 
					SELECT
						p_rss.oid as rss_id
						,MAX(COALESCE(t_unites_medicales.oid, 0)) as um_id
					FROM
						[SCHEMA].p_rss
                        JOIN pmsi.t_divers ON t_divers.code = 'EXT_UF_UM'
						JOIN prod_hm.IDE_SEJOUR ON SEJO_NUM_SEJ = p_rss.no_sejour_administratif
							AND p_rss.date_entree::date = SEJO_DAT_DEB::date
							AND p_rss.date_sortie::date = SEJO_DAT_FIN::date
						JOIN prod_hm.BAS_UF ON SEJO_ID_UNFO = UNFO_ID_UNFO AND SEJO_ID_ETAB_CON = UNFO_ID_ETAB
                        JOIN prod_hm.SAD_UM ON UNFO_ID_UNME = UNME_ID_UNME AND UNFO_ID_ETAB = UNME_ID_ETAB
						LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = CASE WHEN t_divers.valeur = 'UF' THEN UNFO_CODE ELSE UNME_CODE END
					WHERE 1=1
						AND p_rss.nb_rum = 1
						AND p_rss.ghm_id = 0
					GROUP BY 1
				;
				
				UPDATE [SCHEMA].p_rss SET
					unite_medicale_principale_id = w_um_ext.um_id
				FROM
					w_um_ext
				WHERE 1=1
					AND w_um_ext.rss_id = p_rss.oid
					AND p_rss.unite_medicale_principale_id IS DISTINCT FROM w_um_ext.um_id
				;
				
				UPDATE [SCHEMA].p_rss_rum SET
					unite_medicale_id = w_um_ext.um_id
				FROM
					w_um_ext
				WHERE 1=1
					AND p_rss_rum.rss_id = w_um_ext.rss_id
					AND p_rss_rum.unite_medicale_id IS DISTINCT FROM w_um_ext.um_id
				;
				
				UPDATE [SCHEMA].p_rsf_detail SET
					unite_medicale_id = w_um_ext.um_id
				FROM
					w_um_ext
				WHERE 1=1
					AND p_rsf_detail.rss_id = w_um_ext.rss_id
					AND p_rsf_detail.unite_medicale_id IS DISTINCT FROM w_um_ext.um_id
				;
				
				DROP TABLE IF EXISTS w_um_ext;
			
			]]></sqlcmd>
		</NODE>
		
	</NODE>
	
	<NODE name="PMSIENCOURS" label="RECUPERATION DES DOSSIERS PMSI EN-COURS HM">
		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[
				-- Choix du medecin si plusieurs medecins (parametre dans activite)
				SELECT base.cti_execute('
				UPDATE PROD_HM.IDE_SEJOUR
				SET SEJO_ID_MEDE_COURANT = subview.MESE_ID_MEDE
				FROM
				(
				SELECT MESE_ID_SEJO, (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint AS MESE_ID_MEDE, MAX(SEJO_ID_MEDE_COURANT) AS SEJO_ID_MEDE_COURANT
				FROM prod_hm.IDE_MED_VENUE
				JOIN PROD_HM.IDE_SEJOUR ON MESE_ID_SEJO = SEJO_ID_SEJO
				JOIN prod_hm.BAS_CATALOGUE_PERS ON MESE_ID_CAPE = CAPE_ID_CAPE
				JOIN prod_hm.IDE_MEDECIN  ON MESE_ID_MEDE = MEDE_ID_MEDE
				JOIN activite.t_divers ON t_divers.code = ''HM_MULTIMED'' AND t_divers.valeur = ''1''
				WHERE CAPE_CODE = ''1''
				GROUP BY 1
				HAVING (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint <> MAX(SEJO_ID_MEDE_COURANT)
				) subview
				WHERE SEJO_ID_SEJO = MESE_ID_SEJO
				',1)
				WHERE 't_divers' IN (SELECT tablename FROM pg_tables WHERE schemaname = 'activite')
				;
			
				DROP TABLE IF EXISTS w_IDE_MEDECIN_used;
				CREATE TEMP TABLE w_IDE_MEDECIN_used AS
				SELECT TRSS_ID_MEDE AS USED_ID_MEDE
				FROM prod_hm.PMS_RSS 
				JOIN prod_hm.IDE_SEJOUR ON (TRSS_ID_SEJO_D = SEJO_ID_SEJO) 
				WHERE SEJO_ID_ETAB_CON = [ETAB]
				GROUP BY 1
				;
				INSERT INTO w_IDE_MEDECIN_used
				SELECT SEJO_ID_MEDE_COURANT 
				FROM prod_hm.IDE_SEJOUR 
				WHERE SEJO_ID_ETAB_CON = [ETAB]
				GROUP BY 1
				;
				INSERT INTO w_IDE_MEDECIN_used
				SELECT LFAC_ID_MEDE_EXE 
				FROM prod_hm.FAC_LIGNE_FACTURE 
				WHERE LFAC_ID_ETAB_D = [ETAB] AND 
					LFAC_ID_MEDE_EXE > 0
				GROUP BY 1
				;
			
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, specialite_interne_id, no_adeli)
				SELECT 
					CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
					MAX(MEDE_NOM_USU), 
					MAX(COALESCE(MEDE_PRENOM,'')) AS MEDE_PRENOM, 
					MAX(COALESCE(t_specialites_medecin.oid,0)),
					MAX(COALESCE(t_specialites_internes_medecin.oid,0)),
					MAX(COALESCE(MEDI_ADELI,'')) AS MEDI_ADELI
				FROM prod_hm.IDE_MEDECIN 
					LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI, MAX(MEDI_ID_CAGE) AS MEDI_ID_CAGE FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB = [ETAB] GROUP BY 1) subview 
						ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
					LEFT JOIN prod_hm.BAS_CATALOGUE_GEN ON (MEDI_ID_CAGE = CAGE_ID_CAGE)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = CAGE_CODE)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = CAGE_CODE || '..')
					LEFT JOIN pmsi.t_medecins ON (CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code)
				WHERE 
					MEDE_ID_MEDE = ANY (SELECT USED_ID_MEDE FROM w_IDE_MEDECIN_used)
					AND t_medecins.oid IS NULL
				GROUP BY 1
				;
					

				INSERT INTO pmsi.t_unites_medicales(code, texte)
				SELECT UNME_CODE, UNME_LIBELLE
				FROM prod_hm.SAD_UM
				WHERE 
					UNME_ID_ETAB = [ETAB] AND
					UNME_CODE NOT IN (SELECT code FROM pmsi.t_unites_medicales)
				ORDER BY UNME_CODE;
				
				INSERT INTO pmsi.t_prestations(code, texte, texte_court)
				SELECT 
					LFAC_LET_CLE,
					LFAC_LET_CLE,
					LFAC_LET_CLE
				FROM prod_hm.FAC_LIGNE_FACTURE
				WHERE LFAC_ID_PRSE <> 0 AND LFAC_LET_CLE NOT IN (select code from pmsi.t_prestations)
				GROUP BY 1,2,3;
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Variables 2020">
		     <condition><![CDATA[
			 	SELECT base.cti_is_column_not_exists('prod_hm', 'pms_rss', 'trss_cod_rescrit_tarifaire');
            ]]></condition>
            <sqlcmd><![CDATA[
	
				-- Variable Passage urgences non présente dans ancienne version HM
				ALTER TABLE prod_hm.pms_rss 
					ADD COLUMN TRSS_COD_CTX_PAT_SURVEILLANCE VARCHAR,
					ADD COLUMN TRSS_COD_ADT_PDT_RES_HOSPIT VARCHAR,
					ADD COLUMN TRSS_COD_RESCRIT_TARIFAIRE VARCHAR,
					ADD COLUMN TRSS_COD_NBR_TOT_INTERVENTION VARCHAR;

			]]></sqlcmd>
		</NODE>
		<NODE label="RSS">
			<sqlcmd><![CDATA[
	
				-- Choix du code FINESS à remonter dans le fil de l'eau (HM ou CTI)
                INSERT INTO pmsi.t_divers (code, texte, valeur, description)
                SELECT
                    'HM_FINESS',
                    'FINESS à utiliser pour les dossiers fil de l''eau',
                    '1',
                    '1=FINESS prod HM, 2=FINESS settings CTI'
                WHERE 'HM_FINESS' NOT IN (SELECT code FROM pmsi.t_divers);
                ;
                
                DROP TABLE IF EXISTS w_finess; 
				CREATE TEMP TABLE w_finess AS
                SELECT MAX(code) AS code FROM base.t_finess WHERE secondaire <> 1;

                -- Identification des RSS (hospit et ambu)
				DROP TABLE IF EXISTS w_rss_select; 
				CREATE TEMP TABLE w_rss_select AS
				SELECT
					TRSS_NUMERO,
					TRSS_ID_TRSS,
					SEJO_ID_SEJO,
					SEJO_NUM_SEJ,
					SEJO_DAT_FIN,
					SEJO_ID_PATI,
					CASE WHEN t_divers_finess.valeur = '1' THEN ETAB_COD_FIN ELSE w_finess.code END AS ETAB_COD_FIN,
					MAX(CASE WHEN TRUM_COD_ADNP is null or TRIM(TRUM_COD_ADNP) = '' THEN '0' ELSE TRUM_COD_ADNP END) as w_TRUM_COD_ADNP,
					MIN(TRUM_DAT_ENT_RUM) as w_DATE_ENTREE,
					MAX(TRUM_DAT_SOR_RUM) as w_DATE_SORTIE,
					MAX(SEJO_ID_MEDE_COURANT) AS SEJO_ID_MEDE_COURANT,
					COALESCE(NULLIF(MAX(TRSS_COD_CTX_PAT_SURVEILLANCE), ''), '0')::smallint AS w_PAT_SURVEILLANCE,
                    COALESCE(NULLIF(MAX(TRSS_COD_ADT_PDT_RES_HOSPIT), ''), '0')::smallint AS w_RES_HOSPIT,
                    COALESCE(NULLIF(MAX(TRSS_COD_RESCRIT_TARIFAIRE), ''), '0')::smallint AS w_RESCRIT_TARIFAIRE,
					COALESCE(MAX(TRSS_COD_NBR_TOT_INTERVENTION), '') AS w_NBR_TOT_INTERVENTION
				FROM prod_hm.PMS_RSS 
					JOIN prod_hm.IDE_SEJOUR ON (TRSS_ID_SEJO_D = SEJO_ID_SEJO AND SEJO_ID_ETAB_CON = [ETAB])
					JOIN prod_hm.BAS_UF ON SEJO_ID_UNFO = UNFO_ID_UNFO AND SEJO_ID_ETAB_CON = UNFO_ID_ETAB
					JOIN prod_hm.BAS_ETABLISSEMENT ON (SEJO_ID_ETAB_CON = ETAB_ID_ETAB)
					JOIN prod_hm.PMS_RUM ON (TRUM_ID_TRSS = TRSS_ID_TRSS)
                    JOIN pmsi.t_divers t_divers_finess ON t_divers_finess.code = 'HM_FINESS'
                    JOIN w_finess ON 1=1
					LEFT JOIN prod_hm.PMS_GHM ON (TRSS_ID_TGHM = TGHM_ID_TGHM)
					LEFT JOIN pmsi.t_divers t_select_ser ON t_select_ser.code = 'FILDELEAU_SER'	
				WHERE (t_select_ser.valeur IS NULL OR t_select_ser.valeur = '' OR replace(UNFO_CODE, ',', '@') = ANY (string_to_array(replace(t_select_ser.valeur,' ',''),','))) 
					AND date(SEJO_DAT_FIN) BETWEEN '[ANNEE]0101' AND date(now()) AND SEJO_DAT_DEB <= date(now()) AND TRSS_NUMERO > 0
					AND SEJO_DAT_DEB <= SEJO_DAT_FIN
					AND SEJO_DAT_SUP IS NULL
					AND COALESCE(TGHM_NUMERO,'') NOT LIKE '28%'
				GROUP BY 1,2,3,4,5,6,7
				HAVING MAX(TRUM_DAT_SOR_RUM) >= '[ANNEE]0101'
				ORDER BY SEJO_NUM_SEJ, TRSS_NUMERO;
				
				INSERT INTO w_rss_select
				SELECT
					TRSS_NUMERO,
					TRSS_ID_TRSS,
					SEJO_ID_SEJO,
					SEJO_NUM_SEJ,
					MAX(TRUM_DAT_SOR_RUM) AS TRUM_DAT_SOR_RUM,
					SEJO_ID_PATI,
					CASE WHEN t_divers_finess.valeur = '1' THEN ETAB_COD_FIN ELSE w_finess.code END AS ETAB_COD_FIN,
					MAX(CASE WHEN TRUM_COD_ADNP is null or TRIM(TRUM_COD_ADNP) = '' THEN '0' ELSE TRUM_COD_ADNP END) as w_TRUM_COD_ADNP,
					MIN(TRUM_DAT_ENT_RUM) as w_DATE_ENTREE,
					MAX(TRUM_DAT_SOR_RUM) as w_DATE_SORTIE,
					MAX(SEJO_ID_MEDE_COURANT) AS SEJO_ID_MEDE_COURANT,
					COALESCE(NULLIF(MAX(TRSS_COD_CTX_PAT_SURVEILLANCE), ''), '0')::smallint AS w_PAT_SURVEILLANCE,
                    COALESCE(NULLIF(MAX(TRSS_COD_ADT_PDT_RES_HOSPIT), ''), '0')::smallint AS w_RES_HOSPIT,
                    COALESCE(NULLIF(MAX(TRSS_COD_RESCRIT_TARIFAIRE), ''), '0')::smallint AS w_RESCRIT_TARIFAIRE,
					COALESCE(MAX(TRSS_COD_NBR_TOT_INTERVENTION), '') AS w_NBR_TOT_INTERVENTION
				FROM prod_hm.PMS_RSS 
					JOIN prod_hm.IDE_SEJOUR ON (TRSS_ID_SEJO_D = SEJO_ID_SEJO AND SEJO_ID_ETAB_CON = [ETAB])
					JOIN prod_hm.BAS_UF ON SEJO_ID_UNFO = UNFO_ID_UNFO AND SEJO_ID_ETAB_CON = UNFO_ID_ETAB
					JOIN prod_hm.BAS_ETABLISSEMENT ON (SEJO_ID_ETAB_CON = ETAB_ID_ETAB)
					JOIN prod_hm.PMS_RUM ON (TRUM_ID_TRSS = TRSS_ID_TRSS)
                    JOIN pmsi.t_divers t_divers_finess ON t_divers_finess.code = 'HM_FINESS'
                    JOIN w_finess ON 1=1
					LEFT JOIN prod_hm.PMS_GHM ON (TRSS_ID_TGHM = TGHM_ID_TGHM)
					LEFT JOIN pmsi.t_divers t_select_ser ON t_select_ser.code = 'FILDELEAU_SER'
				WHERE (t_select_ser.valeur IS NULL OR t_select_ser.valeur = '' OR replace(UNFO_CODE, ',', '@') = ANY (string_to_array(replace(t_select_ser.valeur,' ',''),','))) 
					AND date(TRUM_DAT_SOR_RUM) BETWEEN '[ANNEE]0101' AND date(now()) AND TRUM_DAT_ENT_RUM <= date(now()) AND TRSS_NUMERO > 0
					AND TRUM_DAT_ENT_RUM <= TRUM_DAT_SOR_RUM
					AND SEJO_DAT_SUP IS NULL
					AND COALESCE(TGHM_NUMERO,'') LIKE '28%'
				GROUP BY 1,2,3,4,6,7
				HAVING MAX(TRUM_DAT_SOR_RUM) >= '[ANNEE]0101'
				ORDER BY SEJO_NUM_SEJ, TRSS_NUMERO;

				UPDATE w_rss_select SET w_DATE_SORTIE = SEJO_DAT_FIN WHERE w_DATE_SORTIE IS NULL;
					
				CREATE INDEX w_rss_select_i1 ON w_rss_select USING btree (TRSS_NUMERO);
				CREATE INDEX w_rss_select_i2 ON w_rss_select USING btree (SEJO_NUM_SEJ);
					
				DROP TABLE IF EXISTS w_rss;
				CREATE TEMP TABLE w_rss AS
				SELECT 
					ETAB_COD_FIN AS WRSS_COD_FIN,
					TRSS_ID_TRSS AS WRSS_ID_TRSS,
					TRSS_NUMERO AS WRSS_NUMERO,
					SEJO_ID_SEJO AS WRSS_ID_SEJO,
					SEJO_ID_PATI AS WRSS_ID_PATI,
					w_DATE_ENTREE,
					w_DATE_SORTIE,
					nextval('pmsi.s_rss'::regclass) AS rss_id,
					w_TRUM_COD_ADNP,
					w_PAT_SURVEILLANCE,
					w_RES_HOSPIT,
					w_RESCRIT_TARIFAIRE,
					w_NBR_TOT_INTERVENTION
				FROM w_rss_select
					LEFT JOIN pmsi.p_rss p_rss_1 ON TRSS_NUMERO = p_rss_1.no_rss AND 
                        p_rss_1.etat = '' AND 
                        date_trunc('month',p_rss_1.date_sortie) = date_trunc('month', w_DATE_SORTIE)
					LEFT JOIN pmsi.p_rss p_rss_2 ON SEJO_NUM_SEJ = p_rss_2.no_sejour_administratif AND 
                        p_rss_2.etat = '' AND 
                        date_trunc('month',p_rss_2.date_sortie) = date_trunc('month', w_DATE_SORTIE)
				WHERE 1=1
					AND p_rss_1.no_rss IS NULL
					AND p_rss_2.no_rss IS NULL
				;

				DROP TABLE IF EXISTS w_rss_passage_urgence;
				CREATE TEMP TABLE w_rss_passage_urgence AS
				SELECT rss_id, CAGE_CODE as w_passage_urgences_code
				FROM prod_hm.IDE_MOUVEMENT
					JOIN prod_hm.BAS_CATALOGUE_GEN ON MOUV_ID_CAGE_STRUCT_URGENCES = CAGE_ID_CAGE
					JOIN w_rss ON MOUV_ID_SEJO = WRSS_ID_SEJO
				WHERE w_DATE_SORTIE >= '[ANNEE]0101'
				AND MOUV_ID_CAGE_STRUCT_URGENCES IS NOT NULL
				;
	
				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, 
						ghm_production_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, 
						from_oid,
						raac_id,
						np_id,
						passage_urgences_code,
						contexte_pat_id,
						adm_prod_reshospi_id,
						rescrit_tarif_id,
						nb_intervention_id
						)
				SELECT 
						WRSS_COD_FIN AS finess, 
						w_rss.rss_id AS oid, 
						TRSS_NUMERO AS no_rss, 
                        COALESCE(NULLIF(TRIM(IDE_PATIENT.PATI_NIP), ''), '0')::bigint AS no_patient, 
						'11' AS version_groupage, 
						date(PATI_DAT_NAI) AS date_naissance, 
						CASE WHEN PATI_SEXE = 'F' THEN '2' ELSE '1' END AS sexe, 
						date(w_DATE_ENTREE) AS date_entree, 
						date(w_DATE_SORTIE) AS date_sortie, 
						'8' AS mode_entree, 
						'' AS provenance, 
						'8' AS mode_sortie, 
						'' AS destination, 
						'' AS code_postal, 
						0 AS poids_bebe, 
						0 AS igs2, 
						'' AS cma, 
						substr(TGHM_NUMERO , 3 , 1) AS groupe_ghm, 
						CASE WHEN SEJO_DAT_FIN > w_DATE_ENTREE THEN date(w_DATE_SORTIE) - date(w_DATE_ENTREE) ELSE 0 END AS duree_sejour, 
						CASE WHEN substr(TGHM_NUMERO,1,2) = '28' THEN 1 ELSE 1 END AS nb_rsa, 
						CASE WHEN w_DATE_ENTREE > PATI_DAT_NAI AND trunc((date(w_DATE_ENTREE) - date(PATI_DAT_NAI)) / 365.25,0) BETWEEN 0 AND 120 THEN trunc((date(w_DATE_ENTREE) - date(PATI_DAT_NAI)) / 365.25,0) ELSE 0 END AS age, 
						'' AS supprime, 
						now() AS date_import, 
						1 AS nb_rum, 
						'' AS secteur, 
						SEJO_NUM_SEJ AS no_sejour_administratif, 
						CASE WHEN substr(TGHM_NUMERO,1,2) = '28' THEN 1 ELSE 0 END AS nb_seances, 
						'' AS ghm_fg9, 
						COALESCE(t_ghm.oid, 0) AS ghm_id, 
						0 AS medecin_rss_id, 
						COALESCE(t_ghs.oid, 0) AS ghs_id, 
						date_part('year', w_DATE_SORTIE) * 100 + date_part('month', w_DATE_SORTIE) AS mois_sortie, 
						0 AS diagnostic_principal_id, 
						0 AS diagnostic_relie_id, 
						COALESCE(t_ghm.oid, 0) AS ghm_production_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(TGHM_NUMERO) = 6 AND substr(TGHM_NUMERO,1,2) <> '90' AND (TRSS_ETA_CONFIRMATION = '1' OR TRSS_DAT_SIG IS NOT NULL) THEN 'V' WHEN length(TGHM_NUMERO) = 6 AND substr(TGHM_NUMERO,1,2) <> '90' 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 ERGR_COD_ERR_GRO ~'[A-Z][0-9]*' THEN substring(ERGR_COD_ERR_GRO,2) ELSE ERGR_COD_ERR_GRO END,'') AS code_retour_groupage, 
						0 AS comite_medical_id, 
						'0' AS rehosp_meme_ghm, 
						0 AS from_oid,
						COALESCE(t_raac.oid, 0),
						w_TRUM_COD_ADNP::smallint AS np_id,
						COALESCE(w_passage_urgences_code, '') AS passage_urgences_code,
						w_PAT_SURVEILLANCE AS contexte_pat_id,
						w_RES_HOSPIT AS adm_prod_reshospi_id,
						w_RESCRIT_TARIFAIRE AS rescrit_tarif_id,
						COALESCE(t_nb_interventions.oid, 0) AS nb_intervention_id
				FROM prod_hm.PMS_RSS
						JOIN w_rss ON (WRSS_ID_TRSS = TRSS_ID_TRSS)
						JOIN prod_hm.IDE_SEJOUR ON (WRSS_ID_SEJO = SEJO_ID_SEJO)
						JOIN prod_hm.IDE_PATIENT ON (PATI_ID_PATI = SEJO_ID_PATI)
						LEFT JOIN prod_hm.PMS_GHM ON (TRSS_ID_TGHM = TGHM_ID_TGHM)
						LEFT JOIN (SELECT ERSG_ID_TRSS, (MAX(ARRAY[ERSG_ID_ERSG,ERSG_ID_ERGR]))[2] AS ERSG_ID_ERGR
							FROM prod_hm.PMS_ERR_SEC_GROUP GROUP BY 1) PMS_ERR_SEC_GROUP ON TRSS_ID_TRSS = ERSG_ID_TRSS
						LEFT JOIN prod_hm.PMS_ERR_GROUPAGE ON TRSS_ID_ERGR = ERGR_ID_ERGR
						LEFT JOIN pmsi.t_ghm ON (TGHM_NUMERO = t_ghm.code)
						LEFT JOIN pmsi.t_ghs ON (TRSS_SARGH_NUM_GHS = t_ghs.code)
						LEFT JOIN pmsi.t_raac ON t_raac.code = pms_rss.trss_raac
						LEFT JOIN pmsi.t_np ON t_np.code = w_rss.w_trum_cod_adnp
						LEFT JOIN w_rss_passage_urgence ON w_rss.rss_id = w_rss_passage_urgence.rss_id
                    	LEFT JOIN pmsi.t_nb_interventions ON w_rss.w_NBR_TOT_INTERVENTION = t_nb_interventions.code 
						;
	
				DELETE FROM pmsi.p_rss_leg
				WHERE rss_id IN (SELECT oid FROM pmsi.p_rss WHERE 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_hm.PMS_ERR_SEC_GROUP
					JOIN prod_hm.PMS_RSS ON TRSS_ID_TRSS = ERSG_ID_TRSS
					JOIN prod_hm.PMS_ERR_GROUPAGE ON ERSG_ID_ERGR = ERGR_ID_ERGR
					JOIN prod_hm.IDE_SEJOUR ON TRSS_ID_SEJO_D = SEJO_ID_SEJO
					JOIN pmsi.t_codes_retour_groupeur ON t_codes_retour_groupeur.type || t_codes_retour_groupeur.code = ERGR_COD_ERR_GRO
					JOIN pmsi.p_rss ON SEJO_NUM_SEJ::text = no_sejour_administratif
				WHERE import_id = -1;

				UPDATE pmsi.p_rss SET code_postal = SUBSTR(ADRE_COD_POS, 1 , 5)
				FROM w_rss, prod_hm.IDE_ADRESSE 
				WHERE rss_id = p_rss.oid
					AND WRSS_ID_PATI = ADRE_ID_OBJ;
	
		
				UPDATE pmsi.p_rss SET medecin_rss_id = t_medecins.oid
				FROM prod_hm.PMS_RSS
					JOIN prod_hm.IDE_MEDECIN ON TRSS_ID_MEDE = MEDE_ID_MEDE
				 	JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE p_rss.no_rss = TRSS_NUMERO AND ghm_id <> 0 AND 
					medecin_rss_id = 0 AND t_medecins.oid != 0
				;
					
				UPDATE pmsi.p_rss SET medecin_rss_id = t_medecins.oid
				FROM w_rss_select
					JOIN prod_hm.IDE_MEDECIN ON SEJO_ID_MEDE_COURANT = MEDE_ID_MEDE
					JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE 1=1
					AND p_rss.import_id < 0
					AND w_rss_select.TRSS_NUMERO = p_rss.no_rss 
					AND date(w_DATE_SORTIE) = p_rss.date_sortie
					AND medecin_rss_id = 0
				;
							
				-- Etablissements de provenance et destination
				-- insertion nouveaux etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT * FROM prod_hm.IDE_ETABLISSEMENT_EXTERIEUR LEFT JOIN base.t_etablissements ON ETEX_CODE = code
					WHERE ETEX_ID_ETEX = ANY(array(SELECT SEJO_ID_ETEX_PRO FROM prod_hm.IDE_SEJOUR)::bigint[])
						OR ETEX_ID_ETEX = ANY(array(SELECT SEJO_ID_ETEX_DES FROM prod_hm.IDE_SEJOUR)::bigint[]);
						
				INSERT INTO base.t_etablissements
					(
						code,
						texte,
						texte_court
					)
					SELECT 
						ETEX_CODE,
						ETEX_NOM,
						ETEX_NOM
					FROM w_ETAB
					WHERE code IS NULL;

				-- rechargements des etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT * FROM prod_hm.IDE_ETABLISSEMENT_EXTERIEUR LEFT JOIN base.t_etablissements ON ETEX_CODE = code;
						
				
				/**********************************************************************************
				 *            	 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(MAX(etex_pro.oid),0) as prov_id,
						COALESCE(MAX(etex_des.oid),0) as dest_id						
					FROM prod_hm.IDE_SEJOUR
						JOIN pmsi.p_rss ON SEJO_NUM_SEJ = no_sejour_administratif AND SEJO_NUM_SEJ <> ''
						LEFT JOIN w_ETAB as etex_pro ON SEJO_ID_ETEX_PRO = etex_pro.ETEX_ID_ETEX
						LEFT JOIN w_ETAB as etex_des ON SEJO_ID_ETEX_DES = etex_des.ETEX_ID_ETEX
					WHERE 1=1 AND 
						(SEJO_ID_ETEX_PRO <> 0 OR SEJO_ID_ETEX_DES <> 0) AND
						etat != 'S'
					GROUP BY 1,2
				;
				             
			
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Identités">
			<sqlcmd><![CDATA[

				INSERT INTO pmsi.p_identites(
						finess, 
						rss_id,
						no_rss, 
						nom, 
						prenom, 
						nom_naissance)
				SELECT 
						WRSS_COD_FIN AS finess, 
						w_rss.rss_id AS oid, 
						TRSS_NUMERO AS no_rss, 
						PATI_NOM_USU AS nom, 
						PATI_PRENOM AS prenom, 
						PATI_NOM_NAI AS nom_naissance
				FROM prod_hm.PMS_RSS
					JOIN w_rss ON (WRSS_ID_TRSS = TRSS_ID_TRSS)
					JOIN prod_hm.IDE_PATIENT ON (PATI_ID_PATI = WRSS_ID_PATI);
										
				UPDATE pmsi.p_rss 
						SET no_patient = COALESCE(NULLIF(TRIM(IDE_PATIENT.PATI_NIP), ''), '0')::bigint
				FROM prod_hm.IDE_SEJOUR
						JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
				WHERE 1=1
				AND no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL 
				AND p_rss.date_sortie = date(SEJO_DAT_FIN)                
				AND no_patient IS DISTINCT FROM IDE_PATIENT.PATI_NIP
				;			
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Rum">
			<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_rum
				;
				CREATE TEMP TABLE w_rum AS
					SELECT 
						TRUM_ID_TRSS AS WRUM_ID_TRSS,
						TRUM_NUMERO AS WRUM_NUMERO_ORIGINAL,
						0 AS WRUM_NUMERO,
						0 AS tmp_rum_num,
						0 AS tmp_min_rum_num,
						0 AS tmp_trum_id_mede
					FROM prod_hm.PMS_RUM
						JOIN w_rss ON TRUM_ID_TRSS = WRSS_ID_TRSS
					WHERE TRUM_DAT_SUP IS NULL 
					ORDER BY TRUM_ID_TRSS, TRUM_NUMERO
				;
				DROP SEQUENCE IF EXISTS w_seq
				;
				CREATE TEMP SEQUENCE w_seq
				;
				UPDATE w_rum
				SET tmp_rum_num = nextval('w_seq')
				;
				UPDATE w_rum
				SET 
					tmp_min_rum_num = subq.tmp_min_rum_num
				FROM (
					SELECT
						WRUM_ID_TRSS,
						min(tmp_rum_num) AS tmp_min_rum_num
					FROM w_rum
					GROUP BY WRUM_ID_TRSS
					) AS subq
				WHERE w_rum.WRUM_ID_TRSS = subq.WRUM_ID_TRSS
				;
				UPDATE w_rum
				SET WRUM_NUMERO = tmp_rum_num - tmp_min_rum_num + 1
				;

				SELECT base.cti_execute('
									WITH med_code AS (
										SELECT MEDE_ID_MEDE, coalesce(CASE WHEN MEDE_CODE::text <> '''' THEN MEDE_CODE::text ELSE NULL END, MEDE_ID_MEDE::text) as code
										FROM prod_hm.IDE_MEDECIN
										GROUP BY 1,2
									), new_data AS (
										SELECT 
											trum_id_mede,
											COALESCE(t_medecins.oid,0) as med_id
										FROM prod_hm.PMS_RUM
										JOIN w_rss ON TRUM_ID_TRSS = WRSS_ID_TRSS
										JOIN med_code ON TRUM_ID_MEDE =MEDE_ID_MEDE 
										JOIN pmsi.t_medecins ON t_medecins.code = med_code.code
										WHERE TRUM_DAT_SUP IS NULL
										GROUP BY 1,2
									)
									UPDATE w_rum
									SET tmp_trum_id_mede = med_id
									FROM new_data
									WHERE w_rum.tmp_trum_id_mede = new_data.trum_id_mede
						', 1)
				WHERE (
						SELECT 1
						FROM pg_attribute
						WHERE attrelid = (
								SELECT relid
								FROM pg_stat_user_tables
								WHERE schemaname = 'prod_hm'
									AND relname = 'pms_rum'
								)
							AND attname = 'trum_id_mede'
						) = 1;

				INSERT INTO pmsi.p_rss_rum(
					finess, 
					rss_id, 
					no_rss, 
					no_rum, 
					date_entree, 
					date_sortie, 
					mode_entree, 
					provenance, 
					mode_sortie, 
					destination, 
					duree_sejour, 
					nb_seances, 
					unite_medicale, 
					diagnostic_principal_id, 
					diagnostic_relie_id, 
					unite_medicale_id, 
					type_autorisation, 
					igs2, 
					type_autorisation_lit_dedie, 
					supplement_code,
					medecin_rum_id)
				SELECT
					WRSS_COD_FIN AS finess, 
					w_rss.rss_id AS oid, 
					WRSS_NUMERO AS no_rss, 
					WRUM_NUMERO AS no_rum, 
					date(TRUM_DAT_ENT_RUM) AS date_entree, 
					date(COALESCE(TRUM_DAT_SOR_RUM, w_DATE_SORTIE)) AS date_sortie, 
					CASE WHEN TRUM_MOD_ENT::bigint < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_ENT * 10,1,1)::text END AS mode_entree, 
					CASE WHEN TRUM_MOD_ENT::bigint BETWEEN 1 AND 7 THEN TRUM_MOD_ENT::text WHEN SUBSTR(TRUM_MOD_ENT * 10,2,1)::text <> '0'::text THEN SUBSTR(TRUM_MOD_ENT * 10,2,1)::text ELSE ''::text END AS provenance, 
					CASE WHEN TRUM_MOD_SOR::bigint < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_SOR * 10,1,1)::text END AS mode_sortie, 
					CASE WHEN TRUM_MOD_SOR::bigint BETWEEN 1 AND 7 THEN TRUM_MOD_SOR::text WHEN SUBSTR(TRUM_MOD_SOR * 10,2,1)::text <> '0'::text THEN SUBSTR(TRUM_MOD_SOR * 10,2,1)::text ELSE ''::text END AS destination, 
					CASE WHEN TRUM_DAT_SOR_RUM > TRUM_DAT_ENT_RUM THEN date(TRUM_DAT_SOR_RUM) - date(TRUM_DAT_ENT_RUM) ELSE 0 END AS duree_sejour, 
					TRUM_NOM_SCE AS nb_seances, 
					UNME_CODE AS unite_medicale, 
					0 AS diagnostic_principal_id, 
					0 AS diagnostic_relie_id, 
					COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id, 
					'' AS type_autorisation, 
					TRUM_SCO_IGS AS igs2, 
					'' AS type_autorisation_lit_dedie, 
					'' AS supplement_code,
					tmp_trum_id_mede as medecin_rum_id
				FROM prod_hm.PMS_RUM
					JOIN w_rss ON (TRUM_ID_TRSS = WRSS_ID_TRSS)
					JOIN w_rum ON TRUM_ID_TRSS = WRUM_ID_TRSS AND TRUM_NUMERO = WRUM_NUMERO_ORIGINAL
					LEFT JOIN prod_hm.SAD_UM ON (TRUM_ID_UNME = UNME_ID_UNME)
					LEFT JOIN pmsi.t_unites_medicales ON (UNME_CODE = t_unites_medicales.code)
				WHERE TRUM_DAT_SUP IS NULL;
	
	
				INSERT INTO pmsi.p_rss_rum(
					finess, 
					rss_id, 
					no_rss, 
					no_rum, 
					date_entree, 
					date_sortie, 
					mode_entree, 
					provenance, 
					mode_sortie, 
					destination, 
					duree_sejour, 
					nb_seances, 
					unite_medicale, 
					diagnostic_principal_id, 
					diagnostic_relie_id, 
					unite_medicale_id, 
					type_autorisation, 
					igs2, 
					type_autorisation_lit_dedie, 
					supplement_code,
					medecin_rum_id)
				SELECT
					p_rss.finess AS finess, 
					p_rss.oid AS oid, 
					p_rss.no_rss AS no_rss, 
					1 AS no_rum, 
					p_rss.date_entree AS date_entree, 
					p_rss.date_sortie AS date_sortie, 
					'8' AS mode_entree, 
					'' AS provenance, 
					'8' AS mode_sortie, 
					'' AS destination, 
					p_rss.duree_sejour AS duree_sejour, 
					0 AS nb_seances, 
					'' AS unite_medicale, 
					0 AS diagnostic_principal_id, 
					0 AS diagnostic_relie_id, 
					0 AS unite_medicale_id, 
					'' AS type_autorisation, 
					0 AS igs2, 
					'' AS type_autorisation_lit_dedie, 
					'' AS supplement_code,
					0 AS medecin_rum_id
				FROM pmsi.p_rss
				WHERE en_cours = '1' AND oid NOT IN (select distinct rss_id from pmsi.p_rss_rum);
	

				-- Récupération du premier et dernier RUM
				DROP TABLE IF EXISTS w_rss_rum;
				CREATE TEMP TABLE w_rss_rum AS
				SELECT p_rss_rum.rss_id, 
					count(*) AS nb_rum, 
					MIN(no_rum) AS no_premier_rum,  
					MAX(no_rum) AS no_dernier_rum 
				FROM pmsi.p_rss_rum, pmsi.p_rss 
				WHERE p_rss.oid = p_rss_rum.rss_id AND en_cours = '1'
				GROUP BY 1;
	
				-- MAJ RSS pour premier RUM
				UPDATE pmsi.p_rss 
				SET 
					nb_rum = w_rss_rum.nb_rum,
					no_rum_principal = p_rss_rum.no_rum,
					unite_medicale_principale_id = p_rss_rum.unite_medicale_id,
					mode_entree = p_rss_rum.mode_entree,
					provenance = p_rss_rum.provenance,
					mode_sortie = p_rss_rum.mode_sortie,
					destination = p_rss_rum.destination
				FROM w_rss_rum, pmsi.p_rss_rum
				WHERE p_rss.oid = w_rss_rum.rss_id AND en_cours = '1' AND
					p_rss_rum.rss_id = w_rss_rum.rss_id AND p_rss_rum.no_rum = w_rss_rum.no_premier_rum
				;

				-- MAJ RUM pour premier RUM
				UPDATE pmsi.p_rss_rum
				SET 
					passage_urgences_code = w_passage_urgences_code
				FROM w_rss_rum
				JOIN w_rss_passage_urgence USING(rss_id)
				WHERE p_rss_rum.rss_id = w_rss_rum.rss_id 
					AND p_rss_rum.no_rum = w_rss_rum.no_premier_rum
				;
	
				-- MAJ RSS pour pernier RUM
				UPDATE pmsi.p_rss 
				SET 
					mode_sortie = p_rss_rum.mode_sortie,
					destination = p_rss_rum.destination
				FROM w_rss_rum, pmsi.p_rss_rum
				WHERE p_rss.oid = w_rss_rum.rss_id AND en_cours = '1' AND p_rss.nb_rum > 1 AND
					p_rss_rum.rss_id = w_rss_rum.rss_id AND p_rss_rum.no_rum = w_rss_rum.no_dernier_rum;
					
				-- mise à jour des dates_d'e/s pour les séances			
				UPDATE pmsi.p_rss 
				SET 
					date_entree = p_rss_rum.date_entree
				FROM w_rss_rum, pmsi.p_rss_rum
				WHERE p_rss.oid = w_rss_rum.rss_id AND en_cours = '1' AND p_rss.nb_seances != 0 AND
					p_rss_rum.rss_id = w_rss_rum.rss_id AND p_rss_rum.no_rum = w_rss_rum.no_premier_rum AND
					p_rss.date_entree < p_rss_rum.date_entree;

				UPDATE pmsi.p_rss 
				SET 
					date_sortie = p_rss_rum.date_sortie
				FROM w_rss_rum, pmsi.p_rss_rum
				WHERE p_rss.oid = w_rss_rum.rss_id AND en_cours = '1' AND p_rss.nb_seances != 0 AND
					p_rss_rum.rss_id = w_rss_rum.rss_id AND p_rss_rum.no_rum = w_rss_rum.no_dernier_rum AND
					p_rss.date_sortie > p_rss_rum.date_sortie;	
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Diagnostics">
			<sqlcmd><![CDATA[

				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)
				WITH w_SAD_DIAG_SAISIS AS (
                    SELECT
                        DSAI_ID_DSAI
                        ,DSAI_ID_ADIA
                    FROM
                        prod_hm.SAD_DIAG_SAISIS
                    GROUP BY 1,2
                )
                SELECT
					WRSS_COD_FIN AS finess, 
					w_rss.rss_id AS oid, 
					WRSS_NUMERO AS no_rss, 
					WRUM_NUMERO AS no_rum, 
					COALESCE(t_diagnostics.oid,0) AS diagnostic_id, 
					CASE 
                        WHEN DIRU_TYP_DIA = 'DAS' THEN 'DA' 
                        WHEN DIRU_TYP_DIA = 'DAD' THEN 'DD'
                        WHEN DIRU_TYP_DIA = 'DP' THEN 'DP'
                        WHEN DIRU_TYP_DIA = 'DR' THEN 'DR'
                        ELSE 'DA' END AS type_diagnostic, 
                    CASE 
                        WHEN DIRU_TYP_DIA = 'DAS' THEN 'DA' 
                        WHEN DIRU_TYP_DIA = 'DAD' THEN 'DD'
                        WHEN DIRU_TYP_DIA = 'DP' THEN 'DP'
                        WHEN DIRU_TYP_DIA = 'DR' THEN 'DR'
                        ELSE 'DA' END AS type_diagnostic_rss,
					'' AS imprecis, 
					unite_medicale, 
					unite_medicale_id
				FROM prod_hm.PMS_RUM_DIAG
					JOIN prod_hm.PMS_RUM ON (DIRU_ID_TRUM = TRUM_ID_TRUM)
					JOIN w_rss ON (TRUM_ID_TRSS = WRSS_ID_TRSS)
					JOIN w_rum ON TRUM_ID_TRSS = WRUM_ID_TRSS AND TRUM_NUMERO = WRUM_NUMERO_ORIGINAL
					JOIN w_SAD_DIAG_SAISIS ON (DIRU_ID_DSAI = w_SAD_DIAG_SAISIS.DSAI_ID_DSAI)
					JOIN prod_hm.SAD_DIAG ON (w_SAD_DIAG_SAISIS.DSAI_ID_ADIA = ADIA_ID_ADIA)
					JOIN pmsi.t_diagnostics ON (ADIA_CODE = t_diagnostics.code)
					JOIN pmsi.p_rss_rum ON (w_rss.rss_id = p_rss_rum.rss_id AND WRUM_NUMERO = p_rss_rum.no_rum)
				WHERE  DIRU_TYP_DIA IN ('DP', 'DR', 'DAS', 'DAD')
				ORDER BY w_rss.rss_id, WRUM_NUMERO;
	
	
				UPDATE pmsi.p_rss_rum
				SET diagnostic_principal_id = p_rss_diagnostics.diagnostic_id
				FROM pmsi.p_rss, pmsi.p_rss_diagnostics
				WHERE p_rss_rum.rss_id = p_rss.oid AND
					p_rss.en_cours = '1' AND
					p_rss_diagnostics.rss_id = p_rss_rum.rss_id AND
					p_rss_diagnostics.no_rum = p_rss_rum.no_rum AND 
					p_rss_diagnostics.type_diagnostic = 'DP';
	
	
				UPDATE pmsi.p_rss_rum
				SET diagnostic_relie_id = p_rss_diagnostics.diagnostic_id
				FROM pmsi.p_rss, pmsi.p_rss_diagnostics
				WHERE p_rss_rum.rss_id = p_rss.oid AND
					p_rss.en_cours = '1' AND
					p_rss_diagnostics.rss_id = p_rss_rum.rss_id AND
					p_rss_diagnostics.no_rum = p_rss_rum.no_rum AND 
					p_rss_diagnostics.type_diagnostic = 'DR';
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Actes">
			<sqlcmd><![CDATA[

				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
					WRSS_COD_FIN AS finess, 
					w_rss.rss_id AS oid, 
					WRSS_NUMERO AS no_rss, 
					WRUM_NUMERO AS no_rum, 
					p_rss_rum.unite_medicale AS unite_medicale, 
					p_rss_rum.unite_medicale_id AS unite_medicale_id, 
					date(ACSA_DAT_EXE_DEB) AS date_acte, 
					COALESCE(t_medecins.oid,0) AS medecin_id,
					COALESCE(t_actes.oid,0) AS acte_id, 
					ACSA_QTE_COEFFICIENT AS nombre, 
					ASAI_NUM_PHAS AS phase_ccam, 
					ACSA_COD_ACT_D AS activite_ccam, 
					CASE WHEN char_length(ACSA_EXT_DOC) > 1 THEN ''::text ELSE ACSA_EXT_DOC END AS extension_ccam, 
					ACSA_MODIF1 AS modificateur_ccam_1, 
					ACSA_MODIF2 AS modificateur_ccam_2, 
					ACSA_MODIF3 AS modificateur_ccam_3, 
					ACSA_MODIF4 AS modificateur_ccam_4, 
					ACSA_IND_RMB_EXCEPTIONNEL AS remboursement_excp_ccam, 
					CASE WHEN ACSA_ASS_NON_PREV < 99 THEN ACSA_ASS_NON_PREV ELSE '' END  AS association_nonprevue_ccam
				FROM prod_hm.SAD_ACTIVITE_SAISIES
					JOIN w_rss ON (ACSA_ID_SEJO = WRSS_ID_SEJO)
					JOIN prod_hm.SAD_ACTES_SAISIS ON (ACSA_ID_ASAI = ASAI_ID_ASAI)		
					JOIN prod_hm.PMS_RUM ON (ASAI_ID_TRUM = TRUM_ID_TRUM)
					JOIN w_rum ON WRSS_ID_TRSS = WRUM_ID_TRSS AND TRUM_NUMERO = WRUM_NUMERO_ORIGINAL
					JOIN pmsi.p_rss_rum ON (w_rss.rss_id = p_rss_rum.rss_id AND WRUM_NUMERO = p_rss_rum.no_rum)
					JOIN pmsi.t_actes ON (ACSA_CODE_D || COALESCE(ACSA_COD_ACT_DESC, ''::text) = t_actes.code)
					JOIN prod_hm.IDE_MEDECIN ON ACSA_ID_MEDE = MEDE_ID_MEDE
					LEFT JOIN pmsi.t_medecins ON (CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END = t_medecins.code);
					
					
				
				UPDATE pmsi.p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM pmsi.t_actes,
					pmsi.p_rss,
					prod_hm.PMS_RSS
					JOIN prod_hm.PMS_RUM ON TRSS_ID_TRSS = TRUM_ID_TRSS
					JOIN prod_hm.IDE_SEJOUR ON TRUM_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTES_SAISIS ON ASAI_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTIVITE_SAISIES ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN prod_hm.IDE_MEDECIN ON ACSA_ID_MEDE = MEDE_ID_MEDE 
					JOIN pmsi.t_medecins ON CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code
				WHERE en_cours = '1'
					AND TRSS_NUMERO = p_rss.no_rss 
					AND p_rss.date_sortie = date(SEJO_DAT_FIN)
					AND p_rss_actes.rss_id = p_rss.oid
					AND p_rss_actes.date_acte = date(ACSA_DAT_EXE_DEB)
					AND p_rss_actes.activite_ccam = ACSA_COD_ACT_D
					AND p_rss_actes.acte_id = t_actes.oid
					AND (t_actes.code = ACSA_CODE_D || COALESCE(ACSA_COD_ACT_DESC, ''::text) OR t_actes.code = ACSA_CODE_D)
					AND p_rss_actes.medecin_id <> t_medecins.oid;
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Factures">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_rsf_3;
				CREATE TEMP TABLE w_rsf_3 AS
				SELECT 
					WRSS_COD_FIN, 
					w_rss.rss_id AS rss_id, 
					WRSS_NUMERO,  
					FACT_NUM_FAC, 
					FACT_ID_SEJO,
					LFAC_ID_LFAC,
					LFAC_ID_PRSE,
					LFAC_ID_PRHO,
					LFAC_LET_CLE,
					LFAC_DAT_EXE_DEB,
					LFAC_DAT_EXE_FIN,
					LFAC_PRI_UNITAIRE,
					LFAC_QTE_COEFFICIENT,
					LFAC_COE_MCO_HAD,
					LFAC_NUM_GHS,
					LFAC_MTT_BAS_RMB AS LFAC_MTT_BAS_RMB,
					LFAD_TAUX AS LFAD_TAUX,
					LFAD_MTT_HOR_DEH,
					LFAC_COD_LPP,
                    LFAC_ID_FACT
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_FACTURE ON (LFAC_ID_FACT = FACT_ID_FACT)
					JOIN w_rss ON (FACT_ID_SEJO = WRSS_ID_SEJO)
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON (FACD_ID_FACT = FACT_ID_FACT)
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON (LFAD_ID_FACD = FACD_ID_FACD AND LFAD_ID_LFAC = LFAC_ID_LFAC)
				WHERE FACT_DAT_SUP IS NULL AND FACT_TYPE <> 'P' AND FACT_TYPE <> 'E' AND FACD_ID_ORGA_AMO <> 0 AND LFAC_MTT_BAS_RMB <> 0 AND
					LFAC_LET_CLE = ANY(ARRAY['GHS','EXH','SRC','REA','STF','NN1','NN2','NN3']) 
				;
	
				-- suppression factures seances dont l'execution ne correspondant au date rss
				DELETE FROM w_rsf_3 USING pmsi.p_rss
				WHERE 
					rss_id = p_rss.oid
					AND p_rss.nb_seances != 0
					AND LFAC_DAT_EXE_DEB != date_entree
					AND LFAC_DAT_EXE_FIN != date_sortie;
	
				DROP TABLE IF EXISTS w_rsf_5;
				CREATE TEMP TABLE w_rsf_5 AS
				SELECT 
					WRSS_COD_FIN, 
					rss_id, 
					WRSS_NUMERO,  
					MIN(FACT_NUM_FAC) AS FACT_NUM_FAC, 
					1 AS rang, 
					MAX('01') AS grand, 
					MAX('1') AS assurance, 
					MAX('0') AS exoneration, 
					MIN('1') AS operation, 
					MAX('') AS matricule, 
					MAX('') AS cle,
					SUM(CASE WHEN LFAC_ID_PRSE <> 0 THEN LFAC_MTT_BAS_RMB ELSE 0 END) AS FACT_MTT_SEJ,
					SUM(CASE WHEN LFAC_ID_PRHO <> 0 THEN LFAC_MTT_BAS_RMB ELSE 0 END) AS FACT_MTT_HON
				FROM w_rsf_3
				GROUP BY 1,2,3;
	
	
				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 
						WRSS_COD_FIN AS finess, 
						rss_id AS oid, 
						WRSS_NUMERO AS no_rss,  
						'1' AS code_pec, 
						w_rsf_5.rang AS rang_beneficiaire, 
						w_rsf_5.grand AS regime, 
						w_rsf_5.assurance AS nature_pec, 
						w_rsf_5.exoneration AS justificatif_exo, 
						w_rsf_5.FACT_NUM_FAC AS no_facture, 
						w_rsf_5.operation AS code_regularisation, 
						w_rsf_5.matricule AS matricule_assure, 
						w_rsf_5.cle AS cle_matricule_assure, 
						FACT_MTT_SEJ AS base_remboursement, 
						FACT_MTT_SEJ AS sejour_facture, 
						FACT_MTT_SEJ AS sejour_remboursable, 
						FACT_MTT_HON AS honoraires_factures, 
						FACT_MTT_HON 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_rsf_5;
	
	
				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">
			<sqlcmd><![CDATA[

				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_rsf_3.WRSS_COD_FIN AS finess, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.WRSS_NUMERO, 
						'' AS nature, 
						'' AS mt, 
						'' AS dmt, 
						date(LFAC_DAT_EXE_DEB) AS date_debut, 
						date(LFAC_DAT_EXE_FIN) AS date_fin, 
						LFAC_QTE_COEFFICIENT AS nombre, 
						1 AS coefficient, 
						w_rsf_3.LFAC_PRI_UNITAIRE AS prix_unitaire, 
						w_rsf_3.LFAC_MTT_BAS_RMB AS base_remboursement, 
						to_number(w_rsf_3.LFAD_TAUX,'000') AS taux_remboursement, 
						w_rsf_3.LFAC_MTT_BAS_RMB AS sejour_facture, 
						w_rsf_3.LFAD_MTT_HOR_DEH AS sejour_remboursable, 
						0 AS compteur, 
						'' AS ligne_t2a, 
						'' AS pec_fj, 
						CASE WHEN w_rsf_3.LFAC_COE_MCO_HAD > 0 THEN w_rsf_3.LFAC_COE_MCO_HAD ELSE 1 END 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 w_rsf_3
					JOIN pmsi.t_prestations ON (w_rsf_3.LFAC_LEt_CLE = t_prestations.code)
					LEFT JOIN pmsi.t_ghs ON (to_number('0' || w_rsf_3.LFAC_NUM_GHS,'0000') = t_ghs.code)
				WHERE LFAC_ID_PRSE <> 0;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="LPP">
			<sqlcmd><![CDATA[

				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_rsf_3.WRSS_COD_FIN AS finess, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.WRSS_NUMERO, 
						0 AS rang, 
						date(LFAC_DAT_EXE_DEB) AS date_lpp, 
						COALESCE(t_lpp.oid, 0) AS lpp_id, 
						LFAC_QTE_COEFFICIENT AS nombre, 
						w_rsf_3.LFAC_PRI_UNITAIRE AS prix_unitaire, 
						w_rsf_3.LFAC_MTT_BAS_RMB AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM w_rsf_3
					LEFT JOIN pmsi.t_lpp ON (LFAC_COD_LPP = t_lpp.code)
				WHERE LFAC_COD_LPP <> '';	
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="UCD">
			<sqlcmd><![CDATA[
                
                -- Attention, quand avois,pas d'ucd donc seulement les UCD de la dernière facture calculée
                DROP TABLE IF EXISTS w_FAC_FACTURE_lastucd;
                CREATE TEMP TABLE w_FAC_FACTURE_lastucd AS
                SELECT FACT_ID_SEJO, (MAX(ARRAY[FACT_DAT_FAC::text, FACT_ID_FACT::text]))[2]::bigint AS FACT_ID_FACT_last
                FROM prod_hm.FAC_LIGNE_FACTURE
                JOIN prod_hm.FAC_LIGNE_FACTURE_UCD ON LFUC_id_lfac = lfac_id_lfac
                JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAD_ID_LFAC = LFAC_ID_LFAC
                JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
                JOIN prod_hm.IDE_SEJOUR ON sejo_id_sejo = fact_id_sejo
                WHERE FACT_DAT_SUP IS NULL AND FACT_TYPE <> 'P' AND FACT_TYPE <> 'E' AND  LFAC_MTT_BAS_RMB <> 0
                GROUP BY 1;

				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_rsf_3.WRSS_COD_FIN AS finess, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.WRSS_NUMERO, 
						0 AS rang, 
						MAX(date(LFAC_DAT_EXE_DEB)) AS date_ucd, 
						MAX(COALESCE(t_ucd.oid,0)) AS ucd_id, 
						MAX(LFUC_QUANTITE) AS nombre, 
						MAX(LFUC_COEFFICIENT) AS coefficient_fractionnement, 
						MAX(LFUC_VLR_REFERENCE) AS prix_unitaire_achat, 
						MAX(LFUC_MTT_EUI) AS prix_unitaire_ecart_indemnisable, 
						MAX(LFUC_MTT_EMI) AS montant_ecart_indemnisable, 
						MAX(LFUC_MTT_FACTURE) AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM w_rsf_3
					JOIN prod_hm.FAC_LIGNE_FACTURE_UCD ON LFAC_ID_LFAC = LFUC_ID_LFAC
                    JOIN w_FAC_FACTURE_lastucd ON LFAC_ID_FACT = FACT_ID_FACT_last
					LEFT JOIN pmsi.t_ucd ON (LFUC_COD_UCD = t_ucd.code)
                GROUP BY 1,2,3;	
										
			]]></sqlcmd>
		</NODE>
			
		<NODE label="Identification des externes">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_rss_externes_numsej;
                CREATE TEMP TABLE w_rss_externes_numsej AS
                SELECT p_rss.*
                FROM pmsi.p_rss
                LEFT JOIN prod_hm.IDE_SEJOUR ON no_sejour_administratif = SEJO_NUM_SEJ AND
                     (p_rss.date_entree = date(SEJO_DAT_DEB) OR p_rss.date_sortie = date(SEJO_DAT_FIN))
                WHERE ghm_id = 0 AND
                    en_cours = '0' AND
                    SEJO_ID_SEJO IS NULL
                ;

				UPDATE w_rss_externes_numsej p_rss SET no_sejour_administratif = SEJO_NUM_SEJ
				FROM prod_hm.FAC_FACTURE
					JOIN prod_hm.IDE_SEJOUR ON FACT_ID_SEJO = SEJO_ID_SEJO
				WHERE p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) AND
					ghm_id = 0 AND
					FACT_NUM_FAC LIKE '%' || no_sejour_administratif AND SEJO_DAT_SUP IS NULL AND
					FACT_NUM_FAC IS NOT NULL AND no_sejour_administratif <> SEJO_NUM_SEJ
                ;

                UPDATE pmsi.p_rss 
                SET no_sejour_administratif = w_rss_externes_numsej.no_sejour_administratif
                FROM w_rss_externes_numsej
                WHERE p_rss.oid = w_rss_externes_numsej.oid AND
                    p_rss.no_sejour_administratif IS DISTINCT FROM w_rss_externes_numsej.no_sejour_administratif
                    ;


				DROP TABLE IF EXISTS w_rss_hm;
				CREATE TEMP TABLE w_rss_hm AS
				SELECT *
				FROM pmsi.p_rss
					LEFT JOIN prod_hm.IDE_SEJOUR ON 
						no_sejour_administratif = SEJO_NUM_SEJ AND SEJO_DAT_SUP IS NULL AND 
							(p_rss.date_entree = date(SEJO_DAT_DEB) OR p_rss.date_sortie = date(SEJO_DAT_FIN))
				;
					
				UPDATE pmsi.p_identites SET nom = PATI_NOM_USU, prenom = PATI_PRENOM, nom_naissance = CASE WHEN PATI_NOM_NAI <> PATI_NOM_USU THEN PATI_NOM_NAI ELSE '' END
				FROM w_rss_hm
					JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
				WHERE 
					p_identites.rss_id = w_rss_hm.oid AND
					(
						nom IS DISTINCT FROM PATI_NOM_USU OR 
						prenom IS DISTINCT FROM PATI_PRENOM OR 
						nom_naissance IS DISTINCT FROM (CASE WHEN PATI_NOM_NAI <> PATI_NOM_USU THEN PATI_NOM_NAI ELSE '' END)
					); 


				UPDATE pmsi.p_rss 
				SET medecin_rss_id = t_medecins.oid
				FROM w_rss_hm
				 	JOIN prod_hm.IDE_MEDECIN ON SEJO_ID_MEDE_COURANT = MEDE_ID_MEDE
				 	JOIN pmsi.t_medecins ON t_medecins.code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END
				WHERE p_rss.oid = w_rss_hm.oid AND
				 	p_rss.ghm_id = 0 AND
					t_medecins.oid != 0 AND p_rss.medecin_rss_id = 0;
					
				UPDATE pmsi.p_rss
				SET code_postal = SUBSTR(ADRE_COD_POS,1,5)
				FROM w_rss_hm
					JOIN prod_hm.IDE_ADRESSE ON SEJO_ID_PATI = ADRE_ID_OBJ AND length(ADRE_COD_POS) >= 5
				WHERE p_rss.oid = w_rss_hm.oid
					AND p_rss.ghm_id = 0 
					AND p_rss.code_postal IS DISTINCT FROM SUBSTR(ADRE_COD_POS,1,5);

				UPDATE pmsi.p_rss
				SET code_postal = '0' || ADRE_COD_POS
				FROM w_rss_hm
					JOIN prod_hm.IDE_ADRESSE ON SEJO_ID_PATI = ADRE_ID_OBJ AND length(ADRE_COD_POS) = 4
				WHERE p_rss.oid = w_rss_hm.oid
					AND p_rss.ghm_id = 0 
					AND p_rss.code_postal IS DISTINCT FROM ('0' || ADRE_COD_POS);
					

				UPDATE pmsi.p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM pmsi.t_actes,
					w_rss_hm
					JOIN prod_hm.SAD_ACTES_SAISIS ON ASAI_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.SAD_ACTIVITE_SAISIES ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN prod_hm.IDE_MEDECIN ON ACSA_ID_MEDE = MEDE_ID_MEDE 
					JOIN pmsi.t_medecins ON CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE::text ELSE MEDE_ID_MEDE::text END  = t_medecins.code
				WHERE ghm_id = 0
					AND p_rss_actes.rss_id = w_rss_hm.oid
					AND p_rss_actes.date_acte = date(ACSA_DAT_EXE_DEB)
					AND p_rss_actes.activite_ccam = ACSA_COD_ACT_D
					AND p_rss_actes.acte_id = t_actes.oid
					AND (t_actes.code = ACSA_CODE_D || COALESCE(ACSA_COD_ACT_DESC, ''::text) OR t_actes.code = ACSA_CODE_D)
					AND p_rss_actes.medecin_id <> t_medecins.oid;
					
				UPDATE pmsi.p_rss 
				SET medecin_rss_id = 
				CASE WHEN 
					(SELECT medecin_id FROM pmsi.v_rss_actes_1 WHERE activite_ccam <> '4' AND v_rss_actes_1.rss_id = p_rss.oid ORDER BY icr DESC LIMIT 1) > 0 
					THEN (SELECT medecin_id FROM pmsi.v_rss_actes_1 WHERE activite_ccam <> '4' AND v_rss_actes_1.rss_id = p_rss.oid ORDER BY icr DESC LIMIT 1) 
					ELSE p_rss.medecin_rss_id END 
				WHERE ghm_id = 0 AND medecin_rss_id = 0;	
					
				
				
										
			]]></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_PMS_RSS;
				CREATE TEMP TABLE w_PMS_RSS AS
				SELECT TRSS_ID_TRSS, 
					TRSS_NUMERO, 
					MAX(date(SEJO_DAT_FIN)) AS SEJO_DAT_FIN,
					MAX(CASE WHEN TGHM_NUMERO <> '' AND TGHM_NUMERO NOT LIKE '90%' THEN COALESCE(date(TRUM_DAT_DER_GROUPAGE),'20991231') ELSE '20991231' END) AS date_groupage
				FROM prod_hm.pms_rss 
					JOIN prod_hm.IDE_SEJOUR ON TRSS_ID_SEJO_D = SEJO_ID_SEJO
					JOIN prod_hm.PMS_RUM ON TRSS_ID_TRSS = TRUM_ID_TRSS
					JOIN prod_hm.PMS_GHM ON (TRSS_ID_TGHM = TGHM_ID_TGHM)
				GROUP BY 1,2;

				CREATE INDEX w_PMS_RSS_i1 ON w_PMS_RSS USING btree (TRSS_NUMERO);

				UPDATE pmsi.p_rss_etat SET
					date_groupage = w_PMS_RSS.date_groupage
				FROM w_PMS_RSS
				JOIN pmsi.p_rss ON w_PMS_RSS.TRSS_NUMERO = p_rss.no_rss AND w_PMS_RSS.SEJO_DAT_FIN = p_rss.date_sortie
				WHERE p_rss_etat.rss_id = p_rss.oid AND
					p_rss_etat.date_groupage <> w_PMS_RSS.date_groupage;

				DROP TABLE IF EXISTS w_sejo_fac;
				CREATE TEMP TABLE w_sejo_fac AS
				SELECT
					SEJO_NUM_SEJ,
					date(SEJO_DAT_DEB) AS SEJO_DAT_DEB, date(SEJO_DAT_FIN) AS SEJO_DAT_FIN,
					COALESCE(MAX(GREATEST(date(FACT_DAT_IMPRESSION), date(FACT_DAT_DER_CALCUL))),'20991231') AS date_facture
				FROM prod_hm.IDE_SEJOUR
				JOIN prod_hm.FAC_FACTURE ON SEJO_ID_SEJO = FACT_ID_SEJO AND FACT_TYPE = 'F'
				GROUP BY 1,2,3;


					
				UPDATE pmsi.p_rss_etat SET
					date_facture = subview.date_facture, 
					est_facture = CASE WHEN subview.date_facture != '20991231' OR en_cours <> '1' THEN '1' ELSE '0' END
				FROM (
					SELECT
						p_rss.oid AS rss_id,
						p_rss.en_cours,
						COALESCE(MAX(date_facture),'20991231') AS date_facture
					FROM pmsi.p_rss
					LEFT JOIN w_sejo_fac ON SEJO_NUM_SEJ = no_sejour_administratif AND date_sortie = SEJO_DAT_FIN
					GROUP BY 1,2) subview
				WHERE p_rss_etat.rss_id = subview.rss_id AND
					(
					p_rss_etat.date_facture IS DISTINCT FROM subview.date_facture OR
					p_rss_etat.est_facture IS DISTINCT FROM CASE WHEN subview.date_facture != '20991231' OR en_cours <> '1' 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>
