<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	
	<NODE name="PMSICOMPLEMENTS" label="RECUPERATION DES DONNEES COMPLEMENTAIRES PMSI">
		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[

				/**********************************************************************************
				 *                             SPECIALITES MEDECINS                              *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_specialites_medecin(code,texte)
				SELECT 
					NOSPEC,
					LIBELLE
				FROM prod_mederi.KSPECIAL
					LEFT JOIN pmsi.t_specialites_medecin on t_specialites_medecin.code = NOSPEC
				WHERE t_specialites_medecin.code IS NULL 
				ORDER BY 1;
				
				INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
				SELECT
					t_specialites_medecin.code::text || '..'::text,
					t_specialites_medecin.texte
				FROM
					pmsi.t_specialites_medecin
					LEFT JOIN pmsi.t_specialites_internes_medecin on t_specialites_internes_medecin.code = t_specialites_medecin.code::text || '..'::text
				WHERE 1=1
					AND t_specialites_medecin.oid <> 0
					AND t_specialites_internes_medecin.code IS NULL
				ORDER BY 1;
				
				/**********************************************************************************
				 *                                  MEDECINS                                      *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_medecins (code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				SELECT
					NOPRAT as code
					,NOMPRAT as nom
					,PRENOMPRAT as prenom
					,COALESCE(t_specialites_medecin.oid, 0) as specialite_id
                    ,COALESCE(RPPS,'') AS RPPS
                    ,COALESCE(t_specialites_internes_medecin.oid, 0) as specialite_interne_id
				FROM
					prod_mederi.KPRAT
					LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = NOSPEC
                    LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = NOSPEC || '..')
                    LEFT JOIN pmsi.t_medecins ON NOPRAT = t_medecins.code
                WHERE t_medecins.code IS NULL;
                
                SELECT pmsi.cti_reorganize_medecins_c();
				
				/**********************************************************************************
				 *                               UNITES MEDICALES                                 *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_unites_medicales (code, texte)
				SELECT
					CODEUM
					,LIBSERVSS
				FROM
					prod_mederi.KSERVINT
                    JOIN prod_mederi.KSERVSS ON KSERVINT.NOSERVSS = KSERVSS.NOSERVSS
					JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = KSERVINT.CODEUM
                WHERE
                    CODEUM != '' AND
					t_unites_medicales.code IS NULL 
				GROUP BY 1,2
				ORDER BY 1;
				
                UPDATE pmsi.t_unites_medicales
                SET texte = LIBSERVSS
                FROM prod_mederi.KSERVINT
                        JOIN prod_mederi.KSERVSS ON KSERVINT.NOSERVSS = KSERVSS.NOSERVSS
                WHERE t_unites_medicales.code = CODEUM AND
                    texte <> LIBSERVSS;
                
				/**********************************************************************************
				 *                             UNITES FONCTIONNELLES                           *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_unites_fonctionnelles(oid, code, texte) 
				SELECT 0, '', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM pmsi.t_unites_fonctionnelles);
				
				INSERT INTO pmsi.t_unites_fonctionnelles (code, texte)
				SELECT NOSERVSS, LIBSERVSS
				FROM prod_mederi.KSERVSS
				LEFT JOIN pmsi.t_unites_fonctionnelles uf ON code = NOSERVSS
				WHERE 
					uf.code IS NULL
				ORDER BY 1;
				
			
				
                /**********************************************************************************
				 *                            PRESTATIONS                              *
				 **********************************************************************************/
				
                INSERT INTO pmsi.t_prestations(code, texte, texte_court)
				SELECT 
					NOACTE,
					LIBELLE,
					LIBELLE
				FROM prod_mederi.KRUBTAR
				WHERE NOACTE NOT IN (select code from pmsi.t_prestations)
				GROUP BY 1,2,3;                          
                 
								
				/**********************************************************************************
				 *                             COEFF MCO                              *
				 **********************************************************************************/
                 
                DROP TABLE IF EXISTS w_coef;
                CREATE TEMP TABLE w_coef as 
                SELECT DATEDEB, COEFF, row_number() over (order by DATEDEB) 
                FROM prod_mederi.ETABLI
                LEFT JOIN prod_mederi.ETABCOEF ON 1=1
                WHERE NOFITNESS IN (SELECT code FROM base.t_finess)
                ORDER BY DATEDEB;
                UPDATE base.t_finess SET
                    date_debut_coefficient_mco_1 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 1),
                    date_debut_coefficient_mco_2 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 3),
                    date_debut_coefficient_mco_3 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 3),
                    date_debut_coefficient_mco_4 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 4),
                    date_debut_coefficient_mco_5 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 5),
                    date_debut_coefficient_mco_6 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 6),
                    date_debut_coefficient_mco_7 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 7),
                    date_debut_coefficient_mco_8 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 8),
                    date_debut_coefficient_mco_9 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 9),
                    coefficient_mco_1 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 1),
                    coefficient_mco_2 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 2),
                    coefficient_mco_3 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 3),
                    coefficient_mco_4 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 4),
                    coefficient_mco_5 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 5),
                    coefficient_mco_6 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 6),
                    coefficient_mco_7 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 7),
                    coefficient_mco_8 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 8),
                    coefficient_mco_9 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 9);
          
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Identités">
			<sqlcmd><![CDATA[
			
                
				-- Numéros de séjours des externes selon numéro de facture
				UPDATE [SCHEMA].p_rss
				SET no_sejour_administratif = NODOSSIER
				FROM
				(
				SELECT p_rsf_total.rss_id, KFACTURE.NODOSSIER
				FROM [SCHEMA].p_rsf_total
				JOIN [SCHEMA].p_rss ON p_rsf_total.rss_id = p_rss.oid
				JOIN prod_mederi.KFACTURE ON KFACTURE.NOFAC = p_rsf_total.no_facture
				JOIN prod_mederi.KDOSSIER ON KFACTURE.NODOSSIER = KDOSSIER.NODOSSIER
				WHERE no_sejour_administratif IS DISTINCT FROM KFACTURE.NODOSSIER AND
					(
					date_entree = KDOSSIER.DATEENTREE OR
					date_sortie = KDOSSIER.DATESORTIE
					) AND
					ghm_id = 0 AND
					p_rss.import_id > 0
				) subview
				WHERE p_rss.oid = subview.rss_id
				;
            
				UPDATE [SCHEMA].p_identites SET
					nom = NOMPAT
					,prenom = PRENOMPAT
					,nom_naissance = NOMJFPAT
				FROM [SCHEMA].p_rss
                    JOIN prod_mederi.KDOSSIER ON KDOSSIER.NODOSSIER = no_sejour_administratif
				WHERE
					p_identites.rss_id = p_rss.oid AND
					p_rss.import_id > 0
				;
                
                UPDATE [SCHEMA].p_rss SET code_postal = SUBSTR(CPPAT, 1 , 5)
				FROM prod_mederi.KDOSSIER
				WHERE no_sejour_administratif = KDOSSIER.NODOSSIER;
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Médecins RSS">
			<sqlcmd><![CDATA[

                UPDATE [SCHEMA].p_rss SET medecin_rss_id = t_medecins.oid
				FROM 
                    prod_mederi.KDOSSIER 
					JOIN pmsi.t_medecins ON t_medecins.code = NOPRAT
				WHERE no_sejour_administratif = KDOSSIER.NODOSSIER AND 
					p_rss.import_id > 0 AND
					medecin_rss_id <> t_medecins.oid;
                                     
			]]></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_mederi.KDOSSIER
                    JOIN prod_mederi.KACTES ON KACTES.NODOSSIER = KDOSSIER.NODOSSIER
					JOIN pmsi.t_medecins ON t_medecins.code = KACTES.NOPRAT
				WHERE 
                    KDOSSIER.NODOSSIER = no_sejour_administratif
					AND p_rss_actes.rss_id = p_rss.oid
					AND p_rss_actes.date_acte = date(DATEACTE)
					AND p_rss_actes.activite_ccam = ACTIVITE
					AND p_rss_actes.acte_id = t_actes.oid
					AND t_actes.code = substring(NCCAM, 1, 7)
					AND p_rss_actes.medecin_id <> t_medecins.oid
					AND p_rss.import_id > 0;
		
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Etat des dossiers">
			<sqlcmd><![CDATA[
				
				SELECT pmsi.cti_initialize_rss_etat();
			
			]]></sqlcmd>
		</NODE>	
        
        
		
	</NODE>
	
	<NODE name="PMSIENCOURS" label="RECUPERATION DES DOSSIERS PMSI EN-COURS MEDERI">
		
		<NODE label="Paramètres">
			<sqlcmd><![CDATA[
				 /**********************************************************************************
				 *                             SPECIALITES MEDECINS                              *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_specialites_medecin(code,texte)
				SELECT 
					NOSPEC,
					LIBELLE
				FROM prod_mederi.KSPECIAL
					LEFT JOIN pmsi.t_specialites_medecin on t_specialites_medecin.code = NOSPEC
				WHERE t_specialites_medecin.code IS NULL 
				ORDER BY 1;
				
				INSERT INTO pmsi.t_specialites_internes_medecin(code, texte)
				SELECT
					t_specialites_medecin.code::text || '..'::text,
					t_specialites_medecin.texte
				FROM
					pmsi.t_specialites_medecin
					LEFT JOIN pmsi.t_specialites_internes_medecin on t_specialites_internes_medecin.code = t_specialites_medecin.code::text || '..'::text
				WHERE 1=1
					AND t_specialites_medecin.oid <> 0
					AND t_specialites_internes_medecin.code IS NULL
				ORDER BY 1;
				
				/**********************************************************************************
				 *                                  MEDECINS                                      *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_medecins (code, nom, prenom, specialite_id, no_adeli, specialite_interne_id)
				SELECT
					NOPRAT as code
					,NOMPRAT as nom
					,PRENOMPRAT as prenom
					,COALESCE(t_specialites_medecin.oid, 0) as specialite_id
                    ,COALESCE(RPPS,'') AS RPPS
                    ,COALESCE(t_specialites_internes_medecin.oid, 0) as specialite_interne_id
				FROM
					prod_mederi.KPRAT
					LEFT JOIN pmsi.t_specialites_medecin ON t_specialites_medecin.code = NOSPEC
                    LEFT JOIN pmsi.t_specialites_internes_medecin ON (t_specialites_internes_medecin.code = NOSPEC || '..')
                    LEFT JOIN pmsi.t_medecins ON NOPRAT = t_medecins.code
                WHERE t_medecins.code IS NULL;
                
                SELECT pmsi.cti_reorganize_medecins_c();
				
				/**********************************************************************************
				 *                               UNITES MEDICALES                                 *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_unites_medicales (code, texte)
				SELECT
					CODEUM
					,LIBSERVSS
				FROM
					prod_mederi.KSERVINT
                    JOIN prod_mederi.KSERVSS ON KSERVINT.NOSERVSS = KSERVSS.NOSERVSS
					JOIN pmsi.t_unites_medicales ON t_unites_medicales.code = KSERVINT.CODEUM
                WHERE
                    CODEUM != '' AND
					t_unites_medicales.code IS NULL 
				GROUP BY 1,2
				ORDER BY 1;
				
                UPDATE pmsi.t_unites_medicales
                SET texte = LIBSERVSS
                FROM prod_mederi.KSERVINT
                        JOIN prod_mederi.KSERVSS ON KSERVINT.NOSERVSS = KSERVSS.NOSERVSS
                WHERE t_unites_medicales.code = CODEUM AND
                    texte <> LIBSERVSS;
                
				/**********************************************************************************
				 *                             UNITES FONCTIONNELLES                           *
				 **********************************************************************************/
				
				INSERT INTO pmsi.t_unites_fonctionnelles(oid, code, texte) 
				SELECT 0, '', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM pmsi.t_unites_fonctionnelles);
				
				INSERT INTO pmsi.t_unites_fonctionnelles (code, texte)
				SELECT NOSERVSS, LIBSERVSS
				FROM prod_mederi.KSERVSS
				LEFT JOIN pmsi.t_unites_fonctionnelles uf ON code = NOSERVSS
				WHERE 
					uf.code IS NULL
				ORDER BY 1;
				
                /**********************************************************************************
				 *                            PRESTATIONS                              *
				 **********************************************************************************/
				
                INSERT INTO pmsi.t_prestations(code, texte, texte_court)
				SELECT 
					NOACTE,
					LIBELLE,
					LIBELLE
				FROM prod_mederi.KRUBTAR
				WHERE NOACTE NOT IN (select code from pmsi.t_prestations)
				GROUP BY 1,2,3;                          
                 
								
				/**********************************************************************************
				 *                             COEFF MCO                              *
				 **********************************************************************************/
                 
                DROP TABLE IF EXISTS w_coef;
                CREATE TEMP TABLE w_coef as 
                SELECT DATEDEB, COEFF, row_number() over (order by DATEDEB) 
                FROM prod_mederi.ETABLI
                LEFT JOIN prod_mederi.ETABCOEF ON 1=1
                WHERE NOFITNESS IN (SELECT code FROM base.t_finess)
                ORDER BY DATEDEB;
                UPDATE base.t_finess SET
                    date_debut_coefficient_mco_1 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 1),
                    date_debut_coefficient_mco_2 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 3),
                    date_debut_coefficient_mco_3 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 3),
                    date_debut_coefficient_mco_4 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 4),
                    date_debut_coefficient_mco_5 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 5),
                    date_debut_coefficient_mco_6 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 6),
                    date_debut_coefficient_mco_7 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 7),
                    date_debut_coefficient_mco_8 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 8),
                    date_debut_coefficient_mco_9 = (SELECT date(DATEDEB) FROM w_coef WHERE row_number = 9),
                    coefficient_mco_1 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 1),
                    coefficient_mco_2 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 2),
                    coefficient_mco_3 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 3),
                    coefficient_mco_4 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 4),
                    coefficient_mco_5 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 5),
                    coefficient_mco_6 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 6),
                    coefficient_mco_7 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 7),
                    coefficient_mco_8 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 8),
                    coefficient_mco_9 = (SELECT COEFF::numeric FROM w_coef WHERE row_number = 9);
			]]></sqlcmd>
		</NODE>
			
		<NODE label="RSS">
			<sqlcmd><![CDATA[
				
				DROP TABLE IF EXISTS w_DOSSIER;
				CREATE TEMP TABLE w_DOSSIER AS
				SELECT 
					NOFITNESS,	
					KDOSSIER.* ,
					COALESCE(DATESORTIE, '20991231') AS date_sortie,
					'N'::text AS CTI_OK,
					''::text AS dup_type_sejour,
					'0'::text AS dup_code_prevu,
					0::bigint AS dup_sejour_id,
					0::bigint AS dup_medecin_sejour_id,
					''::text AS dup_etat,
					rank() OVER (PARTITION BY KDOSSIER.NODOSSIER ORDER BY DATESORTIE, HEURESOR) as rank,
					K5CLEUNIK
				FROM prod_mederi.KDOSSIER
					LEFT JOIN prod_mederi.KRSS ON KDOSSIER.NODOSSIER = KRSS.NODOSSIER
					,prod_mederi.ETABLI--LEFT JOIN prod_mederi.ETABLI ON KDOSSIER.NOETABLI = ETABLI.NOETABLI
                WHERE  1=1
					AND COALESCE(COALESCE(DATESORTIE,RSSSORT), '20991231') >=  '20160101'
					AND COALESCE(COALESCE(DATESORTIE,RSSSORT), '20991231') <= now()
                ORDER BY NODOSSIER, K5CLEUNIK;

                -- date entrée > datedeb 
                UPDATE w_DOSSIER 
                SET
                    DATEENTREE = KSEJOUR.DATEDEB,
                    HEUREENT = KSEJOUR.HEUREDEB
                FROM prod_mederi.KSEJOUR
                WHERE 
                    DATEENTREE > w_DOSSIER.DATEDEB
                    AND KSEJOUR.NODOSSIER = w_DOSSIER.NODOSSIER
                    AND w_DOSSIER.DATEDEB = KSEJOUR.DATEDEB;

                
                UPDATE w_DOSSIER 
                SET
                    NODOSSIER = NODOSSIER || '_' || rank
                WHERE rank != 1;
                
                -- modification de la table des rss pour prendre en compte les rss multiples par séjour
                
                UPDATE prod_mederi.KRSS 
                SET 
                    NODOSSIER = w_DOSSIER.NODOSSIER 
                FROM w_DOSSIER
                WHERE KRSS.K5CLEUNIK = w_DOSSIER.K5CLEUNIK
                ;
                
				CREATE INDEX  w_dossier_i1
				  ON  w_dossier
				  USING btree
				  (NODOSSIER);
				
				ANALYSE W_DOSSIER;
				
				-- ghm et ghs
                DROP TABLe IF EXISTS w_KRSSLOG;
                CREATE TEMP TABLE w_KRSSLOG AS
                SELECT 
                    RSSNR,
                    MAX(PMSI_DEXPORT) AS PMSI_DEXPORT,
                    (MAX(Array[PMSI_DEXPORT::text, VERROUAP::text]))[2]  AS VERROUAP,
                    (MAX(Array[PMSI_DEXPORT::text, GHM::text]))[2]  AS GHM
                FROM prod_mederi.KRSSLOG
                GROUP BY 1
                ;
			
				DROP TABLE IF EXISTS w_rss;
				CREATE TEMP TABLE w_rss AS
				SELECT 
					KRSS.*,
					w_DOSSIER.NOFITNESS,
					w_DOSSIER.NIP,
					w_DOSSIER.NODOSSIER as NODOSSIER_ADM,
					NOMPAT,
					PRENOMPAT,
					NOMJFPAT,
					CPPAT,
					DATEENTREE,
					DATESORTIE,
					NOPRAT,
					TYPDOS,
					nextval('pmsi.s_rss'::regclass) AS rss_id
				FROM prod_mederi.KRSS 
					JOIN w_DOSSIER ON (w_DOSSIER.K5CLEUNIK = KRSS.K5CLEUNIK)
					--JOIN prod_mederi.PMS_RUM ON (TRUM_ID_TRSS = TRSS_ID_TRSS)
					LEFT JOIN pmsi.p_rss ON RSSNR::bigint = p_rss.no_rss AND p_rss.etat = '' AND date_trunc('month',p_rss.date_sortie) = date_trunc('month', RSSSORT)
				WHERE RSSSORT BETWEEN '[ANNEE]0101' AND ('[ANNEE]1231'::date + '10 years'::interval)::date AND RSSNR > 0
					AND RSSENTRE <= RSSSORT
					AND (w_DOSSIER.TYPDOS < 4 OR KRSS.RSSCMDGHM BETWEEN '01' AND '29') 
					AND p_rss.no_rss IS NULL
				ORDER BY RSSNR;
				
				-- Suppression faux RSS (souvent transformés en SE)
				DELETE FROM w_rss
				USING
				(
				SELECT w_rss.NODOSSIER
				FROM w_rss
				JOIN prod_mederi.KSEJOUR ON w_rss.NODOSSIER = KSEJOUR.NODOSSIER
				JOIN prod_mederi.KSERVINT ON KSEJOUR.NOSERVINT = KSERVINT.NOSERVINT 
				WHERE GENPMSI <> '1'
				GROUP BY 1
				) subview
				WHERE w_rss.NODOSSIER = subview.NODOSSIER
				;
				
				DELETE FROM w_rss
				USING
				(
				SELECT w_rss.NODOSSIER,
					SUM(CASE WHEN NOACTE LIKE 'SE%' OR NOACTE LIKE 'ATU' THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END ELSE 0 END) AS QTE_EXT,
					SUM(CASE WHEN NOACTE LIKE 'GHS' THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END ELSE 0 END) AS QTE_GHS
				FROM w_rss
				JOIN prod_mederi.KACTES ON w_rss.NODOSSIER = KACTES.NODOSSIER
				JOIN prod_mederi.KFACTURE ON KACTES.NOFAC = KFACTURE.NOFAC
				WHERE TYPERUB = '1' AND
					(NOACTE LIKE 'SE%' OR NOACTE LIKE 'ATU' OR NOACTE LIKE 'GHS')
				GROUP BY 1
				HAVING SUM(CASE WHEN NOACTE LIKE 'SE%' OR NOACTE LIKE 'ATU' THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END ELSE 0 END) > 0 AND
					SUM(CASE WHEN NOACTE LIKE 'GHS' THEN CASE WHEN TYPEFAC NOT IN ('2','4') THEN QTE ELSE 0-QTE END ELSE 0 END) = 0
				) subview
				WHERE w_rss.NODOSSIER = subview.NODOSSIER
				;
	
				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
						)
				SELECT 
						NOFITNESS, 
						w_rss.rss_id AS oid, 
						w_rss.RSSNR::bigint AS no_rss, 
						0 AS no_patient, 
						'11' AS version_groupage, 
						date(RSSNELE) AS date_naissance, 
						SEXE,
						RSSENTRE AS date_entree, 
						RSSSORT AS date_sortie, 
						'8' AS mode_entree, 
						'' AS provenance, 
						'8' AS mode_sortie, 
						'' AS destination, 
						CPPAT AS code_postal, 
						0 AS poids_bebe, 
						0 AS igs2, 
						'' AS cma, 
						substr(GHM , 3 , 1) AS groupe_ghm, 
						CASE WHEN RSSSORT > RSSENTRE THEN date(RSSSORT) - date(RSSENTRE) ELSE 0 END AS duree_sejour, 
						CASE WHEN substr(GHM,1,2) = '28' THEN 1 ELSE 1 END AS nb_rsa, 
						CASE WHEN RSSENTRE > RSSNELE THEN trunc((date(RSSENTRE) - date(RSSNELE)) / 365.25,0) ELSE 0 END AS age, 
						'' AS supprime, 
						now() AS date_import, 
						1 AS nb_rum, 
						'' AS secteur, 
						NODOSSIER_ADM AS no_sejour_administratif, 
						CASE WHEN substr(GHM,1,2) = '28' THEN 1 ELSE 0 END AS nb_seances, 
						'' AS ghm_fg9, 
						COALESCE(t_ghm.oid, 0) AS ghm_id, 
						t_medecins.oid AS medecin_rss_id, 
						COALESCE(t_ghs.oid, 0) AS ghs_id, 
						date_part('year', RSSSORT) * 100 + date_part('month', RSSSORT) AS mois_sortie, 
						0 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(GHM) = 6 AND substr(GHM,1,2) <> '90' THEN 'V' 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, 
						'' AS code_retour_groupage, 
						0 AS comite_medical_id, 
						'0' AS rehosp_meme_ghm, 
						0 AS from_oid
				FROM w_rss
						LEFT JOIN w_KRSSLOG ON w_rss.RSSNR = w_KRSSLOG.RSSNR
						LEFT JOIN pmsi.t_ghm ON (GHM = t_ghm.code)
						LEFT JOIN pmsi.t_ghs ON (VERROUAP = t_ghs.code)
						LEFT JOIN pmsi.t_medecins ON (NOPRAT = t_medecins.code)
				;
	
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Identités">
			<sqlcmd><![CDATA[
				
				INSERT INTO pmsi.p_identites(
						finess, 
						rss_id,
						no_rss, 
						nom, 
						prenom, 
						nom_naissance)
				SELECT 
						NOFITNESS, 
						w_rss.rss_id AS oid, 
						RSSNR::bigint AS no_rss, 
						NOMPAT AS nom, 
						PRENOMPAT AS prenom, 
						NOMJFPAT AS nom_naissance
				FROM w_rss;
							
				UPDATE pmsi.p_rss SET
                 no_sejour_administratif = KFACTURE.NODOSSIER
                 FROM w_rss
					LEFT JOIN w_KRSSLOG ON w_rss.RSSNR = w_KRSSLOG.RSSNR
                    JOIN prod_mederi.KFACTURE ON KFACTURE.NODOSSIER = w_rss.NODOSSIER
                 WHERE NOFAC = no_sejour_administratif
                    AND (TYPDOS IN (6,2) 
                        OR (TYPDOS = 3 AND NOFAC IS NOT NULL AND GHM IS NULL));
        				
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Rum">
			<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_rum
				;
				CREATE TEMP TABLE w_rum AS
					SELECT 
						KRUM.*,
						0 AS WRUM_NUMERO,
						0 AS tmp_rum_num,
						0 AS tmp_min_rum_num
					FROM prod_mederi.KRUM
						JOIN w_rss ON w_rss.RSSNR = KRUM.RSSNR
					ORDER BY RSSNR, RSSNO
				;
					
				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
						RSSNR,
						min(tmp_rum_num) AS tmp_min_rum_num
					FROM w_rum
					GROUP BY RSSNR
					) AS subq
				WHERE w_rum.RSSNR = subq.RSSNR
				;
				UPDATE w_rum
				SET WRUM_NUMERO = tmp_rum_num - tmp_min_rum_num + 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)
				SELECT
					NOFITNESS, 
					w_rss.rss_id AS oid, 
					w_rss.RSSNR::bigint AS no_rss, 
					WRUM_NUMERO AS no_rum, 
					date(DATEDEBUM) AS date_entree, 
					date(DATEFINUM) AS date_sortie, 
					MODEENTREE::bigint AS mode_entree, 
					CASE WHEN substring(PROVENANCE,1,1) != '0' THEN substring(PROVENANCE,1,1) ELSE '' END, 
					MODESORTIE::bigint AS mode_sortie, 
					CASE WHEN substring(DESTINATION,1,1) != '0' THEN substring(DESTINATION,1,1) ELSE '' END, 
					CASE WHEN DATEFINUM > DATEDEBUM THEN date(DATEFINUM) - date(DATEDEBUM) ELSE 0 END AS duree_sejour, 
					w_rum.NBSEANCES AS nb_seances, 
					NOUM AS unite_medicale, 
					COALESCE(diap.oid,0) AS diagnostic_principal_id, 
					COALESCE(diar.oid,0) AS diagnostic_relie_id, 
					COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id, 
					'' AS type_autorisation, 
					w_rss.IGS2::numeric, 
					'' AS type_autorisation_lit_dedie, 
					'' AS supplement_code
				FROM w_rum
					JOIN w_rss ON (w_rum.RSSNR = w_RSS.RSSNR)
					LEFT JOIN pmsi.t_diagnostics diap ON w_rum.DP = diap.code
					LEFT JOIN pmsi.t_diagnostics diar ON w_rum.DR = diar.code
					LEFT JOIN pmsi.t_unites_medicales ON (NOUM = t_unites_medicales.code);
	
	
				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)
				SELECT
					p_rss.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
				FROM pmsi.p_rss			
				WHERE en_cours = '1' AND oid NOT IN (select distinct rss_id from pmsi.p_rss_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;
	
				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;
	
	
				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[
				-- DP
				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.finess, 
					rss_id, 
					p_rss.no_rss, 
					no_rum, 
					p_rss_rum.diagnostic_principal_id, 
					'DP' AS type_diagnostic, 
					CASE WHEN p_rss.diagnostic_principal_id = p_rss_rum.diagnostic_principal_id THEN 'DP' ELSE 'DA' END AS type_diagnostic_rss, 
					'' AS imprecis, 
					unite_medicale, 
					unite_medicale_id
				FROM pmsi.p_rss_rum
					JOIN pmsi.p_rss ON rss_id = p_rss.oid
				WHERE 1 = 1
					AND p_rss_rum.diagnostic_principal_id != 0
					AND p_rss.en_cours = '1'
				;
				
				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.finess, 
					rss_id, 
					p_rss.no_rss, 
					no_rum, 
					p_rss_rum.diagnostic_principal_id, 
					'DR' AS type_diagnostic, 
					'DR' AS type_diagnostic_rss, 
					'' AS imprecis, 
					unite_medicale, 
					unite_medicale_id
				FROM pmsi.p_rss_rum
					JOIN pmsi.p_rss ON rss_id = p_rss.oid
				WHERE 1 = 1
					AND p_rss_rum.diagnostic_relie_id != 0
					AND p_rss.en_cours = '1'
					;
				
				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
					NOFITNESS, 
					rss_id AS oid, 
					w_rss.RSSNR::bigint AS no_rss, 
					WRUM_NUMERO AS no_rum, 
					COALESCE(t_diagnostics.oid,0) AS diagnostic_id, 
					'DA' AS type_diagnostic, 
					'DA' AS type_diagnostic_rss, 
					'' AS imprecis, 
					NOUM AS unite_medicale, 
					COALESCE(t_unites_medicales.oid,0) AS unite_medicale_id
				FROM prod_mederi.KDAS
					JOIN w_rum ON w_rum.RSSNR || w_rum.RSSNO = KDAS.RUM
					JOIN w_rss ON (w_rss.RSSNR::bigint = w_rum.RSSNR::bigint)
					JOIN pmsi.t_diagnostics ON (DAS = t_diagnostics.code)
					JOIN pmsi.t_unites_medicales ON (NOUM = t_unites_medicales.code)
				ORDER BY w_rss.rss_id, WRUM_NUMERO;
	
									
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Actes">
			<sqlcmd><![CDATA[
				
				INSERT INTO pmsi.t_modificateurs_ccam
				SELECT mod FROM (
					SELECT substr(modificat,1,1) as mod
					FROM prod_mederi.MCCAM
					UNION ALL 
					SELECT substr(modificat,2,1) as mod
					FROM prod_mederi.MCCAM
					UNION ALL
					SELECT substr(modificat,3,1) as mod
					FROM prod_mederi.MCCAM
					UNION ALL
					SELECT substr(modificat,4,1) as mod
				FROM prod_mederi.MCCAM) as sub
				WHERE 1=1 
					AND mod NOT IN (SELECT code FROM pmsi.t_modificateurs_ccam)
					AND mod != ''
				GROUP BY mod
				;
			
				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
					FINESS, 
					rss_id AS oid, 
					w_rum.RSSNR::bigint 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(DATEACTE) AS date_acte, 
					COALESCE(t_medecins.oid,0) AS medecin_id,
					COALESCE(t_actes.oid,0) AS acte_id, 
					1 AS nombre, 
					PHASE AS phase_ccam, 
					MODIF9 AS activite_ccam, 
					'' AS extension_ccam, 
					substr(modificat,1,1) AS modificateur_ccam_1, 
					substr(modificat,2,1) AS modificateur_ccam_2, 
					substr(modificat,3,1) AS modificateur_ccam_3, 
					substr(modificat,4,1) AS modificateur_ccam_4, 
					'' AS remboursement_excp_ccam, 
					MODIF8 AS association_nonprevue_ccam --attention valeurs non valides
				FROM prod_mederi.MCCAM
					JOIN
						w_rum ON 
							w_RUM.NODOSSIER = MCCAM.NODOSSIER
							AND (w_rum.RSSNO = MCCAM.RSSNO OR MCCAM.RSSNO IS NULL AND DATEACTE BETWEEN DATEDEBUM AND DATEFINUM)
					JOIN pmsi.p_rss_rum ON (w_rum.RSSNR::bigint = p_rss_rum.no_rss AND WRUM_NUMERO = p_rss_rum.no_rum)
					LEFT JOIN pmsi.t_actes ON (substring(CODEACTE, 1, 7) = t_actes.code)
					LEFT JOIN pmsi.t_medecins ON MCCAM.NOPRAT = t_medecins.code
					;
							
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Factures">
			<sqlcmd><![CDATA[ 
                DROP TABLE IF EXISTS w_rsf_3;
                CREATE TEMP TABLE w_rsf_3 AS
                SELECT 
                    w_rss.NOFITNESS, 
                    w_rss.rss_id AS rss_id, 
                    w_rss.RSSNR,  
                    KFACTURE.NOFAC, 
                    KACTES.ACCLEUNIK,
                    NOACTE,
                    NOACTEASS,
                    DATEACTE,
                    DATEFIN,
                    PRIXU,
                    QTE * KACTES.COEFF as QTE_COEFF,
                    MONTANT,
                    TAUXSS,
                    TYPERUB,
                    VERROUAP
                FROM prod_mederi.KACTES
                    JOIN prod_mederi.KFACTURE ON (KACTES.NOFAC = KFACTURE.NOFAC)
                    JOIN w_rss ON (KACTES.NODOSSIER = w_rss.NODOSSIER)
                    JOIN w_KRSSLOG ON w_KRSSLOG.RSSNR = w_rss.RSSNR
                WHERE FACAVOIR IS NULL 
                AND KFACTURE.ETATFAC <> 6;
	
				-- 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 DATEACTE != date_entree
					AND DATEFIN != date_sortie;
	
				DROP TABLE IF EXISTS w_rsf_5;
				CREATE TEMP TABLE w_rsf_5 AS
				SELECT 
					NOFITNESS, 
					rss_id, 
					RSSNR,  
					MIN(NOFAC) AS NOFAC, 
					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 TYPERUB = 1 THEN MONTANT ELSE 0 END) AS FACT_MTT_SEJ,
					SUM(CASE WHEN TYPERUB = 3 THEN MONTANT 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 
						NOFITNESS, 
						rss_id AS oid, 
						RSSNR::bigint 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, 
						substr(w_rsf_5.NOFAC,1,9) 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.NOFITNESS, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.RSSNR::bigint, 
						'' AS nature, 
						'' AS mt, 
						'' AS dmt, 
						date(DATEACTE) AS date_debut, 
						date(DATEFIN) AS date_fin, 
						QTE_COEFF AS nombre, 
						1 AS coefficient, 
						w_rsf_3.PRIXU AS prix_unitaire, 
						w_rsf_3.MONTANT AS base_remboursement, 
						TAUXSS AS taux_remboursement, 
						w_rsf_3.MONTANT AS sejour_facture, 
						w_rsf_3.MONTANT AS sejour_remboursable, 
						0 AS compteur, 
						'' AS ligne_t2a, 
						'' AS pec_fj, 
						1 AS coefficient_mco, 
						0 AS sejour_remboursable_2, 
						COALESCE(t_ghs.oid, 0) AS ghs_id,
						0 AS sejour_rembourse_noemie, 
						'' AS nature_noemie, 
						COALESCE(t_prestations.oid, 0) AS prestation_id, 
						'B' AS type, 
						0 AS coefficient_geo, 
						'1' AS est_ligne_rss, 
						'0' AS est_ligne_rum, 
						1 AS no_rum, 
						0 AS unite_medicale_id, 
						0 AS base_remboursement_rum
				FROM w_rsf_3
					JOIN pmsi.t_prestations ON (w_rsf_3.NOACTEASS = t_prestations.code)
					LEFT JOIN pmsi.t_ghs ON (to_number('0' || w_rsf_3.VERROUAP,'0000') = t_ghs.code)
				WHERE TYPERUB = 1;
											
			]]></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.NOFITNESS, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.RSSNR::bigint, 
						0 AS rang, 
						date(DATEACTE) AS date_lpp, 
						COALESCE(t_lpp.oid, 0) AS lpp_id, 
						QTE_COEFF AS nombre, 
						w_rsf_3.PRIXU AS prix_unitaire, 
						w_rsf_3.MONTANT AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM w_rsf_3
					JOIN prod_mederi.KLPP ON KLPP.ACCLEUNIK = w_rsf_3.ACCLEUNIK
					LEFT JOIN pmsi.t_lpp ON (CODE_TIPS = 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_3.NOFITNESS, 
						w_rsf_3.rss_id AS rss_id, 
						w_rsf_3.RSSNR::bigint, 
						0 AS rang, 
						date(DATEACTE) AS date_ucd, 
						COALESCE(t_ucd.oid,0) AS ucd_id, 
						KUCD.QTE AS nombre, 
						KUCD.COEFF AS coefficient_fractionnement, 
						KUCD.PRIXU AS prix_unitaire_achat, 
						MONTANTUECART AS prix_unitaire_ecart_indemnisable, 
						MONTANTTECART AS montant_ecart_indemnisable, 
						KUCD.MONTANT AS montant_facture, 
						'0' AS non_pris_en_compte
				FROM w_rsf_3
					JOIN prod_mederi.KUCD ON KUCD.ACCLEUNIK = w_rsf_3.ACCLEUNIK
					LEFT JOIN pmsi.t_ucd ON (CODEUCD = t_ucd.code);					
			]]></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[
				-- maj des séjours externes
				UPDATE pmsi.p_rss
				SET no_sejour_administratif = NODOSSIER
				FROM
				(
				SELECT p_rsf_total.rss_id, KFACTURE.NODOSSIER
				FROM pmsi.p_rsf_total
				JOIN pmsi.p_rss ON p_rsf_total.rss_id = p_rss.oid
				JOIN prod_mederi.KFACTURE ON KFACTURE.NOFAC = p_rsf_total.no_facture
				JOIN prod_mederi.KDOSSIER ON KFACTURE.NODOSSIER = KDOSSIER.NODOSSIER
				WHERE no_sejour_administratif IS DISTINCT FROM KFACTURE.NODOSSIER AND
					(
					date_entree = KDOSSIER.DATEENTREE OR
					date_sortie = KDOSSIER.DATESORTIE
					) AND
					ghm_id = 0 AND
					p_rss.import_id > 0
				) subview
				WHERE p_rss.oid = subview.rss_id
				;
            
				UPDATE pmsi.p_identites SET
					nom = NOMPAT
					,prenom = PRENOMPAT
					,nom_naissance = NOMJFPAT
				FROM pmsi.p_rss
                    JOIN prod_mederi.KDOSSIER ON KDOSSIER.NODOSSIER = no_sejour_administratif
				WHERE
					p_identites.rss_id = p_rss.oid AND
					p_rss.import_id > 0
				;
                
                UPDATE pmsi.p_rss SET code_postal = SUBSTR(CPPAT, 1 , 5)
				FROM prod_mederi.KDOSSIER
				WHERE no_sejour_administratif = KDOSSIER.NODOSSIER;
		
                UPDATE pmsi.p_rss SET medecin_rss_id = t_medecins.oid
				FROM 
                    prod_mederi.KDOSSIER 
					JOIN pmsi.t_medecins ON t_medecins.code = NOPRAT
				WHERE no_sejour_administratif = KDOSSIER.NODOSSIER AND 
					p_rss.import_id > 0 AND
					medecin_rss_id <> t_medecins.oid;
					
				UPDATE pmsi.p_rss_actes
				SET medecin_id = t_medecins.oid
				FROM pmsi.t_actes,
					pmsi.p_rss,
					prod_mederi.KDOSSIER
                    JOIN prod_mederi.KACTES ON KACTES.NODOSSIER = KDOSSIER.NODOSSIER
					JOIN pmsi.t_medecins ON t_medecins.code = KACTES.NOPRAT
				WHERE 
                    KDOSSIER.NODOSSIER = no_sejour_administratif
					AND p_rss_actes.rss_id = p_rss.oid
					AND p_rss_actes.date_acte = date(DATEACTE)
					AND p_rss_actes.activite_ccam = ACTIVITE
					AND p_rss_actes.acte_id = t_actes.oid
					AND t_actes.code = substring(NCCAM, 1, 7)
					AND p_rss_actes.medecin_id <> t_medecins.oid
					AND p_rss.import_id > 0;
					
				-- maj des etats
                DROP TABLE IF EXISTS w_RSS_LOG;
				CREATE TEMP TABLE w_RSS_LOG AS
				SELECT 
					KRSS.RSSNR::bigint, 
					date(RSSSORT) AS RSSSORT,
					COALESCE(MIN(CASE WHEN KRSSLOG.GHM <> '' AND PMSI_DEXPORT >= RSSSORT AND KRSSLOG.GHM = KRSS.RSSCMDGHM THEN date(PMSI_DEXPORT) ELSE NULL END),'20991231') AS date_groupage
				FROM prod_mederi.KRSSLOG 
					JOIN prod_mederi.KRSS ON KRSS.RSSNR::bigint = KRSSLOG.RSSNR::bigint
				GROUP BY 1,2;

				CREATE INDEX w_RSS_LOG_i1 ON w_RSS_LOG USING btree (RSSNR);

				UPDATE pmsi.p_rss_etat SET
					date_groupage = w_RSS_LOG.date_groupage
				FROM w_RSS_LOG
				JOIN pmsi.p_rss ON w_RSS_LOG.RSSNR::bigint = p_rss.no_rss AND w_RSS_LOG.RSSSORT = p_rss.date_sortie
				WHERE p_rss_etat.rss_id = p_rss.oid AND
					p_rss_etat.date_groupage <> w_RSS_LOG.date_groupage;

				DROP TABLE IF EXISTS w_sejo_fac;
				CREATE TEMP TABLE w_sejo_fac AS
				SELECT
					KFACTURE.NODOSSIER,
					MIN(date(KDOSSIER.DATEENTREE)) AS RSSENTRE, 
					MAX(date(KDOSSIER.DATESORTIE)) AS RSSSORT,
					COALESCE(MAX(date(DATEFAC)),'20991231') AS date_facture
				FROM prod_mederi.KFACTURE
				JOIN prod_mederi.KDOSSIER ON KFACTURE.NODOSSIER = KDOSSIER.NODOSSIER
				GROUP BY 1
				;

				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 NODOSSIER = no_sejour_administratif AND date_sortie = RSSSORT
					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>