<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	

	<NODE name="PMSICOMPLEMENTS" label="RECUPERATION DES DONNEES COMPLEMENTAIRES PMSI">
		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_etb;
				CREATE TEMP TABLE w_etb AS
				SELECT 
					ETB_ID as w_etb_id,
					ETB_FINESS as w_etb_finess
				FROM
					prod_cegi.CJ_ETB
				WHERE
					ETB_FINESS = '[FINESS]';
					
				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				SELECT 
					cj_pra.pra_libc,
					MAX(per_nom),
					MAX(COALESCE(per_prenom, '')),
					MAX(COALESCE(t_specialites_medecin.oid,0)),
					MAX(COALESCE(cj_prc.prc_identification, '')),
					MAX(COALESCE(t_specialites_internes_medecin.oid,0))
				FROM prod_cegi.cj_pra 
					LEFT JOIN prod_cegi.cj_prc ON (cj_pra.pra_id = cj_prc.pra_id)
					LEFT JOIN prod_cegi.cj_spe ON (cj_pra.spe_id = cj_spe.spe_id)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = spe_libc)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = spe_libc || '..')
					LEFT JOIN pmsi.t_medecins ON (cj_pra.pra_libc = t_medecins.code)
				WHERE 1=1
					AND cj_pra.pra_id IN (
							SELECT RUM.pra_id
							FROM prod_cegi.rum
						UNION
							SELECT CJ_PRA_SUBQ.pra_id
							FROM prod_cegi.CJ_PRA AS CJ_PRA_SUBQ
								JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.TER_ID = CJ_PRA_SUBQ.TER_ID
						GROUP BY 1)
					AND t_medecins.code IS NULL
				GROUP BY 1;
				
				UPDATE pmsi.t_medecins SET
					nom = PER_NOM,
					prenom = PER_PRENOM
				FROM prod_cegi.CJ_PRA 
				WHERE t_medecins.code = CJ_PRA.PRA_LIBC AND
					(
					nom IS DISTINCT FROM PER_NOM OR
					prenom IS DISTINCT FROM PER_PRENOM
					)
				;
                
                -- patients
                DROP TABLE IF EXISTS w_CJ_PATIENT;
                CREATE TEMP TABLE w_CJ_PATIENT AS 
                SELECT
                    pat_id
                    ,MAX(pat_ipp) as pat_ipp
                    ,MAX(per_nom) as per_nom
                    ,MAX(per_prenom) as per_prenom
                    ,MAX(per_nomjf) as per_nomjf
                    ,MAX(per_cp) as per_cp
                    ,MAX(per_naissance) as per_naissance
                    ,MAX(pat_sexe) as per_sexe
                FROM
                    prod_cegi.CJ_PATIENT
                GROUP BY 1;
                
                CREATE INDEX w_CJ_PATIENT_i1
				  ON w_CJ_PATIENT
				  USING btree
				  (pat_id)
				;

				-- Unités médicales
				SELECT base.cti_execute('
					UPDATE pmsi.t_unites_medicales SET
					texte = UM.LIB
				FROM
					prod_cegi.UM
				WHERE 1=1
					AND UM.CODE = t_unites_medicales.code
					AND t_unites_medicales.code = t_unites_medicales.texte
					AND t_unites_medicales.texte IS DISTINCT FROM UM.LIB',1)
				WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0
				;
					
				-- maj des établissements insérés juste avec le finess
				UPDATE base.t_etablissements
				SET
					texte = FNS_NOM,
					texte_court = FNS_NOM
				FROM 
					prod_cegi.CJ_FINESS
				WHERE 1=1 AND
					FNS_FINESS =  t_etablissements.code AND 
					t_etablissements.code = t_etablissements.texte
				;

			]]></sqlcmd>
		</NODE>
		
		
		
		
		
		<NODE label="Identités">
			<sqlcmd><![CDATA[
				
				-- Séjour mal alimenté dans RSS IN
				UPDATE [SCHEMA].p_rss SET
					no_sejour_administratif = CASE WHEN p_rss.no_sejour_administratif IN ('','0') THEN subview.no_sejour_administratif ELSE p_rss.no_sejour_administratif END,
					rss_mere_id = CASE WHEN p_rss.rss_mere_id = 0 THEN subview.rss_mere_id ELSE p_rss.rss_mere_id END
				FROM
				(
					SELECT p_rss_nne.oid, p_rss_mere.no_sejour_administratif, p_rss_mere.oid AS rss_mere_id
					FROM prod_cegi.parente
					JOIN prod_cegi.rss rss_mere ON n_rss_mere = rss_mere.n_rss
					JOIN prod_cegi.rss rss_nne ON n_rss_nne = rss_nne.n_rss
					JOIN [SCHEMA].p_rss p_rss_mere ON 
						p_rss_mere.no_rss = n_rss_mere AND
						date_trunc('year',p_rss_mere.date_sortie) = date_trunc('year',rss_mere.d_s_etablt)
					JOIN [SCHEMA].p_rss p_rss_nne ON 
						p_rss_nne.no_rss = n_rss_nne AND
						date_trunc('year',p_rss_nne.date_sortie) = date_trunc('year',rss_nne.d_s_etablt)
				) subview
				WHERE p_rss.oid = subview.oid
				;

				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = p_rss_mere.no_sejour_administratif
				FROM [SCHEMA].p_rss p_rss_mere 
				WHERE 
					p_rss.rss_mere_id = p_rss_mere.oid AND
					p_rss.no_sejour_administratif = '0' AND
					p_rss_mere.no_sejour_administratif <> p_rss.no_sejour_administratif
				;

				-- Dans le cas d'un changement de prestataire, le no_rss peut changer
				-- On cherche le numéro patient par le numéro administratif et ensuite par le numéro rss
				-- On garde en priorité l'info venant du numéro RSS

				-- Par numéro séjour administratif
				UPDATE [SCHEMA].p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM  prod_cegi.rss
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.no_sejour_administratif = rss.n_doss AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint;

				-- Par numéro rss
				UPDATE [SCHEMA].p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM  prod_cegi.rss
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.no_rss = rss.n_rss AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint;



				-- Dans le cas d'un changement de prestataire, le no_rss peut changer
				-- On cherche les infos du patient grâce par le numéro administratif et ensuite par le numéro rss

				-- Par numéro séjour administratif
				UPDATE [SCHEMA].p_identites
				SET nom = w_CJ_PATIENT.per_nom,
					prenom = w_CJ_PATIENT.per_prenom,
					nom_naissance = w_CJ_PATIENT.per_nomjf
				FROM [SCHEMA].p_rss 
					JOIN prod_cegi.rss ON p_rss.no_sejour_administratif = rss.n_doss AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt)
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_identites.rss_id = p_rss.oid AND 
					(
					nom IS DISTINCT FROM w_CJ_PATIENT.per_nom OR
					prenom IS DISTINCT FROM w_CJ_PATIENT.per_prenom OR
					nom_naissance IS DISTINCT FROM w_CJ_PATIENT.per_nomjf
					);

				-- Par numéro rss
				UPDATE [SCHEMA].p_identites
				SET nom = w_CJ_PATIENT.per_nom,
					prenom = w_CJ_PATIENT.per_prenom,
					nom_naissance = w_CJ_PATIENT.per_nomjf
				FROM [SCHEMA].p_rss
					JOIN prod_cegi.rss ON p_rss.no_rss = rss.n_rss AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt)
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_identites.rss_id = p_rss.oid AND
					(
					nom IS DISTINCT FROM w_CJ_PATIENT.per_nom OR
					prenom IS DISTINCT FROM w_CJ_PATIENT.per_prenom OR
					nom_naissance IS DISTINCT FROM w_CJ_PATIENT.per_nomjf
					);

					
										
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Médecins RSS">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_RSS;

				CREATE TEMP TABLE w_RSS AS
				SELECT RSS.N_RSS, RSS.N_DOSS, RSS.N_PMSI, RSS.D_S_ETABLT, MAX(RUM.I_RUM) AS MAX_I_RUM
				FROM  prod_cegi.rum
					JOIN prod_cegi.RSS ON RSS.N_PMSI = RUM.N_PMSI
				GROUP BY 1,2,3,4;


				-- Dans le cas d'un changement de prestataire, le no_rss peut changer
				-- On cherche les infos du médecin grâce par le numéro administratif et ensuite par le numéro rss
				-- Par numéro séjour administratif
				UPDATE [SCHEMA].p_rss 
				SET medecin_rss_id = t_medecins.oid
				FROM prod_cegi.rum
					JOIN w_RSS ON w_RSS.N_PMSI = RUM.N_PMSI AND RUM.I_RUM = w_RSS.MAX_I_RUM
					JOIN prod_cegi.CJ_PRA ON (RUM.PRA_ID = CJ_PRA.PRA_ID AND (RUM.PRA_ID != 0 OR (RUM.PRA_ID = 0 AND RUM.C_MED = '?'))) OR (RUM.C_MED = CJ_PRA.PRA_LIBC AND RUM.PRA_ID = 0 )
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE p_rss.no_sejour_administratif = w_RSS.N_DOSS AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', w_RSS.D_S_ETABLT) AND
					medecin_rss_id IS DISTINCT FROM t_medecins.oid;

				-- Par numéro rss
				UPDATE [SCHEMA].p_rss
				SET medecin_rss_id = t_medecins.oid
				FROM prod_cegi.rum
					JOIN w_RSS ON w_RSS.N_PMSI = RUM.N_PMSI AND RUM.I_RUM = w_RSS.MAX_I_RUM
					JOIN prod_cegi.CJ_PRA ON (RUM.PRA_ID = CJ_PRA.PRA_ID AND (RUM.PRA_ID != 0 OR (RUM.PRA_ID = 0 AND RUM.C_MED = '?'))) OR (RUM.C_MED = CJ_PRA.PRA_LIBC AND RUM.PRA_ID = 0 )
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE p_rss.no_rss = w_RSS.N_RSS AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', w_RSS.D_S_ETABLT) AND
					medecin_rss_id IS DISTINCT FROM t_medecins.oid;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Médecins actes">
			<sqlcmd><![CDATA[

				-- Par numéro séjour administratif
				UPDATE [SCHEMA].p_rss_actes 
				SET medecin_id = t_medecins.oid
				FROM prod_cegi.RSS RSS
					JOIN [SCHEMA].p_rss ON p_rss.no_sejour_administratif = rss.n_doss AND	date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
						p_rss.import_id = [IMPORT_ID]
					JOIN prod_cegi.CJ_LSRGP CJ_LSRGP ON RSS.SEJ_ID = CJ_LSRGP.SEJ_ID AND LSR_ACTIF = 1 
					JOIN prod_cegi.CJ_LSCCAM CJ_LSCCAM ON CJ_LSRGP.LSR_ID = CJ_LSCCAM.LSR_ID AND CJ_LSCCAM.LSCA_ACTIF = 1 
					JOIN prod_cegi.CJ_CCAM CJ_CCAM ON  CJ_LSCCAM.CCAM_ID = CJ_CCAM.CCAM_ID
					JOIN prod_cegi.CJ_PRA CJ_PRA ON CJ_LSCCAM.TER_ID = CJ_PRA.TER_ID
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
					JOIN pmsi.t_actes ON false
                        OR CJ_CCAM.CCAM_CODE || COALESCE(CJ_LSCCAM.LSCA_EXT, ''::text) = t_actes.code -- Avec...
                        OR CJ_CCAM.CCAM_CODE = t_actes.code -- ... ou sans extension.
				WHERE p_rss_actes.rss_id = p_rss.oid AND
					p_rss_actes.acte_id = t_actes.oid AND
					p_rss_actes.activite_ccam = CJ_CCAM.CCAM_ACTV AND
					p_rss_actes.date_acte = date(CJ_LSRGP.LSR_DDEB) AND
					p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid
				;

				-- Par numéro rss
				UPDATE [SCHEMA].p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM prod_cegi.RSS RSS
					JOIN [SCHEMA].p_rss ON p_rss.no_rss = rss.n_rss AND	date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
						p_rss.import_id = [IMPORT_ID]
					JOIN prod_cegi.CJ_LSRGP CJ_LSRGP ON RSS.SEJ_ID = CJ_LSRGP.SEJ_ID AND LSR_ACTIF = 1
					JOIN prod_cegi.CJ_LSCCAM CJ_LSCCAM ON CJ_LSRGP.LSR_ID = CJ_LSCCAM.LSR_ID AND CJ_LSCCAM.LSCA_ACTIF = 1
					JOIN prod_cegi.CJ_CCAM CJ_CCAM ON  CJ_LSCCAM.CCAM_ID = CJ_CCAM.CCAM_ID
					JOIN prod_cegi.CJ_PRA CJ_PRA ON CJ_LSCCAM.TER_ID = CJ_PRA.TER_ID
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
					JOIN pmsi.t_actes ON false
                        OR CJ_CCAM.CCAM_CODE || COALESCE(CJ_LSCCAM.LSCA_EXT, ''::text) = t_actes.code -- Avec...
                        OR CJ_CCAM.CCAM_CODE = t_actes.code -- ... ou sans extension.
				WHERE p_rss_actes.rss_id = p_rss.oid AND
					p_rss_actes.acte_id = t_actes.oid AND
					p_rss_actes.activite_ccam = CJ_CCAM.CCAM_ACTV AND
					p_rss_actes.date_acte = date(CJ_LSRGP.LSR_DDEB) AND
					p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid
				;

			]]></sqlcmd>
		</NODE>
		
		<NODE label="Compléments identifications Externes">
			<sqlcmd><![CDATA[
			
				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = RSF_2.ENTREE
				FROM prod_cegi.RSF_2
				WHERE p_rss.ghm_id = 0 AND
					to_number('0' || FACTURE, '000000000000') =  to_number('0' || no_sejour_administratif, '000000000000') AND
					ENTREE <> to_number('0' || no_sejour_administratif, '000000000000') AND
					date(base.cti_to_date((D_ENTREE))) = date(date_entree) AND
					date(base.cti_to_date((D_SORTIE))) = date(date_sortie) AND
					no_sejour_administratif IS DISTINCT FROM RSF_2.ENTREE;
				
				-- Cas où le n° de facture ne correspond pas, on cherche à identifier les séjours avec les n°SECU les dates d'entree et de sortie
				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = RSF_2.ENTREE
				FROM 
					[SCHEMA].p_rsf_total,
					prod_cegi.RSF_2 
				WHERE 1=1
					AND p_rss.ghm_id = 0
					AND p_rsf_total.rss_id = p_rss.oid
					AND p_rss.no_sejour_administratif = p_rsf_total.no_facture
					AND RSF_2.MATRICULE = p_rsf_total.matricule_assure
					AND date(base.cti_to_date((RSF_2.D_ENTREE))) = date(p_rss.date_entree)
					AND date(base.cti_to_date((RSF_2.D_SORTIE))) = date(p_rss.date_sortie)
					AND p_rss.no_sejour_administratif != RSF_2.ENTREE;
                   
				UPDATE [SCHEMA].p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM prod_cegi.CJ_SEJOUR
					JOIN w_CJ_PATIENT ON (CJ_SEJOUR.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.ghm_id = 0 AND
					to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND 
					to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND 
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE)) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint;
				
				UPDATE [SCHEMA].p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM prod_cegi.CJ_SEJOUR
					JOIN w_CJ_PATIENT ON (CJ_SEJOUR.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE 1=1 AND
					to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND 
					to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND 
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE)) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
					AND (-1)*no_rss = sej_id;


				UPDATE [SCHEMA].p_identites
				SET nom = w_CJ_PATIENT.per_nom,
					prenom = w_CJ_PATIENT.per_prenom,
					nom_naissance = w_CJ_PATIENT.per_nomjf
				FROM [SCHEMA].p_rss 
					JOIN prod_cegi.cj_sejour ON to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE))
					JOIN w_CJ_PATIENT ON (cj_sejour.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_identites.rss_id = p_rss.oid AND p_rss.ghm_id = 0 AND
					(
					nom IS DISTINCT FROM w_CJ_PATIENT.per_nom OR
					prenom IS DISTINCT FROM w_CJ_PATIENT.per_prenom OR
					nom_naissance IS DISTINCT FROM w_CJ_PATIENT.per_nomjf
					);
				
				-- D'après CJ_SEJPRA comme dans l'activité
				UPDATE [SCHEMA].p_rss SET
					medecin_rss_id = t_medecins.oid
				FROM
					prod_cegi.CJ_SEJOUR
					JOIN prod_cegi.CJ_SEJPRA ON CJ_SEJOUR.SEJ_ID = CJ_SEJPRA.SEJ_ID AND SEJPRA_QUALITE = 'R'
					JOIN prod_cegi.CJ_PRA ON CJ_SEJPRA.PRA_ID = CJ_PRA.PRA_ID
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE 1=1
					AND to_number('0'::text || p_rss.no_sejour_administratif::text, '000000000000'::text) = to_number('0'::text || CJ_SEJOUR.SEJ_NUMDOS::text, '000000000000'::text) 
					AND to_number('0'::text || CJ_SEJOUR.SEJ_NUMDOS::text, '000000000000'::text) <> 0 
					AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(CJ_SEJOUR.SEJ_DT_SORTIE))
					AND p_rss.ghm_id = 0
					AND p_rss.medecin_rss_id IS DISTINCT FROM t_medecins.oid;
					
					
				DROP TABLE IF EXISTS w_RSS;

				CREATE TEMP TABLE w_RSS AS
				SELECT RSS.N_DOSS, RSS.N_PMSI, RSS.D_S_ETABLT, MAX(RUM.I_RUM) AS MAX_I_RUM
				FROM  prod_cegi.rum
					JOIN prod_cegi.RSS ON RSS.N_PMSI = RUM.N_PMSI
				GROUP BY 1,2,3;


				UPDATE [SCHEMA].p_rss 
				SET medecin_rss_id = t_medecins.oid
				FROM prod_cegi.rum
					JOIN w_RSS ON w_RSS.N_PMSI = RUM.N_PMSI AND RUM.I_RUM = w_RSS.MAX_I_RUM
					JOIN prod_cegi.CJ_PRA ON (RUM.PRA_ID = CJ_PRA.PRA_ID AND (RUM.PRA_ID != 0 OR (RUM.PRA_ID = 0 AND RUM.C_MED = '?'))) OR (RUM.C_MED = CJ_PRA.PRA_LIBC AND RUM.PRA_ID = 0 )
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE p_rss.ghm_id = 0 AND 
					to_number('0' || no_sejour_administratif, '000000000000') = w_RSS.N_DOSS AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', w_RSS.D_S_ETABLT) AND
					medecin_rss_id = 0;
					
					
				UPDATE [SCHEMA].p_rss
				SET code_postal = w_CJ_PATIENT.PER_CP
				FROM prod_cegi.cj_sejour  					
					JOIN w_CJ_PATIENT ON (cj_sejour.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_rss.ghm_id = 0 AND 
					code_postal = '' AND
					to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND 
					to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND 
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE)) AND
					length(w_CJ_PATIENT.PER_CP) = 5 AND
					code_postal IS DISTINCT FROM w_CJ_PATIENT.PER_CP ;


					
					
					
				UPDATE [SCHEMA].p_rss_actes 
				SET medecin_id = t_medecins.oid
				FROM prod_cegi.CJ_SEJOUR
					JOIN [SCHEMA].p_rss ON to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE))
					JOIN prod_cegi.CJ_LSRGP CJ_LSRGP ON CJ_SEJOUR.SEJ_ID = CJ_LSRGP.SEJ_ID AND LSR_ACTIF = 1 
					JOIN prod_cegi.CJ_LSCCAM CJ_LSCCAM ON CJ_LSRGP.LSR_ID = CJ_LSCCAM.LSR_ID AND CJ_LSCCAM.LSCA_ACTIF = 1 
					JOIN prod_cegi.CJ_CCAM CJ_CCAM ON  CJ_LSCCAM.CCAM_ID = CJ_CCAM.CCAM_ID 
					JOIN prod_cegi.CJ_PRA CJ_PRA ON CJ_LSCCAM.TER_ID = CJ_PRA.TER_ID
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
					JOIN pmsi.t_actes ON false
                        OR CJ_CCAM.CCAM_CODE || COALESCE(CJ_LSCCAM.LSCA_EXT, ''::text) = t_actes.code -- Avec...
                        OR CJ_CCAM.CCAM_CODE = t_actes.code -- ... ou sans extension.
				WHERE p_rss.ghm_id = 0 AND
					p_rss_actes.rss_id = p_rss.oid AND
					p_rss_actes.acte_id = t_actes.oid AND
					p_rss_actes.activite_ccam = CJ_CCAM.CCAM_ACTV AND
					p_rss_actes.date_acte = date(CJ_LSRGP.LSR_DDEB) AND
					p_rss_actes.medecin_id IS DISTINCT FROM t_medecins.oid;
					
					
				
				UPDATE [SCHEMA].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 p_rss.ghm_id = 0 AND medecin_rss_id = 0;	
				
				
				
										
			]]></sqlcmd>
		</NODE>
							 
	</NODE>

	
	<NODE name="PMSIENCOURS" label="RECUPERATION DES DOSSIERS PMSI EN-COURS CEGI">
		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[
			
				-- Préparation table des GHS pour chainage
				DROP TABLE IF EXISTS w_ghs;
				CREATE TEMP TABLE w_ghs AS
				SELECT *, CASE WHEN code_text BETWEEN '0' AND '9999' THEN lpad(code_text ,4,'0') ELSE code_text END AS code_text2
				FROM pmsi.t_ghs
				;
				
				CREATE INDEX w_ghs_i_code_text
				  ON w_ghs
				  USING btree
				  (code_text)
				;
				CREATE INDEX w_ghs_i_code_text2
				  ON w_ghs
				  USING btree
				  (code_text2)
				;
				
			
				DROP TABLE IF EXISTS w_etb;
				CREATE TEMP TABLE w_etb AS
				SELECT 
					ETB_ID as w_etb_id,
					ETB_FINESS as w_etb_finess
				FROM
					prod_cegi.CJ_ETB
				WHERE
					ETB_FINESS = '[FINESS]';

				INSERT INTO pmsi.t_medecins(code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				SELECT 
					cj_pra.pra_libc,
					MAX(per_nom),
					MAX(COALESCE(per_prenom, '')),
					MAX(COALESCE(t_specialites_medecin.oid,0)),
					MAX(COALESCE(cj_prc.prc_identification, '')),
					MAX(COALESCE(t_specialites_internes_medecin.oid,0))
				FROM prod_cegi.cj_pra 
					LEFT JOIN prod_cegi.cj_prc ON (cj_pra.pra_id = cj_prc.pra_id)
					LEFT JOIN prod_cegi.cj_spe ON (cj_pra.spe_id = cj_spe.spe_id)
					LEFT JOIN pmsi.t_specialites_medecin ON (t_specialites_medecin.code = spe_libc)
					LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = spe_libc || '..')
					LEFT JOIN pmsi.t_medecins ON (cj_pra.pra_libc = t_medecins.code)
				WHERE 1=1
					AND cj_pra.pra_id IN (
							SELECT RUM.pra_id
							FROM prod_cegi.rum
						UNION
							SELECT CJ_PRA_SUBQ.pra_id
							FROM prod_cegi.CJ_PRA AS CJ_PRA_SUBQ
								JOIN prod_cegi.CJ_LSCCAM ON CJ_LSCCAM.TER_ID = CJ_PRA_SUBQ.TER_ID
						GROUP BY 1)
					AND t_medecins.code IS NULL
				GROUP BY 1;
				
				
				-- Unités médicales
				SELECT base.cti_execute('
					SELECT
						UM.CODE,
						UM.LIB
					FROM
						prod_cegi.UM
						LEFT JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = UM.CODE
					WHERE
						t_unites_medicales.code IS NULL 
					ORDER BY 1.,
					
					UPDATE pmsi.t_unites_medicales SET
						texte = UM.LIB
					FROM
						prod_cegi.UM
					WHERE 1=1
						AND UM.CODE = t_unites_medicales.code
						AND t_unites_medicales.code = t_unites_medicales.texte
						AND t_unites_medicales.texte IS DISTINCT FROM UM.LIB',1)
				WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'um' AND table_schema='prod_cegi') > 0
				;

			]]></sqlcmd>
		</NODE>
		
		
		
		
		
		<NODE label="RSS">
			<sqlcmd><![CDATA[
            
                -- patients
                DROP TABLE IF EXISTS w_CJ_PATIENT;
                CREATE TEMP TABLE w_CJ_PATIENT AS 
                SELECT
                    pat_id
                    ,MAX(pat_ipp) as pat_ipp
                    ,MAX(per_nom) as per_nom
                    ,MAX(per_prenom) as per_prenom
                    ,MAX(per_nomjf) as per_nomjf
                    ,MAX(per_cp) as per_cp
                    ,MAX(per_naissance) as per_naissance
                    ,MAX(pat_sexe) as per_sexe
                FROM
                    prod_cegi.CJ_PATIENT
                GROUP BY 1;
                
                CREATE INDEX w_CJ_PATIENT_i1
				  ON w_CJ_PATIENT
				  USING btree
				  (pat_id)
				;

			
				-- Séjours PMSI avec RSS
				
				DROP TABLE IF EXISTS w_rss;
				CREATE TEMP TABLE w_rss AS
				SELECT w_etb.w_etb_finess AS finess, 
				n_pmsi, 
				n_rss, 
				rss.sej_id, 
				n_doss::text, 
				cj_sejour.pat_id,
				nextval('pmsi.s_rss'::regclass) AS rss_id, 
				'1'::text AS frompmsi
				FROM prod_cegi.rss 
					JOIN prod_cegi.cj_sejour ON (rss.sej_id = cj_sejour.sej_id)
					JOIN w_etb ON cj_sejour.etb_id = w_etb.w_etb_id
                    LEFT JOIN pmsi.p_rss ON rss.n_rss = p_rss.no_rss AND p_rss.etat = '' AND date_part('month',d_s_etablt) = date_part('month', p_rss.date_sortie) AND date_part('year',d_s_etablt) = date_part('year', p_rss.date_sortie)
				WHERE d_s_etablt BETWEEN '[ANNEE]0101'::date AND date(now())
					AND n_rss > 0
					AND c_etat <> 5
					AND SEJ_ANNUL_DH IS NULL
					AND p_rss.no_rss IS NULL
					AND 
						(
							n_pmsi NOT IN (
										SELECT n_pmsi
										FROM prod_cegi.rss 
										JOIN prod_cegi.rsf_2 ON (rsf_2.entree = rss.n_doss)
										LEFT JOIN prod_cegi.rsf_3 ON (rsf_3.facture = rsf_2.facture)
										WHERE (ACTE IN ('SE1', 'SE2', 'SE3', 'SE4', 'ATU', 'FFM', 'XTR') OR
											rsf_3.facture IS NULL
											) AND 
											d_s_etablt BETWEEN '[ANNEE]0101' AND date(now())
										)
									 OR
							(length(c_ghm_ccam) = 6 AND c_ghm_ccam NOT LIKE '90%')
							)
					AND CASE WHEN '[ETAB]' != '' THEN cj_sejour.etb_id = ANY(regexp_split_to_array('[ETAB]',',')) ELSE 1=1 END
				ORDER BY rss.n_pmsi;
				
				-- Séjours PMSI sans RSS
				
				-- Types de séjour à choisir
				DROP TABLE IF EXISTS w_TYD;
				CREATE TEMP TABLE w_TYD AS
				SELECT TYD_ID, '0'::text AS TYD_OK, count(*)::numeric(15,2) AS TYD_NB
				FROM prod_cegi.CJ_SEJOUR
				JOIN pmsi.p_rss ON 
					SEJ_NUMDOS = lpad(no_sejour_administratif,9,'0')
				WHERE SEJ_DT_SORTIE BETWEEN '[ANNEE]0101' AND date(now()) AND
					p_rss.en_cours <> '1' AND 
					p_rss.ghm_id <> 0 AND
					SEJ_NATURE <> 'EXT' AND 
					SEJ_ACTIF = 1 AND 
					SEJ_RESA <> 1 AND
					SEJ_ANNUL_DH IS NULL
				GROUP BY 1,2;

				UPDATE w_TYD
				SET TYD_OK = '1'
				FROM
					(SELECT SUM(TYD_NB) AS TOT FROM w_TYD) subview
				WHERE base.cti_division(TYD_NB,TOT) > 0.05;

				-- Séjours
				INSERT INTO w_rss
				SELECT w_etb.w_etb_finess AS finess, 
					0::numeric AS N_PMSI, 
					0 - CJ_SEJOUR.SEJ_ID AS N_RSS, 
					CJ_SEJOUR.SEJ_ID, 
					CJ_SEJOUR.SEJ_NUMDOS AS N_DOSS,
					cj_sejour.pat_id, 
					nextval('pmsi.s_rss'::regclass) AS rss_id, 
					'0'::text AS frompmsi
				FROM prod_cegi.cj_sejour
					JOIN w_TYD ON CJ_SEJOUR.TYD_ID = w_TYD.TYD_ID AND TYD_OK = '1'
					LEFT JOIN prod_cegi.rss ON rss.sej_id = cj_sejour.sej_id
					JOIN w_etb ON cj_sejour.etb_id = w_etb.w_etb_id
					LEFT JOIN pmsi.p_rss ON 
						CJ_SEJOUR.SEJ_NUMDOS  = lpad(p_rss.no_sejour_administratif,9,'0') AND 
						p_rss.etat = '' AND 
						date_part('month',SEJ_DT_SORTIE) = date_part('month', p_rss.date_sortie)
				WHERE SEJ_DT_SORTIE BETWEEN '[ANNEE]0101'::date AND date(now()) AND
					RSS.SEJ_ID IS NULL AND
					p_rss.no_rss IS NULL AND
					SEJ_NATURE <> 'EXT' AND 
					SEJ_ACTIF = 1 AND 
					SEJ_RESA <> 1 AND
					CASE WHEN '[ETAB]' != '' THEN cj_sejour.etb_id = ANY(regexp_split_to_array('[ETAB]',',')) ELSE 1=1 END
				ORDER BY CJ_SEJOUR.SEJ_NUMDOS;
	
				-- Ajout des séjours avec 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, 
						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,
						np_id
						)
				SELECT 
						w_rss.finess AS finess, 
						w_rss.rss_id AS oid, 
						w_rss.n_rss AS no_rss, 
						0 AS no_patient, 
						ver_classif AS version_groupage, 
						w_CJ_PATIENT.per_naissance AS date_naissance, 
						CASE WHEN w_CJ_PATIENT.per_sexe = 'F' THEN '2' ELSE '1' END AS sexe, 
						d_e_etablt AS date_entree, 
						d_s_etablt AS date_sortie, 
						'8' AS mode_entree, 
						'' AS provenance, 
						'8' AS mode_sortie, 
						'' AS destination, 
						substr(w_CJ_PATIENT.per_cp,1,5) AS code_postal, 
						rss.poids AS poids_bebe, 
						0 AS igs2, 
						'' AS cma, 
						substr(c_ghm_ccam , 3 , 1) AS groupe_ghm, 
						CASE WHEN d_s_etablt > d_e_etablt THEN date(d_s_etablt) - date(d_e_etablt) ELSE 0 END AS duree_sejour, 
						CASE WHEN substr(c_ghm_ccam,1,2) = '28' THEN GREATEST(nb_seances, 1) ELSE 1 END AS nb_rsa, 
						CASE WHEN trunc((date(d_e_etablt) - date(w_CJ_PATIENT.per_naissance)) / 365.25,0) BETWEEN 0 AND 130 THEN trunc((date(d_e_etablt) - date(w_CJ_PATIENT.per_naissance)) / 365.25,0) ELSE 0 END AS age, 
						'' AS supprime, 
						now() AS date_import, 
						1 AS nb_rum, 
						'' AS secteur, 
						w_rss.n_doss AS no_sejour_administratif, 
						CASE WHEN substr(c_ghm_ccam,1,2) = '28' THEN GREATEST(nb_seances, 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', d_s_etablt) * 100 + date_part('month', d_s_etablt) 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(c_ghm_ccam) = 6 AND substr(c_ghm_ccam,1,2) <> '90' AND dt_env_adm IS NOT NULL THEN 'V' WHEN length(c_ghm_ccam) = 6 AND substr(c_ghm_ccam,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(C_ERR_CCAM::text,'') AS code_retour_groupage, 
						0 AS comite_medical_id, 
						'0' AS rehosp_meme_ghm, 
						0 AS from_oid,
						0 AS np_id
				FROM prod_cegi.rss 
					JOIN w_rss ON rss.n_pmsi = w_rss.n_pmsi AND frompmsi = '1'
					JOIN w_CJ_PATIENT ON (w_rss.pat_id = w_CJ_PATIENT.pat_id)
					LEFT JOIN pmsi.t_ghm ON (rss.c_ghm_ccam = t_ghm.code)
					LEFT JOIN w_ghs t_ghs ON rss.ghs_numero = t_ghs.code_text OR rss.ghs_numero = t_ghs.code_text2
				;
					
				-- Ajout des séjours sans 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, 
						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,
						np_id
						)
				SELECT 
						w_rss.finess AS finess, 
						w_rss.rss_id AS oid, 
						w_rss.n_rss AS no_rss, 
						0 AS no_patient, 
						'' AS version_groupage, 
						w_CJ_PATIENT.per_naissance AS date_naissance, 
						CASE WHEN w_CJ_PATIENT.per_sexe = 'F' THEN '2' ELSE '1' END AS sexe, 
						SEJ_DT_ENTREE AS date_entree, 
						SEJ_DT_SORTIE AS date_sortie, 
						'8' AS mode_entree, 
						'' AS provenance, 
						'8' AS mode_sortie, 
						'' AS destination, 
						substr(w_CJ_PATIENT.per_cp,1,5) AS code_postal, 
						0 AS poids_bebe, 
						0 AS igs2, 
						'' AS cma, 
						'Z' AS groupe_ghm, 
						CASE WHEN SEJ_DT_SORTIE > SEJ_DT_ENTREE THEN date(SEJ_DT_SORTIE) - date(SEJ_DT_ENTREE) ELSE 0 END AS duree_sejour, 
						1 AS nb_rsa, 
						CASE WHEN SEJ_DT_SORTIE > w_CJ_PATIENT.per_naissance THEN trunc((date(SEJ_DT_ENTREE) - date(w_CJ_PATIENT.per_naissance)) / 365.25,0) ELSE 0 END AS age, 
						'' AS supprime, 
						now() AS date_import, 
						1 AS nb_rum, 
						'' AS secteur, 
						w_rss.n_doss AS no_sejour_administratif, 
						0 AS nb_seances, 
						'' AS ghm_fg9, 
						COALESCE(t_ghm.oid, 0) AS ghm_id, 
						0 AS medecin_rss_id, 
						0 AS ghs_id, 
						date_part('year', SEJ_DT_SORTIE) * 100 + date_part('month', SEJ_DT_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, 
						'S' 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, 
						'' AS code_retour_groupage, 
						0 AS comite_medical_id, 
						'0' AS rehosp_meme_ghm, 
						0 AS from_oid,
						0 as np_id
				FROM prod_cegi.CJ_SEJOUR
					JOIN w_rss ON CJ_SEJOUR.SEJ_ID = w_rss.SEJ_ID AND frompmsi = '0' AND
						SEJ_NATURE <> 'EXT' AND 
						SEJ_ACTIF = 1 AND 
						SEJ_RESA <> 1 AND
						CASE WHEN '[ETAB]' != '' THEN cj_sejour.etb_id = ANY(regexp_split_to_array('[ETAB]',',')) ELSE 1=1 END
					JOIN w_CJ_PATIENT ON w_rss.pat_id = w_CJ_PATIENT.pat_id
					LEFT JOIN pmsi.t_ghm ON t_ghm.code = '99Z99Z'
				;
				
				-- Code GHM fictif pour sorties non groupées
				UPDATE pmsi.p_rss
				SET ghm_id = t_ghm.oid
				FROM pmsi.t_ghm
				WHERE t_ghm.code LIKE '99Z99Z' AND
					p_rss.ghm_id = 0 AND
					p_rss.en_cours = '1' AND
					p_rss.en_cours_etat = 'S'
				;
										
				DROP TABLE IF EXISTS w_RSS_med;

				CREATE TEMP TABLE w_RSS_med AS
				SELECT RSS.N_RSS, RSS.N_PMSI, RSS.D_S_ETABLT, MAX(RUM.I_RUM) AS MAX_I_RUM
				FROM  prod_cegi.rum
					JOIN prod_cegi.RSS ON RSS.N_PMSI = RUM.N_PMSI
				GROUP BY 1,2,3;


				UPDATE pmsi.p_rss 
				SET medecin_rss_id = t_medecins.oid
				FROM prod_cegi.rum
					JOIN w_RSS_med ON w_RSS_med.N_PMSI = RUM.N_PMSI AND RUM.I_RUM = w_RSS_med.MAX_I_RUM
					JOIN prod_cegi.CJ_PRA ON (RUM.PRA_ID = CJ_PRA.PRA_ID AND (RUM.PRA_ID != 0 OR (RUM.PRA_ID = 0 AND RUM.C_MED = '?'))) OR (RUM.C_MED = CJ_PRA.PRA_LIBC AND RUM.PRA_ID = 0 )
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE p_rss.no_rss = w_RSS_med.N_RSS AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', w_RSS_med.D_S_ETABLT) AND
					medecin_rss_id IS DISTINCT FROM t_medecins.oid;		
		
				-- transferts d'établissements
				INSERT INTO base.t_etablissements(code, texte, texte_court)
				SELECT 
					FNS_FINESS,
					FNS_NOM,
					FNS_NOM
				FROM prod_cegi.CJ_FINESS 
				WHERE FNS_FINESS 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,
					MAX(import_id) as import_id,
					COALESCE(MAX(provenance.oid),0) AS prov_id,
					COALESCE(MAX(destination.oid),0) AS dest_id
				FROM
					pmsi.p_rss
					JOIN prod_cegi.CJ_SEJOUR ON SEJ_NUMDOS = no_sejour_administratif
					JOIN w_etb ON cj_sejour.etb_id = w_etb.w_etb_id
					LEFT JOIN prod_cegi.CJ_FINESS CJ_FINESS_ENT ON FNS_ID_ENT = CJ_FINESS_ENT.FNS_ID
					LEFT JOIN prod_cegi.CJ_FINESS CJ_FINESS_SOR ON FNS_ID_SOR = CJ_FINESS_SOR.FNS_ID
					LEFT JOIN base.t_etablissements provenance ON CJ_FINESS_ENT.FNS_FINESS = provenance.code
					LEFT JOIN base.t_etablissements destination ON CJ_FINESS_ENT.FNS_FINESS = destination.code
				WHERE 1=1 AND (
					FNS_ID_ENT NOT IN (0,10000) OR
					FNS_ID_SOR NOT IN (0,10000)) AND
					etat != 'S'
				GROUP BY 1
				;

			]]></sqlcmd>
		</NODE>
				
		<NODE label="Identités">
			<sqlcmd><![CDATA[

				INSERT INTO pmsi.p_identites(
						finess, 
						rss_id,
						no_rss, 
						nom, 
						prenom, 
						nom_naissance)
				SELECT 
						w_rss.finess AS finess, 
						w_rss.rss_id AS oid, 
						w_rss.n_rss AS no_rss, 
						w_CJ_PATIENT.per_nom AS nom, 
						w_CJ_PATIENT.per_prenom AS prenom, 
						w_CJ_PATIENT.per_nomjf AS nom_naissance
				FROM w_rss 
					JOIN w_CJ_PATIENT ON w_rss.pat_id = w_CJ_PATIENT.pat_id;

				UPDATE pmsi.p_rss
				SET no_patient = 0::bigint
				FROM  prod_cegi.rss
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.no_rss = rss.n_rss AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
					w_CJ_PATIENT.pat_ipp ilike 'TEMP%';

				UPDATE pmsi.p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM  prod_cegi.rss
					JOIN w_CJ_PATIENT ON (rss.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.no_rss = rss.n_rss AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', rss.d_s_etablt) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint;
										
			]]></sqlcmd>
		</NODE>
			
		<NODE label="Passage urgences">
		     <condition><![CDATA[
			 	SELECT base.cti_is_column_not_exists('prod_cegi', 'rum', 'rum_passurg');
            ]]></condition>
            <sqlcmd><![CDATA[
	
				-- Varibale Passage urgences non présente dans ancienne version CEGI
				ALTER TABLE prod_cegi.rum ADD COLUMN rum_passurg VARCHAR
				;

			]]></sqlcmd>
		</NODE>
	
		<NODE label="Rum">
			<sqlcmd><![CDATA[

				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,
					passage_urgences_code
					)
				SELECT
					w_rss.finess  AS finess, 
					w_rss.rss_id AS rss_id, 
					w_rss.n_rss AS no_rss, 
					i_rum AS no_rum, 
					rum.d_e AS date_entree, 
					rum.d_s AS date_sortie, 
					rum.c_mode_e AS mode_entree, 
					CASE WHEN rum.c_prov <> '-' THEN rum.c_prov ELSE '' END AS provenance, 
					rum.c_mode_s AS mode_sortie, 
					CASE WHEN rum.c_dest <> '-' THEN rum.c_dest ELSE '' END AS destination, 
					CASE WHEN rum.d_s > rum.d_e THEN date(rum.d_s) - date(rum.d_e) ELSE 0 END AS duree_sejour, 
					0 AS nb_seances, 
					c_um 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.igs AS igs2, 
					'' AS type_autorisation_lit_dedie,
					'' AS supplement_code,
					COALESCE(rum.RUM_PASSURG, '') AS passage_urgences_code
				FROM prod_cegi.rum 
					JOIN w_rss ON (rum.n_pmsi = w_rss.n_pmsi)
					LEFT JOIN pmsi.t_unites_medicales ON (rum.c_um = t_unites_medicales.code)
					LEFT JOIN pmsi.t_diagnostics ON (rum.c_dp = t_diagnostics.code)
					LEFT JOIN pmsi.t_diagnostics t_diagnostics_relies ON (rum.c_dr = t_diagnostics_relies.code);

				-- RSS sans rum
				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,
					passage_urgences_code
					)
				SELECT
					p_rss.finess  AS finess, 
					p_rss.oid AS rss_id, 
					p_rss.no_rss AS no_rss, 
					1 AS no_rum, 
					p_rss.date_entree, 
					p_rss.date_sortie, 
					p_rss.mode_entree, 
					p_rss.provenance, 
					p_rss.mode_sortie, 
					p_rss.destination, 
					p_rss.duree_sejour, 
					p_rss.nb_seances, 
					''::text AS unite_medicale, 
					p_rss.diagnostic_principal_id, 
					p_rss.diagnostic_relie_id, 
					0::bigint AS unite_medicale_id, 
					'' AS type_autorisation, 
					0 AS igs2, 
					'' AS type_autorisation_lit_dedie, 
					'' AS supplement_code,
					p_rss.passage_urgences_code
				FROM pmsi.p_rss
					LEFT JOIN pmsi.p_rss_rum ON p_rss_rum.rss_id = p_rss.oid
				WHERE p_rss.en_cours = '1' AND
					p_rss_rum.rss_id IS NULL;


				-- Variables RSS

				DROP TABLE IF EXISTS w_rss_variables;
				CREATE TEMP TABLE w_rss_variables AS 
					SELECT 
					w_rss.rss_id, 
					MAX(PEC_RAAC) AS PEC_RAAC, 
					MAX(RUM_PASSURG) AS RUM_PASSURG, 
					COALESCE(NULLIF(MAX(RUM_CONTPAT),''),'0')::smallint AS RUM_CONTPAT,
					COALESCE(NULLIF(MAX(RUM_ADMPDTRH),''),'0')::smallint AS RUM_ADMPDTRH,
					COALESCE(NULLIF(MAX(RUM_RESCTARIF),''),'0')::smallint AS RUM_RESCTARIF,
					MAX(t_nb_interventions.oid) AS RUM_CATNBINTTOT
				FROM prod_cegi.rum
				JOIN w_rss ON rum.n_pmsi = w_rss.n_pmsi
				LEFT JOIN pmsi.t_nb_interventions ON rum.RUM_CATNBINTTOT = t_nb_interventions.code   
				GROUP BY 1;

				UPDATE pmsi.p_rss 
				SET 
					raac_id = w_rss_variables.PEC_RAAC,
				 	passage_urgences_code = w_rss_variables.RUM_PASSURG,
					contexte_pat_id = w_rss_variables.RUM_CONTPAT,
					adm_prod_reshospi_id = w_rss_variables.RUM_ADMPDTRH,
					rescrit_tarif_id = w_rss_variables.RUM_RESCTARIF,
					nb_intervention_id = w_rss_variables.RUM_CATNBINTTOT
				FROM w_rss_variables
				WHERE p_rss.oid = w_rss_variables.rss_id 
				;
				
				
				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;
				
				-- 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;
					
				
				
				-- Dernier 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;
										
										
			]]></sqlcmd>
		</NODE>
		<NODE label="ADNP">
		     <condition><![CDATA[
			 	SELECT base.cti_is_column_exists('prod_cegi', 'rum', 'rum_nonprog');
            ]]></condition>
            <sqlcmd><![CDATA[
	
				-- Varibale ADNP 
				UPDATE pmsi.p_rss
				SET np_id = RUM_NONPROG::smallint
				FROM
				(
				SELECT w_rss.rss_id, MAX(RUM_NONPROG) AS RUM_NONPROG
				FROM prod_cegi.rum
				JOIN w_rss ON (rum.n_pmsi = w_rss.n_pmsi)
				WHERE TRIM(RUM_NONPROG) <> ''
				GROUP BY 1
				) subview
				WHERE p_rss.oid = subview.rss_id
				;

			]]></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)
				SELECT 
						w_rss.finess, 
						p_rss_rum.rss_id, 
						no_rss, 
						no_rum, 
						diagnostic_principal_id AS diagnostic_id, 
						'DP' AS type_diagnostic, 
						'DP' AS type_diagnostic_rss, 
						'' AS imprecis, 
						unite_medicale, 
						unite_medicale_id
				FROM pmsi.p_rss_rum 
					JOIN w_rss ON (p_rss_rum.rss_id = w_rss.rss_id)
				WHERE diagnostic_principal_id <> 0;
	
	
				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, 
						p_rss_rum.rss_id, 
						no_rss, 
						no_rum, 
						diagnostic_relie_id AS diagnostic_id, 
						'DR' AS type_diagnostic, 
						'DR' AS type_diagnostic_rss, 
						'' AS imprecis, 
						unite_medicale, 
						unite_medicale_id
				FROM pmsi.p_rss_rum 
					JOIN w_rss ON (p_rss_rum.rss_id = w_rss.rss_id)
				WHERE diagnostic_relie_id <> 0;
		
		
				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
						p_rss_rum.finess AS finess, 
						p_rss_rum.rss_id, 
						no_rss, 
						no_rum, 
						COALESCE(t_diagnostics.oid,0) AS diagnostic_id, 
						'DA' AS type_diagnostic, 
						'DA' AS type_diagnostic_rss, 
						'' AS imprecis, 
						unite_medicale, 
						unite_medicale_id
				FROM prod_cegi.rum_da
					JOIN w_rss ON (rum_da.n_pmsi = w_rss.n_pmsi)
					JOIN pmsi.t_diagnostics ON (rum_da.c_da = t_diagnostics.code)
					JOIN pmsi.p_rss_rum ON (w_rss.rss_id = p_rss_rum.rss_id AND rum_da.i_rum = p_rss_rum.no_rum);
                
                
				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
						p_rss_rum.finess AS finess, 
						p_rss_rum.rss_id, 
						no_rss, 
						no_rum, 
						COALESCE(t_diagnostics.oid,0) AS diagnostic_id, 
						'DD' AS type_diagnostic, 
						'DD' AS type_diagnostic_rss, 
						'' AS imprecis, 
						unite_medicale, 
						unite_medicale_id
				FROM prod_cegi.rum_dad
					JOIN w_rss ON (rum_dad.n_pmsi = w_rss.n_pmsi)
					JOIN pmsi.t_diagnostics ON (rum_dad.c_dad = t_diagnostics.code)
					JOIN pmsi.p_rss_rum ON (w_rss.rss_id = p_rss_rum.rss_id AND rum_dad.i_rum = p_rss_rum.no_rum);
											
										
			]]></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
						p_rss_rum.finess AS finess, 
						w_rss.rss_id AS rss_id, 
						w_rss.n_pmsi AS no_rss, 
						p_rss_rum.no_rum AS no_rum, 
						p_rss_rum.unite_medicale AS unite_medicale, 
						p_rss_rum.unite_medicale_id AS unite_medicale_id, 
						lsr_ddeb AS date_acte, 
						COALESCE(t_medecins.oid,0) AS medecin_id,
						COALESCE(t_actes_ext.oid, t_actes_nxt.oid, 0) AS acte_id, -- On privilégie l'association avec l'extension CCAM.
						1 AS nombre, 
						'' AS phase_ccam, 
						ccam_actv AS activite_ccam, 
						lsca_extdoc AS extension_ccam, 
						lsca_mod1 AS modificateur_ccam_1, 
						lsca_mod2 AS modificateur_ccam_2, 
						lsca_mod3 AS modificateur_ccam_3, 
						lsca_mod4 AS modificateur_ccam_4, 
						lsca_rmbex AS remboursement_excp_ccam, 
						lsca_assnp AS association_nonprevue_ccam
				FROM prod_cegi.cj_lsrgp
					JOIN w_rss ON (cj_lsrgp.sej_id = w_rss.sej_id )
					JOIN prod_cegi.cj_lsccam ON (cj_lsrgp.lsr_id = cj_lsccam.lsr_id )
					JOIN prod_cegi.cj_sejour ON (cj_lsrgp.sej_id = cj_sejour.sej_id )
					JOIN prod_cegi.cj_ccam ON (cj_lsccam.ccam_id = cj_ccam.ccam_id)
					JOIN pmsi.p_rss_rum ON (w_rss.rss_id = p_rss_rum.rss_id AND p_rss_rum.no_rum = 1)
					LEFT JOIN prod_cegi.cj_pra ON (cj_lsccam.ter_id = cj_pra.ter_id)
					LEFT JOIN pmsi.t_medecins ON (cj_pra.pra_libc = t_medecins.code)
					LEFT JOIN pmsi.t_actes as t_actes_ext ON (CJ_CCAM.CCAM_CODE || COALESCE(CJ_LSCCAM.LSCA_EXT, ''::text) = t_actes_ext.code)
                    LEFT JOIN pmsi.t_actes as t_actes_nxt ON CJ_CCAM.CCAM_CODE = t_actes_nxt.code
				WHERE lsr_actif = 1 AND lsca_actif = 1;
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Factures">
			<sqlcmd><![CDATA[
	
				DROP TABLE IF EXISTS w_rsf_2;
				CREATE TEMP TABLE w_rsf_2 AS
				SELECT 
						w_rss.rss_id AS rss_id, 
						MIN(rsf_2.facture) AS facture, 
						MAX(rsf_2.rang) AS rang, 
						MAX(rsf_2.grand) AS grand, 
						MAX(rsf_2.assurance) AS assurance, 
						MAX(rsf_2.exoneration) AS exoneration, 
						MIN(rsf_2.operation) AS operation, 
						MAX(rsf_2.matricule) AS matricule, 
						MAX(rsf_2.cle) AS cle
				FROM prod_cegi.rsf_2
					JOIN w_rss ON rsf_2.entree = w_rss.n_doss
				GROUP BY w_rss.rss_id;
	
	
				DROP TABLE IF EXISTS w_rsf_5;
				CREATE TEMP TABLE w_rsf_5 AS
				SELECT 
						w_rss.rss_id AS rss_id, 
						SUM(rsf_5.tbr_ph) AS tbr_ph, 
						SUM(rsf_5.thf) AS thf
				FROM prod_cegi.rsf_5
					JOIN w_rss ON rsf_5.entree = w_rss.n_doss
				GROUP BY w_rss.rss_id;
	
				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.n_rss AS no_rss, 
						'1' AS code_pec, 
						w_rsf_2.rang AS rang_beneficiaire, 
						w_rsf_2.grand AS regime, 
						w_rsf_2.assurance AS nature_pec, 
						w_rsf_2.exoneration AS justificatif_exo, 
						w_rsf_2.facture AS no_facture, 
						w_rsf_2.operation AS code_regularisation, 
						w_rsf_2.matricule AS matricule_assure, 
						w_rsf_2.cle AS cle_matricule_assure, 
						w_rsf_5.tbr_ph AS base_remboursement, 
						w_rsf_5.tbr_ph AS sejour_facture, 
						w_rsf_5.tbr_ph AS sejour_remboursable, 
						w_rsf_5.thf AS honoraires_factures, 
						w_rsf_5.thf 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_rss
					JOIN w_rsf_2 ON (w_rsf_2.rss_id = w_rss.rss_id)
					JOIN w_rsf_5 ON (w_rsf_5.rss_id = w_rss.rss_id);
	
	
				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[

				DROP TABLE IF EXISTS w_rsf_5d;
				CREATE TEMP TABLE w_rsf_5d AS
				SELECT 
						w_rss.finess AS finess, 
						w_rss.rss_id AS rss_id, 
						w_rss.n_rss AS n_rss,
						rsf_5.facture AS facture 
				FROM prod_cegi.rsf_5
					JOIN w_rss ON rsf_5.entree = w_rss.n_doss
				GROUP BY 1,2,3,4;	

				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_5d.finess AS finess, 
						w_rsf_5d.rss_id AS rss_id, 
						w_rsf_5d.n_rss, 
						'' AS nature, 
						rsf_3.mt AS mt, 
						rsf_3.dmt AS dmt, 
						to_date(d_debut,'DD/MM/YYYY') AS date_debut, 
						to_date(d_fin,'DD/MM/YYYY') AS date_fin, 
						to_number(rsf_3.qte,'000') AS nombre, 
						rsf_3.coeff AS coefficient, 
						rsf_3.pu AS prix_unitaire, 
						rsf_3.base AS base_remboursement, 
						to_number(rsf_3.tx,'000') AS taux_remboursement, 
						rsf_3.base AS sejour_facture, 
						rsf_3.base AS sejour_remboursable, 
						0 AS compteur, 
						'' AS ligne_t2a, 
						'' AS pec_fj, 
						CASE WHEN rsf_3.modul > 0 THEN rsf_3.modul 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 prod_cegi.rsf_3
					JOIN w_rsf_5d ON rsf_3.facture = w_rsf_5d.facture
					JOIN pmsi.t_prestations ON (rsf_3.acte = t_prestations.code)
					LEFT JOIN w_ghs t_ghs ON rsf_3.ghs::text = t_ghs.code_text OR rsf_3.ghs::text = t_ghs.code_text2
				WHERE rsf_3.base <> 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_5d.finess AS finess, 
						w_rsf_5d.rss_id AS rss_id, 
						w_rsf_5d.n_rss, 
						rsf_3f.i AS rang, 
						to_date(rsf_3.d_debut,'DD/MM/YYYY') AS date_lpp, 
						COALESCE(t_lpp.oid, 0) AS lpp_id, 
						rsf_3f.qte AS nombre, 
						rsf_3f.pu AS prix_unitaire, 
						rsf_3f.mtf  AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM prod_cegi.rsf_3f
					JOIN w_rsf_5d ON rsf_3f.facture = w_rsf_5d.facture
					JOIN prod_cegi.rsf_3 ON (rsf_3f.facture = rsf_3.facture AND rsf_3f.i = rsf_3.i)
					LEFT JOIN pmsi.t_lpp ON (code_lpp1 = t_lpp.code);
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="UCD">
			<sqlcmd><![CDATA[

				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_5d.finess AS finess, 
						w_rsf_5d.rss_id AS rss_id, 
						w_rsf_5d.n_rss, 
						rsf_3h.i AS rang, 
						to_date(rsf_3.d_debut,'DD/MM/YYYY') AS date_ucd, 
						COALESCE(t_ucd.oid,0) AS ucd_id, 
						rsf_3h.qte AS nombre, 
						1 AS coefficient_fractionnement, 
						rsf_3h.pua AS prix_unitaire_achat, 
						rsf_3h.puf AS prix_unitaire_ecart_indemnisable, 
						rsf_3h.mtecart AS montant_ecart_indemnisable, 
						rsf_3h.mtf AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM prod_cegi.rsf_3h
					JOIN w_rsf_5d ON rsf_3h.facture = w_rsf_5d.facture
					JOIN prod_cegi.rsf_3 ON (rsf_3h.facture = rsf_3.facture AND rsf_3h.i = rsf_3.i)
					LEFT JOIN pmsi.t_ucd ON (code_ucd_cip = t_ucd.code);	
										
			]]></sqlcmd>
		</NODE>
		
		
		
		<NODE label="Compléments identifications Externes">
			<sqlcmd><![CDATA[
			
				UPDATE pmsi.p_rss
				SET no_sejour_administratif = RSF_2.ENTREE
				FROM prod_cegi.RSF_2
				WHERE p_rss.ghm_id = 0 AND
					to_number('0' || FACTURE, '000000000000') =  to_number('0' || no_sejour_administratif, '000000000000') AND
					ENTREE <> to_number('0' || no_sejour_administratif, '000000000000') AND
					date(base.cti_to_date((D_ENTREE))) = date(date_entree) AND
					date(base.cti_to_date((D_SORTIE))) = date(date_sortie) AND
					no_sejour_administratif IS DISTINCT FROM RSF_2.ENTREE;


				UPDATE pmsi.p_rss
				SET no_patient = to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint
				FROM prod_cegi.CJ_SEJOUR
					JOIN w_CJ_PATIENT ON (CJ_SEJOUR.pat_id = w_CJ_PATIENT.pat_id AND w_CJ_PATIENT.pat_ipp BETWEEN '0' AND '9999999999999999')
				WHERE p_rss.ghm_id = 0 AND
					to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND 
					to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND 
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE)) AND
					no_patient IS DISTINCT FROM to_number(w_CJ_PATIENT.pat_ipp, '000000000000000')::bigint;


				UPDATE pmsi.p_identites
				SET nom = w_CJ_PATIENT.per_nom,
					prenom = w_CJ_PATIENT.per_prenom,
					nom_naissance = w_CJ_PATIENT.per_nomjf
				FROM pmsi.p_rss 
					JOIN prod_cegi.cj_sejour ON to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE))
					JOIN w_CJ_PATIENT ON (cj_sejour.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_identites.rss_id = p_rss.oid AND p_rss.ghm_id = 0 AND
					(
					nom IS DISTINCT FROM w_CJ_PATIENT.per_nom OR
					prenom IS DISTINCT FROM w_CJ_PATIENT.per_prenom OR
					nom_naissance IS DISTINCT FROM w_CJ_PATIENT.per_nomjf
					);
					
					
				DROP TABLE IF EXISTS w_RSS;

				CREATE TEMP TABLE w_RSS AS
				SELECT RSS.N_DOSS, RSS.N_PMSI, RSS.D_S_ETABLT, MAX(RUM.I_RUM) AS MAX_I_RUM
				FROM  prod_cegi.rum
					JOIN prod_cegi.RSS ON RSS.N_PMSI = RUM.N_PMSI
				GROUP BY 1,2,3;


				UPDATE pmsi.p_rss 
				SET medecin_rss_id = t_medecins.oid
				FROM prod_cegi.rum
					JOIN w_RSS ON w_RSS.N_PMSI = RUM.N_PMSI AND RUM.I_RUM = w_RSS.MAX_I_RUM
					JOIN prod_cegi.CJ_PRA ON (RUM.PRA_ID = CJ_PRA.PRA_ID AND (RUM.PRA_ID != 0 OR (RUM.PRA_ID = 0 AND RUM.C_MED = '?'))) OR (RUM.C_MED = CJ_PRA.PRA_LIBC AND RUM.PRA_ID = 0 )
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
				WHERE p_rss.ghm_id = 0 AND 
					to_number('0' || no_sejour_administratif, '000000000000') = w_RSS.N_DOSS AND
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', w_RSS.D_S_ETABLT) AND
					medecin_rss_id IS DISTINCT FROM t_medecins.oid;
					
					
				UPDATE pmsi.p_rss
				SET code_postal = w_CJ_PATIENT.PER_CP
				FROM prod_cegi.cj_sejour  					
					JOIN w_CJ_PATIENT ON (cj_sejour.pat_id = w_CJ_PATIENT.pat_id)
				WHERE p_rss.ghm_id = 0 AND 
					code_postal = '' AND
					to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND 
					to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND 
					date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE)) AND
					length(w_CJ_PATIENT.PER_CP) = 5 AND
					code_postal IS DISTINCT FROM PER_CP ;


					
					
					
				UPDATE pmsi.p_rss_actes 
				SET medecin_id = t_medecins.oid
				FROM prod_cegi.CJ_SEJOUR
					JOIN pmsi.p_rss ON to_number('0' || no_sejour_administratif, '000000000000') = to_number('0' || SEJ_NUMDOS, '000000000000') AND to_number('0' || SEJ_NUMDOS, '000000000000') <> 0 AND date_trunc('month', p_rss.date_sortie) = date_trunc('month', date(SEJ_DT_SORTIE))
					JOIN prod_cegi.CJ_LSRGP CJ_LSRGP ON CJ_SEJOUR.SEJ_ID = CJ_LSRGP.SEJ_ID AND LSR_ACTIF = 1 
					JOIN prod_cegi.CJ_LSCCAM CJ_LSCCAM ON CJ_LSRGP.LSR_ID = CJ_LSCCAM.LSR_ID AND CJ_LSCCAM.LSCA_ACTIF = 1 
					JOIN prod_cegi.CJ_CCAM CJ_CCAM ON  CJ_LSCCAM.CCAM_ID = CJ_CCAM.CCAM_ID
					JOIN prod_cegi.CJ_PRA CJ_PRA ON CJ_LSCCAM.TER_ID = CJ_PRA.TER_ID
					JOIN pmsi.t_medecins ON CJ_PRA.PRA_LIBC = t_medecins.code
					JOIN pmsi.t_actes ON false
                        OR CJ_CCAM.CCAM_CODE || COALESCE(CJ_LSCCAM.LSCA_EXT, ''::text) = t_actes.code -- Avec...
                        OR CJ_CCAM.CCAM_CODE = t_actes.code -- ... ou sans extension.
				WHERE p_rss.ghm_id = 0 AND
					p_rss_actes.rss_id = p_rss.oid AND
					p_rss_actes.acte_id = t_actes.oid AND
					p_rss_actes.activite_ccam = CJ_CCAM.CCAM_ACTV AND
					p_rss_actes.date_acte = date(CJ_LSRGP.LSR_DDEB) AND
					p_rss_actes.medecin_id IS DISTINCT FROM 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 p_rss.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[
			
				-- Date de groupage	
				UPDATE pmsi.p_rss_etat
				SET date_groupage = subview.date_groupage
				FROM
					(
					SELECT p_rss.oid AS rss_id, 
						CASE WHEN p_rss.en_cours = '0' OR p_rss.en_cours_etat IN ('F', 'G', 'V') THEN date(dt_env_adm) ELSE '20991231' END AS date_groupage
					FROM prod_cegi.rss 
						JOIN prod_cegi.cj_sejour ON (rss.sej_id = cj_sejour.sej_id)
						JOIN w_etb ON cj_sejour.etb_id = w_etb.w_etb_id
						JOIN pmsi.p_rss ON rss.n_rss = p_rss.no_rss AND 
							p_rss.etat = '' AND 
							date_part('month',d_s_etablt) = date_part('month', p_rss.date_sortie)
						JOIN pmsi.p_rss_etat ON p_rss_etat.rss_id = p_rss.oid
					WHERE CASE WHEN p_rss.en_cours = '0' OR p_rss.en_cours_etat IN ('F', 'G', 'V') THEN date(dt_env_adm) ELSE '20991231' END 
						IS DISTINCT FROM p_rss_etat.date_groupage
					) subview
				WHERE p_rss_etat.rss_id = subview.rss_id;
				
				-- Code facture
				UPDATE pmsi.p_rss_etat
				SET est_facture = subview.est_facture
				FROM
					(
					SELECT p_rss.oid AS rss_id,
						MAX(CASE WHEN RSF_2.ENTREE IS NOT NULL THEN '1' ELSE '0' END) AS est_facture
					FROM prod_cegi.rss 
						JOIN prod_cegi.cj_sejour ON (rss.sej_id = cj_sejour.sej_id)
						JOIN w_etb ON cj_sejour.etb_id = w_etb.w_etb_id
						LEFT JOIN prod_cegi.RSF_2 ON N_DOSS = ENTREE
						JOIN pmsi.p_rss ON rss.n_rss = p_rss.no_rss AND 
							p_rss.etat = '' AND 
							date_part('month',d_s_etablt) = date_part('month', p_rss.date_sortie) AND
							p_rss.en_cours = '1'
						JOIN pmsi.p_rss_etat ON p_rss_etat.rss_id = p_rss.oid
					GROUP BY 1
					HAVING MAX(CASE WHEN RSF_2.ENTREE IS NOT NULL THEN '1' ELSE '0' END) IS DISTINCT FROM
						MAX(p_rss_etat.est_facture)
					) subview
				WHERE p_rss_etat.rss_id = subview.rss_id;
				
				
				
				UPDATE pmsi.p_rss
				SET en_cours_etat = 'F'
				FROM pmsi.p_rss_etat
				WHERE rss_id = p_rss.oid AND
					en_cours = '1' AND
					est_facture = '1' AND 
					en_cours_etat <> 'F';
			]]></sqlcmd>
		</NODE>
		
	</NODE>
</ROOT>













