<?php
$MODULE="pmsi";
$TITLE="Import des en-cours PMSI";
$DFTENDSTATUS="OK";
$ARGS="";
/** Laisser les lignes 2 à 5 sans changer la casse et sans espaces et dans cet ordre
 * car le script est lu et analysé quand il est exécuté via .exe ou Jenkins
 * pour gestion des fichiers .pid dans system\batch\logs
 */

/**
 * Test pour contrôler que la CI/CD est fonctionnelle pour le module PMSI
 * et le déploiement sur gitea.ctisante.com
 */

if (!defined('__ROOT__') ) {
	list($environmentPath) = explode(DIRECTORY_SEPARATOR.'modules', dirname(__FILE__));
	$environmentPath .= DIRECTORY_SEPARATOR;
	define('__ROOT__', $environmentPath);
}

require_once __ROOT__ . '/modules/base/php/lib/cti/Batch/iCTI_batch_common.php';
require_once __ROOT__ . '/modules/base/php/lib/cti/Database/Database2Factory.class.php';
require_once __ROOT__ . '/modules/base/php/lib/cti/Environnement/Environnement.class.php';
require_once __ROOT__ . '/modules/base/php/classSimpleXML.php';
require_once __ROOT__ . '/modules/outils/php/httpService_cacheManager_cleanCache.php';
require_once __ROOT__ . '/modules/pmsi/php/EtudeManager.php';
require_once __ROOT__ . '/modules/pmsi/import_rss_rsf/utils/import_functions.php';
require_once __ROOT__ . '/modules/pmsi/import_rss_rsf/utils/conso_functions.php';

// Constantes
define("ETABLISSEMENT_PRIVE", "1");
define("ETABLISSEMENT_PUBLIC", "2");
define("ETABLISSEMENT_ESPIC", "3");

//Globals
global $ENDSTATUS;
global $iCTI_connexion;
global $cti_args;

global $idEtablissement;
global $iCTI_cache;
global $SHS_connexion;



global $ENV_TYPEETS;
global $ENV_FINESS;
global $ENV_LOCALKEYS;

global $SHS_connected;
global $SHS_admlib;
global $SHS_gefilib;
global $SHS_pmsilib;

global $ENV_OPTPMSI_MED_CODOUID;
global $ENV_PMSIPROVIDER;
global $ENV_PMSIFILANNEE;
global $ENV_PMSI_DELETE_BEFORE_YEAR;
global $ENV_OPTIMISATIONS_VUES_MATERIALISEES;
global $ENV_OPTPMSI_GHSBB;



global $import_id;


$import_id = -1;



// Arguments transmis ?
$cti_args = new CTI_Args_class();
$cti_args->checkArgs();


logStartMsg("TRAITEMENT DES DONNEES RSS/RSF");

// parametres generaux
$file = "../../../settings/settings.XML";
$settings_xml = simplexml_load_file($file);

$ENV_CONSOLIDATION = "0";
$ENV_ADMPROVIDER = "";
$ENV_PMSIPROVIDER = "";
$ENV_FINESS = "999999999";
$ENV_LOCALKEYS = "";
$ENV_OPTIMISATIONS_VUES_MATERIALISEES = "";
//Initialisation de l'année de début à année en cours -1
$ENV_PMSIFILANNEE = date("Y")-1;
$ENV_PMSI_DELETE_BEFORE_YEAR = false;
foreach ($settings_xml->ENVIRONMENT as $environmentNode) {
	foreach ($environmentNode->PROPERTY as $propertyNode) {
		if ($propertyNode['name'] == 'CONSOLIDATION') {
			$ENV_CONSOLIDATION = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'TYPEETS') {
			$ENV_TYPEETS = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'ADMPROVIDER') {
			$ENV_ADMPROVIDER = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'PMSIPROVIDER') {
			$ENV_PMSIPROVIDER = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'FINESS') {
			$ENV_FINESS = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'OPTPMSI_GHSBB') {
            $ENV_OPTPMSI_GHSBB = trim($propertyNode['value']);
        }
		if ($propertyNode['name'] == 'LOCALKEYS') {
			$ENV_LOCALKEYS = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'OPTPMSI_MED_CODOUID') {
			$ENV_OPTPMSI_MED_CODOUID = trim($propertyNode['value']);
		}
		if ($propertyNode['name'] == 'PMSIFILANNEE') {
			//Soit on utilise dans le setting une année en dur soit un nombre d'année(s) précédé de la lettre A
			if (substr($propertyNode['value'],0,1)==='A'){
				//année en cours moins nombre années demandées
				$nbAnnee = intval(substr($propertyNode['value'],1));
				if ($nbAnnee === 0 && intval(date("m"))<7) {
					$nbAnnee++;
				}
				$ENV_PMSIFILANNEE = date("Y")-$nbAnnee;
			} else if ($propertyNode['value']!="" && strlen($propertyNode['value']) === 4) {
				// si années écrit en dur
				$ENV_PMSIFILANNEE = $propertyNode['value'];
			}
		}
		if ($propertyNode['name'] == 'PMSI_DELETE_BEFORE_YEAR') {
			$value = trim($propertyNode['value']);
			if (!is_default_value_setting($value)){
				//On garde par défault seulement les 10 dernières années
				$ENV_PMSI_DELETE_BEFORE_YEAR = get_ENV_PMSI_DELETE_BEFORE_YEAR($value);
				if (!$ENV_PMSI_DELETE_BEFORE_YEAR){
					logErrorMsg("Attention, mauvais paramètrage de l'attribut ENV_PMSI_DELETE_BEFORE_YEAR, doit se trouver entre A4 et A9");
				}
			}
		}

	}
}


if (isset($settings_xml->OPTIMISATIONS)) {
	foreach ($settings_xml->OPTIMISATIONS as $environmentNode) {
		foreach ($environmentNode->PROPERTY as $propertyNode) {
			if ($propertyNode['name'] == 'VUES_MATERIALISEES') {
				$ENV_OPTIMISATIONS_VUES_MATERIALISEES = trim($propertyNode['value']);
			}
		}
	}
}

logInfoMsg("DEPUIS " . $ENV_PMSIFILANNEE);

// forcage provider PMSI
if ($cti_args->args["-p"]) {
	$ENV_PMSIPROVIDER = $cti_args->args["-p"];
}


$ENV_ADMPROVIDER = strtoupper($ENV_ADMPROVIDER);
if ($ENV_ADMPROVIDER == "R2I") {
	$ENV_ADMPROVIDER = "HM";
}

$ENV_PMSIPROVIDER = strtoupper($ENV_PMSIPROVIDER);
if ($ENV_PMSIPROVIDER == "R2I") {
	$ENV_PMSIPROVIDER = "HM";
}


// Fil de l'eau PMSI traité
$prestataires = array("CEGI", "CLINICOM", "CORA", "CSIS", "HM", "QSP", "ORBIS", 
				      "SIM",  "SHS", "SIGEMS", "SIGEMS2", "WEB100T", "WEB100T2", 
					  "CHATAIGNERAIE", "MEDERI", "EVOLUCARE_OPALE");
if (!in_array($ENV_PMSIPROVIDER, $prestataires)) {
	logErrorMsg("Les prestataire $ENV_PMSIPROVIDER n'est pas traité" );
	logEndMsg("TRAITEMENT DES DONNEES RSS/RSF");
	return;

}

// Pas dans consolidation
if ($ENV_CONSOLIDATION == "1") {
	logErrorMsg("Cet environnement est un environnement consolidé");
	logEndMsg("TRAITEMENT DES DONNEES RSS/RSF");
	return;
}



// Type établissement
if ($ENV_TYPEETS != ETABLISSEMENT_PUBLIC && $ENV_TYPEETS != ETABLISSEMENT_ESPIC) {
	$ENV_TYPEETS = ETABLISSEMENT_PRIVE;
}

// Connexion iCTI
$iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
$ret = $iCTI_connexion->connect();


// Aspirateur
$exitCode = extraction_prod($ENV_PMSIPROVIDER);

// Extraction des encours
if ($exitCode == 0 || $cti_args->args["-f"] || $cti_args->args["-f1"]  ) {
	generation_initialisation_parametres();
	// Suppression de la génération précédente
	suppression_precedents();
	generation_RSS($ENV_PMSIPROVIDER, $ENV_ADMPROVIDER);

    generation_rum_post_traitements();
    generation_rsf_post_traitements();

    creation_chiffrier();
    set_oids();

    finalize();
	
	clean_bdd();
}




$iCTI_connexion->close();


logEndMsg("TRAITEMENT DES DONNEES RSS/RSF");

function get_ENV_PMSI_DELETE_BEFORE_YEAR ($year_AX){
	if (is_year_AX($year_AX)){
		//Doit se trouver entre A4 et A9, pour garder au moins les 5 dernères années
		$nbAnnee = intval(substr($year_AX,1));
		if ($nbAnnee > 9 || $nbAnnee < 4 ){
			return false;
		}
		return date("Y") - $nbAnnee;
	}

	return false;
}

function finalize() {

	global $cti_args;
	global $ENV_OPTIMISATIONS_VUES_MATERIALISEES;
	
	logInfoMsg("TRAITEMENTS FINAUX");
	
	logInfoMsg("Transformations Unités Médicales");
	$toResult = execute_sql("SELECT pmsi.cti_transform_um();", $nbE, $nbW );
	
	logInfoMsg("Estampillage IPA");
	$toResult = execute_sql("SELECT pmsi.cti_gen_ipa()", $nbE, $nbW );
	
	logInfoMsg("Indicateurs Maternité");
	$toResult = execute_sql("SELECT pmsi.cti_gen_maternite('pmsi', -1)", $nbE, $nbW );
	
	logInfoMsg("Estampillage SRC");
	$toResult = execute_sql("SELECT pmsi.cti_gen_src()", $nbE, $nbW );
    
    logInfoMsg("Estampillage REA");
	$toResult = execute_sql("SELECT pmsi.cti_gen_rea()", $nbE, $nbW );

	logInfoMsg("Gestes marqueurs");
	$toResult = execute_sql("SELECT pmsi.cti_gen_gm()", $nbE, $nbW );
	
	logInfoMsg("Cancérologie"); //CDC 2017
	$toResult = execute_sql("SELECT pmsi.cti_gen_cancero_2017()", $nbE, $nbW );
	execute_etude("CTI_CANCERO_2022");

    logInfoMsg("Cardiologie"); // CDC 2022
	execute_etude("CTI_CARDIO_INTERVENTIONNELLE_2022");
    
    logInfoMsg("Etudes. Impact CMA");
	$toResult = execute_sql("SELECT pmsi.cti_etude_impact_cma()", $nbE, $nbW );
	
	logInfoMsg("Indicateurs RSS SAE");
	$toResult = execute_sql("SELECT pmsi.cti_gen_sae(-1)", $nbE, $nbW );
	
	logInfoMsg("Récupération des tarifs bruts des ghs");
	$toResult = execute_sql("SELECT pmsi.cti_generation_caghs_sans_coefficient()", $nbE, $nbW );
	
	if (isset($cti_args->args["-xx"]) || isset($cti_args->args["--except-expert"])) {
		logInfoMsg("Omission de l'exécution règles EXPERT");
	}
	else {
		logInfoMsg("Exécution règles EXPERT");
		$toResult = execute_sql("SELECT pmsi.cti_expert_execute_rules()", $nbE, $nbW );
	}
	

	logInfoMsg("Nettoyage cache");
	cleanAllCache("iCTI_pmsi", TRUE);

		
	// Lancement du calcul des indicateurs Essentiels
	if (isset($cti_args->args["-xe"]) || isset($cti_args->args["--except-essentiels"])) {
		logInfoMsg("Omission du calcul des essentiels MCO");
	}
	else {
		logInfoMsg("Calcul ESSENTIELS MCO");
		$exe = "..\..\outils\dashboard\iCTI_aggregateCtiIndicators.exe";
		if (file_exists($exe)) {
			exec("$exe -m pmsi -e");
		}
		else {
			logErrorMsg("La fonction de calcul des essentiels MCO est absente");
		}
	}

	if ($ENV_OPTIMISATIONS_VUES_MATERIALISEES == '1') {
		logInfoMsg("Performance et optimisations. Rafraichissement des vues matérialisées.");
		$toResult = execute_sql("SELECT pmsi.cti_rafraichir_vues_materialisees()", $nbE, $nbW);
	}

    // Màj de NOW.
    $sqlcmd = "SELECT pmsi.cti_now('NOW','FORCE');";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW);
	
	logInfoMsg("FIN TRAITEMENTS FINAUX");

}

function generation_initialisation_parametres() {

    logInfoMsg("INITIALISATION PARAMETRES");

    $nbW = 0;
    $nbE = 0;

    // Lance la fonction qui insère l'oid 0 dans les tables de paramètres utlisées par le module PMSI
    $sqlcmd = <<<SQL
 SELECT pmsi.cti_initialize_tables();
SQL;

    execute_sql($sqlcmd, $nbE, $nbW );

    logInfoMsg("FIN INITIALISATION PARAMETRES. $nbE erreurs.");
}


function generation_RSS($ENV_PMSIPROVIDER, $ENV_ADMPROVIDER="") {

	global $iCTI_connexion;
	global $ENV_PMSIFILANNEE;
	global $ENV_TYPEETS;
	global $ENV_FINESS;
	global $ENV_OPTPMSI_MED_CODOUID;
	global $cti_args;

	$file = "../../../settings/databases/$ENV_PMSIPROVIDER.XML";
	$xml = simplexml_load_file($file);

	if ($ENV_PMSIPROVIDER == "HM" ||  $ENV_PMSIPROVIDER == "CEGI") {
		$idEtablissement = $xml['idEtablissement'];
	}

	if ($ENV_PMSIPROVIDER == "HM")	 {
		$HM_PMSI_PRATCOD_FIELD = "MEDE_CODE";
		if ($ENV_OPTPMSI_MED_CODOUID == "1") {
			$HM_PMSI_PRATCOD_FIELD = "MEDE_CODE";
		}
	}
	if ($ENV_PMSIPROVIDER == "SHS") {
		$SHS_pmsischema = trim($xml['pmsilib']);
		$SHS_activiteschema = trim($xml['admlib']);
	}
	if ($ENV_PMSIPROVIDER == "WEB100T" && $ENV_ADMPROVIDER == "SHS") {
		$fileadm = "../../../settings/databases/$ENV_ADMPROVIDER.XML";
		$xmladm = simplexml_load_file($fileadm);
		$SHS_activiteschema = trim($xmladm['admlib']);
	}


	// Chargement requetes SQL
	$environmentVars=array();
	$environmentVars["ADMPROVIDER"] = $ENV_ADMPROVIDER;
	$environmentVars["PMSISCHEMA"] = $SHS_pmsischema;
	$environmentVars["ACTIVITESCHEMA"] = $SHS_activiteschema;
	$environmentVars["HM_PMSI_PRATCOD_FIELD"] = $HM_PMSI_PRATCOD_FIELD;
	$environmentVars["ETAB"] = $idEtablissement;
	$environmentVars["TYPEETS"] = $ENV_TYPEETS;
	$environmentVars["FINESS"] = $ENV_FINESS;
	$environmentVars["ANNEE"] = $ENV_PMSIFILANNEE;

	$sqlOptions=array();
	foreach ($cti_args->args as $key => $value) {
		$sqlOptions[] = $key;
	}

	$cti_sqlStatements = new CTI_SqlStatements_class("iCTI_import_pmsi_$ENV_PMSIPROVIDER.XML",$iCTI_connexion,$environmentVars,$sqlOptions);

	// Exécution requetes SQL
	$cti_sqlStatements->executeStatementsNode("PMSIENCOURS");
	$cti_sqlStatements->executeStatementsNode("PMSIETAT");

	// specifique HP Metz pmsi web100T et activite CERNER. Les LPP et les UCD sont dans CERNER
	if ($ENV_PMSIPROVIDER == "WEB100T" && $ENV_ADMPROVIDER == "CERNER") {
		$cti_sqlStatements2 = new CTI_SqlStatements_class("iCTI_import_pmsi_$ENV_ADMPROVIDER.XML",$iCTI_connexion,$environmentVars,$sqlOptions);
		$cti_sqlStatements2->executeStatementsNode("PMSIENCOURS");
	}

	generation_rss_post_traitements_by_prestataire($ENV_PMSIPROVIDER);

}

// suppression en-cours précédent
function suppression_precedents() {


	logInfoMsg("SUPPRESSION GENERATION PRECEDENTE");

	$sqlcmd = "DELETE FROM pmsi.p_rss WHERE en_cours = '1'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	nettoyer_sejours();

	
	$sqlcmd = "SELECT * FROM setval('pmsi.s_rss'::regclass, COALESCE((SELECT MAX(oid) FROM pmsi.p_rss),0) + 1)";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	
	logInfoMsg("FIN SUPPRESSION GENERATION PRECEDENTE");

}


// Aspirateur
function extraction_prod($PMSIPROVIDER) {

	global $cti_args;

	if ($cti_args->args["-u"] || $cti_args->args["--prod-update"]) {
        logInfoMsg("CONTROLE REPLICATION BASE DE DONNEES PRODUCTION $PMSIPROVIDER");
        $prodsgbd_exe = realpath("../../../prodsgbd/iCTI_synchronize_prodsgbd_check.exe");
        $extractCmd = "$prodsgbd_exe -p $PMSIPROVIDER -m pmsi";
        $return = exec($extractCmd, $output_array);
        foreach ($output_array as $output_line) {
            if (trim($output_line) != "") {
                echo PHP_EOL . $output_line;
            }
        }

        logInfoMsg("FIN CONTROLE REPLICATION BASE DE DONNEES PRODUCTION $PMSIPROVIDER");
		return $return;
	}

    return checkLoadedData($PMSIPROVIDER,'pmsi');

}

function generation_rss_post_traitements_by_prestataire($PMSIPROVIDER){
	generation_transferts($PMSIPROVIDER);
}

function generation_transferts($PMSIPROVIDER) {

	global $ENV_TYPEETS;

	logInfoMsg("Etablissement provenance et destination (transfert)");
 
	// On verifie si les etablissements de transfert sont gere dans l'import du prestataire
	$sqlcmd = "
		SELECT EXISTS (
			SELECT FROM 
				pg_tables
			WHERE 
				schemaname = 'temp' AND 
				tablename  = 'w_transferts'
			) as is_tranfert;
	
	";
	$isTransfertSql = execute_sql($sqlcmd);
	$record = pg_fetch_array($isTransfertSql);
	// La query retourne "t" ou "f";
	$isTransfert = false;
	if ($record !== false){
		$isTransfert = $record["is_tranfert"] === "t";
	}
	if ($isTransfert){
		//  PRIVE (lots)
		//  L'etablissement de destination est toujours present dans les rsf-I, il reste alors fige apres l'import des lots
		//  Les etablissement de provenance sont donc importes du prestataire.

		if ($ENV_TYPEETS === ETABLISSEMENT_PRIVE){
			$sqlcmd = "
				UPDATE pmsi.p_rss_transferts
				SET 
					etablissement_provenance_id = prov_id
				FROM temp.w_TRANSFERTS
				WHERE w_TRANSFERTS.rss_id = p_rss_transferts.rss_id
				AND import_id != -1
				AND (
						etablissement_provenance_id IS DISTINCT FROM prov_id
					)
				;
				";
			$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		}

		// PUBLIC (lots)
		// Pas de RSF pour les publics, on recupere la provenance et destination du prestataire

		if ($ENV_TYPEETS !== ETABLISSEMENT_PRIVE){
			$sqlcmd = "
				UPDATE pmsi.p_rss_transferts
				SET 
					etablissement_provenance_id = prov_id,
					etablissement_destination_id = dest_id
				FROM temp.w_TRANSFERTS
				WHERE w_TRANSFERTS.rss_id = p_rss_transferts.rss_id
				AND import_id != -1
				AND (
						etablissement_provenance_id IS DISTINCT FROM prov_id OR
						etablissement_destination_id IS DISTINCT FROM dest_id
					)
				;
			";
			$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		}

		// Ajout des sejours en cours et des lots si ils ne pas present dans p_rss_transferts

		$sqlcmd =" 
		INSERT INTO pmsi.p_rss_transferts (rss_id, etablissement_provenance_id, etablissement_destination_id)
			SELECT rss_id, prov_id, dest_id
			FROM temp.w_TRANSFERTS JOIN pmsi.p_rss ON w_TRANSFERTS.rss_id = p_rss.oid
			WHERE (mode_entree IN (7, 0) OR mode_sortie IN (7, 0))				
			AND NOT EXISTS (SELECT 1 FROM pmsi.p_rss_transferts
							WHERE w_TRANSFERTS.rss_id = p_rss_transferts.rss_id)
		;";
		$toResult = execute_sql($sqlcmd, $nbE,  $nbW_rum );

		
		//On renomme la table temporaire lorsqu'il s'agit d'une fusion de prestataire
		//Le deuxieme prestataire pourra creer une nouvelle table w_transfert sans conflit
		$table_name_with_presta = "w_transferts_" . strtolower($PMSIPROVIDER);
		$sqlcmd = "
		DROP TABLE IF EXISTS temp.$table_name_with_presta;
		ALTER TABLE IF EXISTS temp.w_transferts
		RENAME TO $table_name_with_presta;
		";
		$toResult = execute_sql($sqlcmd);
	}

	// On rajoute les sejours avec mode d'entree ou sortie : transfert 
	// et qu'on a pas l'info des etablissements.

	$sqlcmd = "
	WITH w_transferts_non_present AS (
		SELECT oid as rss_id 
		FROM pmsi.p_rss 
		WHERE NOT EXISTS (
				SELECT 1 FROM pmsi.p_rss_transferts
				WHERE p_rss.oid = p_rss_transferts.rss_id
				)
		AND (mode_entree IN (7, 0) OR mode_sortie IN (7, 0))
		AND etat != 'S'
		GROUP BY 1
	)	INSERT INTO pmsi.p_rss_transferts (rss_id, etablissement_provenance_id, etablissement_destination_id)
		SELECT rss_id, 0,0
		FROM w_transferts_non_present
	;
	";
	$toResult = execute_sql($sqlcmd);

}

function generation_rum_post_traitements() {

	global $ENV_PMSIPROVIDER;
	
	global $import_id;

	logInfoMsg("TRAITEMENTS COMPLEMENTAIRES RUM");
	

	analyse_tables();
	
	$nbE = 0;

	
	logInfoMsg("Coefficient prudentiel théorique");
	// Détermination du coefficient prudentiel théorique en fonction de la date de sortie des séjours
	$sqlcmd = "
		UPDATE pmsi.p_rss SET
            coefficient_prudentiel_theorique = CASE	WHEN date_sortie >= '20160301'::date THEN 0.9950
                                                    WHEN date_sortie >= '20130301'::date THEN 0.9965
                                                    ELSE 1 END
        WHERE 1=1
            AND en_cours <> '0'
            AND coefficient_prudentiel_theorique IS NULL
	";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	logInfoMsg("Correction des dates de naissance");
	// Correction des dates de naissance lorsque le calcul de l'âge retourne un âge sur plus de 3 caractères.
	$sqlcmd = "
		UPDATE pmsi.p_rss 
		SET date_naissance = '19620418'
		WHERE 1=1
			AND en_cours <> '0'
			AND age <> trunc((date_entree::date - date_naissance::date) / 365.25,0)
			AND length(trunc((date_entree::date - date_naissance::date) / 365.25,0)) > 3
	";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	logInfoMsg("Calcul age");
	
	$sqlcmd = "UPDATE pmsi.p_rss 
			SET age = trunc((date_entree::date - date_naissance::date) / 365.25,0)  
			WHERE en_cours <> '0' AND age <> trunc((date_entree::date - date_naissance::date) / 365.25,0) ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss 
		SET duree_sejour = 0  
		WHERE en_cours <> '0' AND 
			duree_sejour <> 0 AND 
			ghm_id IN (SELECT oid FROM pmsi.t_ghm_c WHERE cmd_code = '28') ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	
	logInfoMsg("Suppression des RUM en double");
	$sqlcmd = "
		WITH doublons as (
			SELECT rss_id, no_rum FROM pmsi.p_rss_rum GROUP BY 1,2 HAVING count(*)  > 1
		)
		DELETE FROM pmsi.p_rss_rum
		USING doublons
		WHERE 1=1
			AND doublons.rss_id = p_rss_rum.rss_id
			AND doublons.no_rum = p_rss_rum.no_rum";
    $toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
    logInfoMsg("Initialisation unite medicale dans actes");

	$sqlcmd = "UPDATE pmsi.p_rss_actes 
			SET no_rum = p_rss_rum.no_rum, 
				unite_medicale = p_rss_rum.unite_medicale, 
				unite_medicale_id = p_rss_rum.unite_medicale_id 
			FROM pmsi.p_rss_rum 
			WHERE p_rss_actes.no_rum = 0 AND
				p_rss_actes.rss_id = p_rss_rum.rss_id AND
				p_rss_rum.date_entree <= p_rss_actes.date_acte AND
				p_rss_rum.date_sortie >= p_rss_actes.date_acte;
			";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss_actes SET unite_medicale_id = p_rss_rum.unite_medicale_id 
			FROM pmsi.p_rss_rum 
			WHERE (p_rss_actes.unite_medicale_id = 0 OR p_rss_actes.unite_medicale_id IS NULL) AND
				p_rss_actes.rss_id = p_rss_rum.rss_id AND p_rss_actes.no_rum = p_rss_rum.no_rum AND
				p_rss_actes.unite_medicale_id IS DISTINCT FROM p_rss_rum.unite_medicale_id; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	
	logInfoMsg("Initialisation unite medicale dans diagnostics");

	$sqlcmd = "UPDATE pmsi.p_rss_diagnostics SET unite_medicale_id = p_rss_rum.unite_medicale_id 
		FROM pmsi.p_rss_rum 
		WHERE (p_rss_diagnostics.unite_medicale_id = 0 OR p_rss_diagnostics.unite_medicale_id IS NULL) AND
			p_rss_diagnostics.rss_id = p_rss_rum.rss_id AND p_rss_diagnostics.no_rum = p_rss_rum.no_rum AND
			p_rss_diagnostics.unite_medicale_id IS DISTINCT FROM p_rss_rum.unite_medicale_id ;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	

	logInfoMsg("Initialisation médecins rss");
	
	$sqlcmd = "UPDATE pmsi.p_rss ";
	$sqlcmd = $sqlcmd . "SET medecin_rss_id = ";
	$sqlcmd = $sqlcmd . "CASE WHEN "; 
	$sqlcmd = $sqlcmd . "(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 ";
	$sqlcmd = $sqlcmd . "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 ";
	$sqlcmd = $sqlcmd . "WHERE import_id = $import_id ";
	$sqlcmd = $sqlcmd . "AND (medecin_rss_id = 0 or medecin_rss_id IN (SELECT oid FROM pmsi.t_medecins WHERE code = '9999'))  ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "UPDATE pmsi.p_rss SET medecin_rss_id = 0 WHERE medecin_rss_id IS NULL ;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	
	logInfoMsg("Initialisation types d'autorisation");
	
	$sqlcmd = "INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court)
			(SELECT type_autorisation, type_autorisation, type_autorisation 
			FROM pmsi.p_rss_rum 
			LEFT JOIN pmsi.t_types_autorisations ON type_autorisation = t_types_autorisations.code
			WHERE t_types_autorisations IS NULL
			GROUP BY 1) ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	$sqlcmd = "INSERT INTO pmsi.t_types_autorisations (code, texte, texte_court)
			(SELECT t_unites_medicales.type_autorisation, t_unites_medicales.type_autorisation, t_unites_medicales.type_autorisation 
			FROM pmsi.p_rss_rum JOIN pmsi.t_unites_medicales ON t_unites_medicales.oid = p_rss_rum.unite_medicale_id
			LEFT JOIN pmsi.t_types_autorisations ON t_unites_medicales.type_autorisation = t_types_autorisations.code
			WHERE t_types_autorisations.code IS NULL
			GROUP BY 1) ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	logInfoMsg("Initialisation RUM principal");
	
	$dateDebutFG12 = '20100301';
	
	$sqlcmd = "UPDATE pmsi.t_unites_medicales SET type_autorisation = '' WHERE type_autorisation IS NULL";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	//Pour web100t, le rum principal est récupéré dans la base
	if ($ENV_PMSIPROVIDER != "WEB100T") {

		// Trouver le RUM principal pour les séjours >= $dateDebutFG12
		trouver_rum_principal($dateDebutFG12);
	}
	
	// diag principal sur RSS
	$sqlcmd = "UPDATE pmsi.p_rss SET 
		unite_medicale_principale_id = unite_medicale_id, 
		diagnostic_principal_id = p_rss_rum.diagnostic_principal_id, 
		diagnostic_relie_id = p_rss_rum.diagnostic_relie_id 
		FROM pmsi.p_rss_rum 
		WHERE p_rss.oid = p_rss_rum.rss_id  AND 
			p_rss.no_rum_principal = p_rss_rum.no_rum AND
			(p_rss.unite_medicale_principale_id IS DISTINCT FROM unite_medicale_id OR
			p_rss.diagnostic_principal_id IS DISTINCT FROM p_rss_rum.diagnostic_principal_id OR
			p_rss.diagnostic_relie_id IS DISTINCT FROM p_rss_rum.diagnostic_relie_id)";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	

	
	
	/*// dignostics principaux sur rum secondaire
	$sqlcmd = "UPDATE pmsi.p_rss_diagnostics SET type_diagnostic_rss = 'DA' FROM pmsi.p_rss ";
	$sqlcmd = $sqlcmd . "WHERE p_rss.oid = p_rss_diagnostics.rss_id ";
	$sqlcmd = $sqlcmd . "AND p_rss.no_rum_principal <> p_rss_diagnostics.no_rum  ";
	$sqlcmd = $sqlcmd . "AND p_rss.nb_rum > 1  ";
	$sqlcmd = $sqlcmd . "AND type_diagnostic_rss <> 'DA' ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );*/
	
	// Médecin par défaut 
	$sqlcmd = "UPDATE pmsi.p_rss
			SET medecin_rss_id = medecin_par_defaut_id 
			FROM pmsi.t_unites_medicales
			WHERE unite_medicale_principale_id = t_unites_medicales.oid AND
				en_cours = '1' AND
				medecin_rss_id = 0 AND
				COALESCE(medecin_par_defaut_id,0) <> 0;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	
	
	
	
	logInfoMsg("Initialisation RSS sans nom");
	$sqlcmd = "INSERT into pmsi.p_identites (no_rss, nom, finess, rss_id) SELECT p_rss.no_rss, 'RSS ' || p_rss.no_rss::text, p_rss.finess, p_rss.oid FROM pmsi.p_rss  
			LEFT JOIN pmsi.p_identites ON (p_rss.oid = p_identites.rss_id) WHERE p_identites.rss_id IS NULL";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	

	
	
	// initialisation départements  provenant du RSS
	$sqlcmd = "INSERT INTO base.t_departements (code, texte, texte_court) SELECT DISTINCT substr(code ,1, 2), substr(code ,1, 2), substr(code ,1, 2) FROM base.t_codes_postaux WHERE substr(code ,1, 2) <> '97' AND substr(code ,1, 2) <> '98' AND substr(code ,1, 2) NOT IN (SELECT code FROM base.t_departements ); ";
	$sqlcmd = $sqlcmd . "INSERT INTO base.t_departements (code, texte, texte_court) SELECT DISTINCT substr(code ,1, 3), substr(code ,1, 3), substr(code ,1, 3) FROM base.t_codes_postaux WHERE substr(code ,1, 2) IN ('97', '98') AND substr(code ,1, 3) NOT IN (SELECT code FROM base.t_departements ); ";
	$toResult = execute_sql($sqlcmd);
	
	
	
	
	// initialisation codes postaux  provenant du RSS
	logInfoMsg("Initialisation codes postaux");
	
	// Réinitialise la séquence des codes postaux pour éviter les erreurs de clé primaire dupliquée
	$seq = -1;
	$sqlcmd = "SELECT max(oid) + 1 FROM base.t_codes_postaux";
	$toResult = execute_sql($sqlcmd);
	if (is_resource($toResult)) {
		while ($row = pg_fetch_array($toResult)) {
			$seq = $row[0] + 0;
		}
	}
	if ($seq > -1) {
		$sqlcmd = "ALTER SEQUENCE base.s_codes_postaux RESTART WITH $seq";
		$toResult = execute_sql($sqlcmd);
	}
	
	$sqlcmd = "
		INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id) 
		SELECT 
			DISTINCT code_postal, 
			code_postal, 
			code_postal, 
			COALESCE((SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 2)), 0), 
			substr(code_postal, 1 , 2) || '***',
			COALESCE((SELECT t_territoires_sante.oid FROM base.t_territoires_sante JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code JOIN base.t_departements ON t_departements.region_id = t_regions.oid WHERE t_departements.code = substr(code_postal, 1 , 2)), 0)
		FROM pmsi.p_rss 
		WHERE 
			code_postal <> '' 
			AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux ) 
			AND substr(code_postal, 1 , 2) NOT IN ('97', '98')
		; 
	
		INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id) 
		SELECT
			DISTINCT code_postal, 
			code_postal, 
			code_postal, 
			COALESCE((SELECT oid FROM base.t_departements WHERE code = substr(code_postal, 1 , 3)), 0),
			substr(code_postal, 1 , 3) || '**', 
			COALESCE((SELECT t_territoires_sante.oid FROM base.t_territoires_sante JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code JOIN base.t_departements ON t_departements.region_id = t_regions.oid WHERE t_departements.code = substr(code_postal, 1 , 3)), 0)
		FROM pmsi.p_rss  
		WHERE 
			code_postal <> '' 
			AND code_postal NOT IN (SELECT code FROM base.t_codes_postaux ) 
			AND substr(code_postal, 1 , 2) IN ('97', '98'); 
		
		INSERT INTO base.t_codes_postaux (code, texte, texte_court, departement_id, code_geographique_pmsi, territoire_sante_id) 
		SELECT DISTINCT code_postal, code_postal, code_postal, 0, '*****', 0
		FROM pmsi.p_rss 
		WHERE code_postal NOT IN (SELECT code FROM base.t_codes_postaux )";
	$toResult = execute_sql($sqlcmd);
	
	
	
	
	
	// OID code postal	
	$sqlcmd = "UPDATE pmsi.p_rss SET code_postal_id = t_codes_postaux.oid FROM base.t_codes_postaux 
		WHERE code_postal = t_codes_postaux.code AND (code_postal_id = 0 OR code_postal_id IS NULL OR code_postal_id <> t_codes_postaux.oid) AND code_postal <> '';";
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET code_postal_id = 0 WHERE code_postal = '' AND code_postal_id <> 0 OR code_postal_id IS NULL;";
	$toResult = execute_sql($sqlcmd);
	
	
	
	// Secteurs geographiques
	$sqlcmd = "INSERT INTO pmsi.t_secteurs_geographiques_codes_postaux (secteur_geographique_id, code_postal_id) ";
	$sqlcmd = $sqlcmd . "SELECT 0, oid FROM base.t_codes_postaux WHERE oid NOT IN (SELECT code_postal_id FROM pmsi.t_secteurs_geographiques_codes_postaux)";
	$toResult = execute_sql($sqlcmd);
	
	
	
	// Codes géographiques PMSI
	$sqlcmd = "INSERT INTO base.t_codes_geographiques_pmsi(oid, code, texte, texte_court, population, departement_id, territoire_sante_id) ";
	$sqlcmd = $sqlcmd . "SELECT 0, '*****', 'Non renseigné', 'Non renseigné', 0, 0, 0 WHERE 0 NOT IN (SELECT oid FROM base.t_codes_geographiques_pmsi WHERE oid = 0); ";
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population) ";
	$sqlcmd = $sqlcmd . "SELECT code_geographique_pmsi, substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255), substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255), sum(population) ";
	$sqlcmd = $sqlcmd . "FROM base.t_codes_postaux WHERE code_geographique_pmsi <> '' AND code_geographique_pmsi <> '*****'  ";
	$sqlcmd = $sqlcmd . "AND code_geographique_pmsi NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi) ";
	$sqlcmd = $sqlcmd . "GROUP BY code_geographique_pmsi ";
	$sqlcmd = $sqlcmd . "ORDER BY code_geographique_pmsi; ";
	$sqlcmd = $sqlcmd . "UPDATE base.t_codes_geographiques_pmsi SET texte = subview.texte,  texte_court = subview.texte, population = subview.population FROM ";
	$sqlcmd = $sqlcmd . "(SELECT code_geographique_pmsi, substr(base.cti_group_concat(DISTINCT trim(texte)), 1, 255) as texte, sum(population) as population ";
	$sqlcmd = $sqlcmd . "FROM base.t_codes_postaux WHERE code_geographique_pmsi <> '' AND code_geographique_pmsi <> '*****'  ";
	$sqlcmd = $sqlcmd . "GROUP BY code_geographique_pmsi  ";
	$sqlcmd = $sqlcmd . "ORDER BY code_geographique_pmsi) subview ";
	$sqlcmd = $sqlcmd . "WHERE t_codes_geographiques_pmsi.code = subview.code_geographique_pmsi  ";
	$sqlcmd = $sqlcmd . "AND (t_codes_geographiques_pmsi.texte <> subview.texte OR t_codes_geographiques_pmsi.population <> subview.population); ";
	$toResult = execute_sql($sqlcmd);
	
	

	$sqlcmd = "INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population) ";
	$sqlcmd = $sqlcmd . "SELECT code || '***', 'Divers ' || texte, 'Divers ' || texte, 0 ";
	$sqlcmd = $sqlcmd . "FROM base.t_departements WHERE code <> '**' AND length(code) = 2 ";
	$sqlcmd = $sqlcmd . "AND code || '***' NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi) ";
	$sqlcmd = $sqlcmd . "ORDER BY code; ";
	$sqlcmd = $sqlcmd . "INSERT INTO base.t_codes_geographiques_pmsi(code, texte, texte_court, population) ";
	$sqlcmd = $sqlcmd . "SELECT code || '**', 'Divers ' || texte, 'Divers ' || texte, 0 ";
	$sqlcmd = $sqlcmd . "FROM base.t_departements WHERE code <> '**' AND length(code) = 3 ";
	$sqlcmd = $sqlcmd . "AND code || '**' NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi) ";
	$sqlcmd = $sqlcmd . "ORDER BY code; ";
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "UPDATE base.t_codes_postaux SET code_geographique_pmsi_id = 0 WHERE code_geographique_pmsi_id IS NULL; ";
	$sqlcmd = $sqlcmd . "UPDATE base.t_codes_postaux SET code_geographique_pmsi_id = 0 ";
	$sqlcmd = $sqlcmd . "WHERE code_geographique_pmsi NOT IN (SELECT code FROM base.t_codes_geographiques_pmsi) ";
	$sqlcmd = $sqlcmd . "AND code_geographique_pmsi_id <> 0; ";
	$sqlcmd = $sqlcmd . "UPDATE base.t_codes_postaux SET code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid ";
	$sqlcmd = $sqlcmd . "FROM base.t_codes_geographiques_pmsi  ";
	$sqlcmd = $sqlcmd . "WHERE t_codes_postaux.code_geographique_pmsi = t_codes_geographiques_pmsi.code AND code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid; ";
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "UPDATE base.t_codes_postaux SET territoire_sante_id = 0 WHERE territoire_sante_id IS NULL; ";
	$sqlcmd = $sqlcmd . "UPDATE base.t_codes_postaux SET territoire_sante_id = 0 ";
	$sqlcmd = $sqlcmd . "WHERE territoire_sante_code NOT IN (SELECT code FROM base.t_territoires_sante) ";
	$sqlcmd = $sqlcmd . "AND territoire_sante_id <> 0; ";
	$sqlcmd = $sqlcmd . "UPDATE base.t_codes_postaux SET territoire_sante_id = t_territoires_sante.oid ";
	$sqlcmd = $sqlcmd . "FROM base.t_territoires_sante  ";
	$sqlcmd = $sqlcmd . "WHERE t_codes_postaux.territoire_sante_code = t_territoires_sante.code AND territoire_sante_id <> t_territoires_sante.oid; ";
	$toResult = execute_sql($sqlcmd);

	
	$sqlcmd = "
	UPDATE base.t_codes_postaux
	SET
		departement_id = t_departements.oid,
		departement_code = t_departements.code,
		departement_texte = t_departements.texte
	FROM base.t_departements
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_departements.code = substr(t_codes_postaux.code, 1 , 2)
		AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
		AND (
			departement_id <> t_departements.oid OR
			departement_code <> t_departements.code OR
			departement_texte <> t_departements.texte)
	;

	UPDATE base.t_codes_postaux
	SET
		departement_id = t_departements.oid,
		departement_code = t_departements.code,
		departement_texte = t_departements.texte
	FROM base.t_departements
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_departements.code = substr(t_codes_postaux.code, 1 , 3)
		AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
		AND (
			departement_id <> t_departements.oid OR
			departement_code <> t_departements.code OR
			departement_texte <> t_departements.texte)
	;

	UPDATE base.t_codes_postaux
	SET
		code_geographique_pmsi = t_codes_geographiques_pmsi.code,
		code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid,
		code_geographique_pmsi_code = t_codes_geographiques_pmsi.code,
		code_geographique_pmsi_texte = t_codes_geographiques_pmsi.texte
	FROM base.t_codes_geographiques_pmsi
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_codes_geographiques_pmsi.code = substr(t_codes_postaux.code, 1 , 2) || '***'
		AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
		AND (
			code_geographique_pmsi <> t_codes_geographiques_pmsi.code OR
			code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid OR
			code_geographique_pmsi_code <> t_codes_geographiques_pmsi.code OR
			code_geographique_pmsi_texte <> t_codes_geographiques_pmsi.texte)
	;

	UPDATE base.t_codes_postaux
	SET
		code_geographique_pmsi = t_codes_geographiques_pmsi.code,
		code_geographique_pmsi_id = t_codes_geographiques_pmsi.oid,
		code_geographique_pmsi_code = t_codes_geographiques_pmsi.code,
		code_geographique_pmsi_texte = t_codes_geographiques_pmsi.texte
	FROM base.t_codes_geographiques_pmsi
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_codes_geographiques_pmsi.code = substr(t_codes_postaux.code, 1 , 3) || '**'
		AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
		AND (
			code_geographique_pmsi <> t_codes_geographiques_pmsi.code OR
			code_geographique_pmsi_id <> t_codes_geographiques_pmsi.oid OR
			code_geographique_pmsi_code <> t_codes_geographiques_pmsi.code OR
			code_geographique_pmsi_texte <> t_codes_geographiques_pmsi.texte)
	;

	UPDATE base.t_codes_postaux
	SET
		territoire_sante_id = t_territoires_sante.oid,
		territoire_sante_code = t_territoires_sante.code,
		territoire_sante_texte = t_territoires_sante.texte
	FROM 
		base.t_territoires_sante
		JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
		JOIN base.t_departements ON t_departements.region_id = t_regions.oid
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_departements.code = substr(t_codes_postaux.code, 1 , 2)
		AND substr(t_codes_postaux.code, 1 , 2) NOT IN ('97', '98')
		AND (	territoire_sante_id <> t_territoires_sante.oid OR
			territoire_sante_code <> t_territoires_sante.code OR
			territoire_sante_texte <> t_territoires_sante.texte)
	;

	UPDATE base.t_codes_postaux
	SET
		territoire_sante_id = t_territoires_sante.oid,
		territoire_sante_code = t_territoires_sante.code,
		territoire_sante_texte = t_territoires_sante.texte
	FROM 
		base.t_territoires_sante
		JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
		JOIN base.t_departements ON t_departements.region_id = t_regions.oid
	WHERE 
		t_codes_postaux.code = t_codes_postaux.texte
		AND t_departements.code = substr(t_codes_postaux.code, 1 , 3)
		AND substr(t_codes_postaux.code, 1 , 2) IN ('97', '98')
		AND (	territoire_sante_id <> t_territoires_sante.oid OR
			territoire_sante_code <> t_territoires_sante.code OR
			territoire_sante_texte <> t_territoires_sante.texte)
	; ";
	$toResult = execute_sql($sqlcmd);
	
	$sqlcmd = "
	UPDATE base.t_codes_geographiques_pmsi
	SET
		departement_id = t_departements.oid,
		departement_code = t_departements.code,
		departement_texte = t_departements.texte
	FROM base.t_departements
	WHERE 
		departement_id is null or departement_id = 0
		AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 2)
		AND substr(t_codes_geographiques_pmsi.code, 1 , 2) NOT IN ('97', '98')
		AND (
			departement_id <> t_departements.oid OR
			departement_code <> t_departements.code OR
			departement_texte <> t_departements.texte)
	;

	UPDATE base.t_codes_geographiques_pmsi
	SET
		departement_id = t_departements.oid,
		departement_code = t_departements.code,
		departement_texte = t_departements.texte
	FROM base.t_departements
	WHERE 
		departement_id is null or departement_id = 0
		AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 3)
		AND substr(t_codes_geographiques_pmsi.code, 1 , 2) IN ('97', '98')
		AND (
			departement_id <> t_departements.oid OR
			departement_code <> t_departements.code OR
			departement_texte <> t_departements.texte)
	;

	UPDATE base.t_codes_geographiques_pmsi
	SET
		territoire_sante_id = t_territoires_sante.oid,
		territoire_sante_code = t_territoires_sante.code,
		territoire_sante_texte = t_territoires_sante.texte
	FROM 
		base.t_territoires_sante
		JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
		JOIN base.t_departements ON t_departements.region_id = t_regions.oid
	WHERE 
		territoire_sante_id is null or territoire_sante_id = 0
		AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 2)
		AND substr(t_codes_geographiques_pmsi.code, 1 , 2) NOT IN ('97', '98')
		AND (	territoire_sante_id <> t_territoires_sante.oid OR
			territoire_sante_code <> t_territoires_sante.code OR
			territoire_sante_texte <> t_territoires_sante.texte)
	;

	UPDATE base.t_codes_geographiques_pmsi
	SET
		territoire_sante_id = t_territoires_sante.oid,
		territoire_sante_code = t_territoires_sante.code,
		territoire_sante_texte = t_territoires_sante.texte
	FROM 
		base.t_territoires_sante
		JOIN base.t_regions ON t_regions.code || '*****' = t_territoires_sante.code
		JOIN base.t_departements ON t_departements.region_id = t_regions.oid
	WHERE 
		territoire_sante_id is null or territoire_sante_id = 0
		AND t_departements.code = substr(t_codes_geographiques_pmsi.code, 1 , 3)
		AND substr(t_codes_geographiques_pmsi.code, 1 , 2) IN ('97', '98')
		AND (	territoire_sante_id <> t_territoires_sante.oid OR
			territoire_sante_code <> t_territoires_sante.code OR
			territoire_sante_texte <> t_territoires_sante.texte)
	; ";
	$toResult = execute_sql($sqlcmd);
	
	logInfoMsg("Initialisation patients");
	
	$sqlcmd = "UPDATE pmsi.p_identites SET prenom = '' WHERE prenom is null";
	$toResult = execute_sql($sqlcmd);
	
	
	// Lien activite / pmsi
	if (file_exists("../../activite/settings.xml")) {
	
		// Créer une table d'association dans activité
		$sqlcmd = "SELECT activite.cti_reorganize_sejour_pmsi()";
		$toResult = execute_sql($sqlcmd);
		
		// Récupérer les noms activité vers le PMSI
		$sqlcmd = "UPDATE pmsi.p_identites
			SET 
				nom = p_patients.nom,
				nom_naissance = p_patients.nom_naissance,
				prenom = p_patients.prenom
			FROM pmsi.p_rss,
				activite.p_sejour_pmsi
				JOIN activite.p_sejours ON p_sejour_pmsi.no_sejour = p_sejours.no_sejour
				JOIN activite.p_patients ON p_sejours.no_patient = p_patients.no_patient
			WHERE p_rss.oid = p_identites.rss_id AND
				p_identites.nom LIKE 'RSS %' AND
				p_sejour_pmsi.pmsi_type = 'MCO' AND
				p_sejour_pmsi.rss_id = p_rss.oid;";
		$toResult = execute_sql($sqlcmd);
	}
	
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET patient_id = 0 FROM  
		pmsi.p_identites, pmsi.p_patients  
		WHERE p_rss.oid = p_identites.rss_id  
		AND p_patients.oid = p_rss.patient_id 
		AND p_rss.patient_id <> 0  
		AND (upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) || '|' ||  p_rss.date_naissance::text || '|' ||  p_rss.sexe::text)   
		<> (upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) || '|' ||  p_patients.date_naissance::text || '|' ||  p_patients.sexe::text) ";
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "DROP TABLE IF EXISTS temp_pmsi_identites ;";
	$toResult = execute_sql($sqlcmd);
	

	$sqlcmd = "CREATE TEMP TABLE temp_pmsi_identites (finess character(9), nom character varying(255), prenom character varying(255), nomprenom character varying(255), date_naissance date, sexe character(1));";
	$toResult = execute_sql($sqlcmd);
	

	$sqlcmd = "INSERT INTO temp_pmsi_identites(finess, nom, prenom, nomprenom, date_naissance, sexe)
		SELECT DISTINCT p_rss.finess, p_identites.nom, p_identites.prenom, upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) AS nomprenom, p_rss.date_naissance, p_rss.sexe
		FROM pmsi.p_rss, pmsi.p_identites 
		WHERE p_rss.oid = p_identites.rss_id AND (p_rss.patient_id IS NULL OR p_rss.patient_id = 0);";
	$toResult = execute_sql($sqlcmd);
	


	$sqlcmd = "INSERT INTO pmsi.p_patients (finess, nom, prenom, date_naissance, sexe)
	SELECT temp_pmsi_identites.finess, temp_pmsi_identites.nom, temp_pmsi_identites.prenom, temp_pmsi_identites.date_naissance, temp_pmsi_identites.sexe FROM temp_pmsi_identites 
	LEFT JOIN pmsi.p_patients ON (
		temp_pmsi_identites.nomprenom = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))
		AND temp_pmsi_identites.date_naissance = p_patients.date_naissance
		AND temp_pmsi_identites.sexe = p_patients.sexe)
	WHERE p_patients.nom IS NULL";
	$toResult = execute_sql($sqlcmd);
	

	$sqlcmd = "UPDATE pmsi.p_patients SET no_patient = 0 - nextval('pmsi.s_no_interne_patients'::regclass) WHERE no_patient = 0 OR no_patient IS NULL; ";
	$toResult = execute_sql($sqlcmd);
	
	$sqlcmd = "UPDATE pmsi.p_patients SET no_patient = p_rss.no_patient FROM pmsi.p_rss WHERE p_rss.patient_id = p_patients.oid AND p_patients.no_patient < 0 AND p_rss.no_patient > 0 ;";
	$toResult = execute_sql($sqlcmd);	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET patient_id = p_patients.oid  
		FROM pmsi.p_identites, pmsi.p_patients  
		WHERE p_rss.oid = p_identites.rss_id 
		AND COALESCE(p_rss.patient_id,0) = 0 
		AND p_rss.date_naissance = p_patients.date_naissance 
		AND p_rss.sexe = p_patients.sexe 
		AND upper(translate(p_identites.nom || p_identites.prenom, ' -', '')) = upper(translate(p_patients.nom || p_patients.prenom, ' -', ''))  ";
	
	$toResult = execute_sql($sqlcmd);
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET patient_id = subview.new_id FROM  
			( 
			SELECT  
			p_patients.oid AS old_id,  
			p_patients_nouveaux.oid as new_id  
			FROM pmsi.p_patients, pmsi.p_patients p_patients_nouveaux  
			WHERE p_patients.oid < p_patients_nouveaux.oid 
			AND upper(translate(p_patients.nom || p_patients.prenom, ' -', '')) = upper(translate(p_patients_nouveaux.nom || p_patients_nouveaux.prenom, ' -', '')) 
			AND p_patients.date_naissance = p_patients_nouveaux.date_naissance 
			AND p_patients.sexe = p_patients_nouveaux.sexe 
			) subview  
			WHERE p_rss.patient_id = subview.old_id ";
	
	$toResult = execute_sql($sqlcmd);
	
	$toResult = execute_sql($sqlcmd);
	
	
	$sqlcmd = "DELETE FROM pmsi.p_patients WHERE oid NOT IN (SELECT DISTINCT patient_id FROM pmsi.p_rss)";
	$toResult = execute_sql($sqlcmd);
	
	
	$sqlcmd = "UPDATE pmsi.p_patients SET no_patient = subview.no_patient 
		FROM (SELECT patient_id, MAX(no_patient) as no_patient FROM pmsi.p_rss WHERE no_patient > 0 GROUP BY patient_id) subview
		WHERE p_patients.oid = subview.patient_id AND p_patients.no_patient <> subview.no_patient";
	$toResult = execute_sql($sqlcmd);
	
	logInfoMsg("Sejours avec anesthesie");
	
	$sqlcmd = "
		UPDATE pmsi.p_rss set 
			avec_anesthesie = '1'
		FROM
		(
			SELECT
				rss_id
			FROM
				pmsi.p_rss_actes
			WHERE
				activite_ccam = '4'
			GROUP BY rss_id
		) subview
		WHERE 1=1
			AND subview.rss_id = p_rss.oid 
			AND p_rss.en_cours = '1'
			AND avec_anesthesie IS DISTINCT FROM '1'";
	$toResult = execute_sql($sqlcmd);
	
	logInfoMsg("Actes avec anesthesie");
	// trouve les actes d'activité 1 qui ont un acte d'activité 4 associé
	$sqlcmd = "
		WITH w_update AS (
			SELECT
				p_rss_actes.rss_id,
				p_rss_actes.acte_id,
				p_rss_actes.date_acte,
				p_rss_actes.association_nonprevue_ccam
			FROM
				pmsi.p_rss_actes 
			WHERE
				p_rss_actes.activite_ccam in ('1', '4')
			GROUP BY 1 ,2, 3, 4
			HAVING count(DISTINCT p_rss_actes.activite_ccam) > 1
		)
		UPDATE pmsi.p_rss_actes SET
			acte_avec_anesthesie = 1
		FROM
			w_update
		WHERE 1=1
			AND p_rss_actes.activite_ccam = '1'
			AND w_update.rss_id = p_rss_actes.rss_id 
			AND w_update.acte_id = p_rss_actes.acte_id
			AND w_update.date_acte = p_rss_actes.date_acte
			AND w_update.association_nonprevue_ccam = p_rss_actes.association_nonprevue_ccam
			AND p_rss_actes.acte_avec_anesthesie IS DISTINCT FROM 1";
	$toResult = execute_sql($sqlcmd);
	
	logInfoMsg("MAJ ccam descriptif actes PMSI");
	$sqlcmd = "
		UPDATE pmsi.p_rss_actes
		SET acte_ccam_descriptif_id = acte_id
		WHERE acte_ccam_descriptif_id IS NULL
		;
		UPDATE pmsi.p_rss_actes
		SET acte_id = racine_id
		FROM pmsi.p_rss,
			pmsi.t_actes
		WHERE rss_id = p_rss.oid AND
			p_rss.en_cours = '1' AND
			acte_ccam_descriptif_id = t_actes.oid AND
			racine_id <> p_rss_actes.acte_id
		;

		";
	$toResult = execute_sql($sqlcmd);

	// Remise a null des sejours sans transfert present dans p_rss_transferts
	rssWithoutTransfertToNull();
	
	logInfoMsg("FIN TRAITEMENTS COMPLEMENTAIRES RUM. $nbE erreurs.");
}

function rssWithoutTransfertToNull(){

	/**
	 * Assigne la valeure null aux sejours presents dans p_rss_transferts
	 * qui n'ont pas soit le mode d'entree soit le mode de sortie en transfert (7 ou 0)
	 */

	$sqlcmd = "
	UPDATE pmsi.p_rss_transferts
		SET etablissement_provenance_id = NULL
	FROM pmsi.p_rss  
	WHERE 
		rss_id = p_rss.oid
		AND mode_entree not in (7,0)
		AND etablissement_provenance_id IS NOT NULL;


	UPDATE pmsi.p_rss_transferts
		SET etablissement_destination_id = NULL
	FROM pmsi.p_rss  
	WHERE 
		rss_id = p_rss.oid
		AND mode_sortie not in (7,0)
		AND etablissement_destination_id IS NOT NULL;
	";

	execute_sql($sqlcmd);
}


function trouver_rum_principal($dateDebutFG12) {
	global $import_id;

	$rss = array();
	$listes = array();

	// Récupération des RSS multi-unités
	$rssSQL = "
		SELECT 
			p_rss.oid AS rss_id,
			p_rss.duree_sejour AS duree_rss,
			p_rss.nb_rum,
			p_rss_rum.no_rum,
			p_rss_rum.duree_sejour AS duree_rum,
			t_diagnostics.code as dp,
			base.cti_array_accum(t_actes.code) AS acte
		FROM pmsi.p_rss
			JOIN pmsi.p_rss_rum ON p_rss_rum.rss_id = p_rss.oid
			LEFT JOIN pmsi.t_diagnostics ON t_diagnostics.oid = p_rss_rum.diagnostic_principal_id
			LEFT JOIN pmsi.p_rss_actes ON p_rss_actes.rss_id = p_rss.oid AND p_rss_actes.no_rum = p_rss_rum.no_rum
			LEFT JOIN pmsi.t_actes ON t_actes.oid = p_rss_actes.acte_id
		WHERE 1=1
		--	AND (p_rss.no_rum_principal = 0 OR p_rss.no_rum_principal IS NULL)
			AND p_rss.nb_rum > 1
			AND p_rss.import_id = $import_id
			AND p_rss.date_sortie >= '$dateDebutFG12'
			AND p_rss.ghm_id > 0
		GROUP BY 1,2,3,4,5,6
		ORDER BY rss_id, no_rum
	";
	$rss = pg_fetch_all(execute_sql($rssSQL));

	if ($rss !== false) {
		// mise en forme des actes RUM
		for ($i = 0; $i < count($rss); $i++) {
			if ($rss[$i]['acte'] == '{NULL}') {
				$rss[$i]['acte'] = array();
			} else {
				$rss[$i]['acte'] = explode(',', str_replace(array('{', '}'), '', $rss[$i]['acte']));
			}
		}

		// Récupération des listes d'actes
		$listeActeSQL = "
		SELECT t_actes.code
		FROM pmsi.t_listes
			JOIN pmsi.t_listes_contenu ON t_listes_contenu.liste_id = t_listes.oid
			JOIN pmsi.t_actes ON t_actes.oid = t_listes_contenu.to_id
		WHERE t_listes.code = '%s'
		";
		// 0.0 : Actes opératoires v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeActeSQL, "CTI_AOP_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_AOP_11C"][] = $value['code'];
			}
		}
		// 23:0: Actes reclassant les RSS dans un GHM médical v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeActeSQL, "CTI_AREC_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_AREC_11C"][] = $value['code'];
			}
		}
		// 38.6 : Actes des GHM avec actes classant non opératoires thérapeutiques v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeActeSQL, "CTI_ACNOPTH_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_ACNOPTH_11C"][] = $value['code'];
			}
		}
		// 39.0 : Actes des GHM avec actes classant non opératoires de moins de 2 jours v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeActeSQL, "CTI_ACNOPM2J_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_ACNOPM2J_11C"][] = $value['code'];
			}
		}
		// 39.1 : Autres actes des GHM avec actes classant non opératoires et opératoires mineurs v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeActeSQL, "CTI_ACNOPM_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_ACNOPM_11C"][] = $value['code'];
			}
		}

		// Récupération des listes de diagnostics
		$listeDiagSQL = "
		SELECT t_diagnostics.code
		FROM pmsi.t_listes
			JOIN pmsi.t_listes_contenu ON t_listes_contenu.liste_id = t_listes.oid
			JOIN pmsi.t_diagnostics ON t_diagnostics.oid = t_listes_contenu.to_id
		WHERE t_listes.code = '%s'
		";
		// 21.6 : Diagnostics imprécis v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeDiagSQL, "CTI_DIMP_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_DIMP_11C"][] = $value['code'];
			}
		}
		// 21.2 : Diagnostics en Z ou de type symptômes (en R) v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeDiagSQL, "CTI_DZR_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_DZR_11C"][] = $value['code'];
			}
		}
		// 21.5 : Diagnostics avec un code S (lésions traumatiques récentes) v11c
		$tmp = array();
		$tmp = pg_fetch_all(execute_sql(sprintf($listeDiagSQL, "CTI_DSLTR_11C")));
		if (is_array($tmp)) {
			foreach ($tmp as $key => $value) {
				$listes["CTI_DSLTR_11C"][] = $value['code'];
			}
		}

		$result = array(); // Associe a rss_id le n° de RUM principal => a updater en BD à la fin
		$tmpRSS = array(); // Un RSS composé de plusieurs RUM
		
		// Pour chaque RSS
		foreach ($rss as $rum) {
			// Si on a déjà associé à un séjour au moins un RUM
			// ET que le RUM qu'on tente d'associer n'appartient pas au même séjour,
			// on re-initialise le séjour à blanc
			if (count($tmpRSS) != 0 && $tmpRSS[0]['rss_id'] != $rum['rss_id']) {
				logInfoMsg("Séjour multi-RUM incomplet (rss_id " . $tmpRSS[0]['rss_id'] . " non traité)");
				$tmpRSS = array();
			}
			
			// Affectation du RUM au séjour à traiter
			$tmpRSS[] = $rum;
			
			if ($rum['no_rum'] == $rum['nb_rum']) {
				// dernier RUM de la séquence
				$result[] = '(' . $rum['rss_id'] . ',' . (findmax_13($tmpRSS, $listes) + 1) . ')';
				$tmpRSS = array();
			}
		}

		// Traiter $result
		if(count($result) > 0){
			$resValues = "";
			$resValues = implode(',' . PHP_EOL, $result);

			$sqlCmd = "
				DROP TABLE IF EXISTS w_result
				;
				
				CREATE TEMP TABLE w_result (
					rss_id bigint,
					no_rum_principal bigint
				)
				;
				
				INSERT INTO w_result
				VALUES
				%s
				;
				
				UPDATE pmsi.p_rss
				SET no_rum_principal = w_result.no_rum_principal
				FROM w_result
				WHERE w_result.rss_id = p_rss.oid
				;
			";

			execute_sql(sprintf($sqlCmd, $resValues));
		}
	}
}

/**
 *
 * Détermination du RUM principal dans les séjours multi-unités (multi-RUM)
 * Basé sur le source de la Fonction Groupage 13 et la classification des GHM v11c.
 *
 */
function findmax_13($rss, $listes) {
	// Initialisations
	$score = $scoreprec = 0;
	$iretenu = 0;
	$iZ515retenu = 0;
	$iSretenu = 0;
	$scoremin = 99999999;
	$dureeZ515 = -1;

	$sansS = 0;
	$dureeS = -1;
	$dureemax = 0;
	$maxrumS = 0;

	$bacte = false;
	$bactetherap = false;
	$bactemoyen = false;
	$bacteclass = false;

	// Pour chaque RUM
	for ($i = 0; $i < count($rss); $i++) {
		$rum = $rss[$i];

		// Initialisations
		$bacte = false;
		$bactetherap = false;
		$bactemoyen = false;
		$bacteclass = false;
		$score = $scoreprec;

		// Pour chaque acte
		for ($j = 0; $j < count($rum['acte']); $j++) {
			$acte = $rum['acte'][$j];
			/* actes opératoires non R */
			/* 0:0 : acte opératoire */
			/* 23:0 : acte mineur */
			if (cti_in_array($acte, $listes['CTI_AOP_11C']) && !cti_in_array($acte, $listes['CTI_AREC_11C'])) {
				$bacte = true;
				break;
			}
			/* 38.6 : Actes des GHM avec actes classant non opératoires thérapeutiques */
			if (cti_in_array($acte, $listes['CTI_ACNOPTH_11C'])) {
				$bactetherap = true;
			}
			/* 39.0 : Actes des GHM avec actes classant non opératoires de moins de 2 jours */
			if (($rum['duree_rum'] <= 1) && cti_in_array($acte, $listes['CTI_ACNOPM2J_11C'])) {
				$bactemoyen = true;
			}
			/* 39.1 : Autres actes des GHM avec actes classant non opératoires et opératoires mineurs */
			if (($rum['duree_rum'] == 0) && cti_in_array($acte, $listes['CTI_ACNOPM_11C'])) {
				$bacteclass = true;
			}
		} // Fin parcours des actes

		if ($bacte) {
			$iretenu = $i;
			break;
		}
		if ($bactetherap) {
			$score -= 999999;
		} else {
			if ($bactemoyen) {
				$score -= 99999;
			} else {
				if ($bacteclass) {
					$score -= 9999;
				}
			}
		}

		// 21.2 Pour le DP
		$dp23rz = false;
		$dp23rz = cti_in_array($rum['dp'], $listes['CTI_DZR_11C']);
		if (($rum['duree_rum'] >= 2) && (!$dp23rz)) {
			$scoreprec += 100;
		}
		if ($dp23rz) {
			$score += 150;
		}
		if ($rum['duree_rum'] == 0) {
			$score += 2;
		}
		if ($rum['duree_rum'] == 1) {
			$score += 1;
		}
		/* 21.6 DP imprécis */
		if (cti_in_array($rum['dp'], $listes['CTI_DIMP_11C'])) {
			$score += 201;
		}

		/* DP Z515 */
		if ((substr($rum['dp'], 0, 4) == "Z515" ||
				substr($rum['dp'], 0, 4) == "Z502" ||
				substr($rum['dp'], 0, 4) == "Z503")
				&& ($rum['duree_rum'] > $dureeZ515)
		) {
			$dureeZ515 = $rum['duree_rum'];
			$iZ515retenu = $i;
		}

		if ($score < $scoremin) {
			$iretenu = $i;
			$scoremin = $score;
		}

		// 21.5 
		if (cti_in_array($rum['dp'], $listes['CTI_DSLTR_11C']) && ($sansS == 0)) {
			$maxrumS = $i;
			if ($rum['duree_rum'] > $dureeS) {
				$dureeS = $rum['duree_rum'];
				$iSretenu = $i;
			}
		} else {
			$sansS = 1;
		}

		if ($rum['duree_rum'] > $dureemax) {
			$dureemax = $rum['duree_rum'];
		}
	} // Fin parcours des RUM

	if (!$bacte) {
		if ($dureeZ515 == $dureemax) {
			$iretenu = $iZ515retenu;
		} else {
			if ($iretenu <= $maxrumS) {
				$iretenu = $iSretenu;
			}
		}
	}

	return $iretenu;
}




function generation_rsf_post_traitements() {

	global $ENV_TYPEETS;
	global $ENV_OPTPMSI_GHSBB;

	global $import_id;

	logInfoMsg("TRAITEMENTS COMPLEMENTAIRES RSF");
	
	
	analyse_tables();
	
	$nbE = 0;
	
	if ($ENV_TYPEETS == ETABLISSEMENT_PRIVE) {
		logInfoMsg("GHS des non facturés");
		
		$sqlcmd = "UPDATE pmsi.p_rss SET ghs_id = (SELECT oid from pmsi.t_ghs WHERE code = 9999)
			WHERE ghs_id = 0 AND ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code IN ('09Z02Z', '14C05Z', '14Z04Z', '23Z03Z', '24Z15Z', '24Z19Z', '28Z05Z', '28Z06Z'));";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		

		$sqlcmd = "UPDATE pmsi.p_rss SET ghs_id = ghs_1_id
			FROM pmsi.t_ghm 
			WHERE ghm_id <> 0 AND ghm_id = t_ghm.oid
			AND p_rss.ghs_id = 0
			AND p_rss.ghm_id <> 0
			AND ghs_1_id <> 0
			AND ghs_2_id = 0 ";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		
		
		$sqlcmd = "UPDATE pmsi.p_rss SET ghs_id = 
			CASE 
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z02Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5800)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z03Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5801)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z04E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5802)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5803)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5804)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5805)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z05D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5806)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5807)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5808)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5809)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z06D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5810)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5811)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5812)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5813)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z07D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5814)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z08E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5815)
				WHEN p_rss.date_sortie < '20090301' AND t_ghm.code = '15Z09E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5817)

				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z02Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5819)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z03Z' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5820)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z04E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5821)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5822)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5823)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5824)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z05D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5825)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5826)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5827)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5828)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z06D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5829)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07A' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5830)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07B' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5831)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07C' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5832)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z07D' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5833)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z08E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5834)
				WHEN p_rss.date_sortie >= '20090301' AND t_ghm.code = '15Z09E' THEN (SELECT oid FROM pmsi.t_ghs WHERE code = 5836)

			ELSE 0 END

			FROM pmsi.t_ghm
			WHERE ghs_id = 0 AND p_rss.ghm_id = t_ghm.oid
			and ghm_id > 0";
		$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
		
	
	}
	
	logInfoMsg("Valorisation non facturés");
	$sqlcmd = "SELECT pmsi.cti_valorisation_non_factures()";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

	
	logInfoMsg("Identification EXB V11");
	
	// mise 
	
	// Attention Softway ne met pas de coeff mco sur exb
	$sqlcmd = "
		UPDATE pmsi.p_rsf_detail SET 
			coefficient_mco = v_coefficient_mco.coefficient_mco_calcul
		FROM pmsi.p_rss, pmsi.t_prestations, base.v_coefficient_mco
		WHERE 1=1
			AND p_rss.oid = p_rsf_detail.rss_id
			AND t_prestations.oid = p_rsf_detail.prestation_id
			AND p_rss.date_sortie BETWEEN v_coefficient_mco.date_debut AND v_coefficient_mco.date_fin
			AND p_rss.en_cours = '1'
			AND p_rsf_detail.coefficient_mco IN (0, 1)
			AND p_rsf_detail.base_remboursement > 0
			AND p_rsf_detail.type = 'B'
			AND p_rsf_detail.est_ligne_rss = '1'
			AND t_prestations.code = ANY (ARRAY(SELECT to_code FROM pmsi.v_listes_contenu_1 WHERE liste_code = 'CTI_GHS_SUP')::text[])
			;"
			;
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );
	
	
	// Mise à jour coefficient calculé
	$sqlcmd = "UPDATE pmsi.p_rsf_detail 
			SET coefficient = round(base_remboursement / prix_unitaire / coefficient_mco / nombre, 5)::numeric(18 , 5)
			WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND prestation_id IN (select oid FROM pmsi.t_prestations WHERE code = 'GHS')  
			AND prix_unitaire > 0 AND nombre > 0 AND coefficient_mco > 0 AND base_remboursement > 0 
			AND round(base_remboursement / prix_unitaire / coefficient_mco / nombre, 1) <  1 
			AND rss_id IN (SELECT oid FROM pmsi.p_rss WHERE import_id = $import_id AND date_sortie >= '20090301')
			AND coefficient <> round(base_remboursement / prix_unitaire / coefficient_mco / nombre, 5)::numeric(18 , 5)";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	
	logInfoMsg("Sous totaux RSF");
	$sqlcmd = "UPDATE pmsi.p_rsf_total SET 
		base_remboursement = subview.base_remboursement 
		FROM pmsi.p_rss, 
		( 
		SELECT rss_id,  
		SUM(base_remboursement) as base_remboursement  
		FROM pmsi.p_rsf_detail WHERE p_rsf_detail.est_ligne_rss = '1' 
		GROUP BY rss_id) subview 
		WHERE p_rsf_total.base_remboursement = 0 AND p_rsf_total.rss_id = p_rss.oid  AND p_rss.import_id = $import_id AND p_rsf_total.rss_id = subview.rss_id ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	
	$sqlcmd = "UPDATE pmsi.p_rsf_total SET 
			t2a_facture = subview.t2a_facture, 
			dmi_facture = subview.dmi_facture, 
			phc_facture = subview.phc_facture, 
			forfait_facture = subview.forfait_facture,
			nb_exh = subview.nb_exh, 
			ca_exh = subview.ca_exh, 
			nb_exb = subview.nb_exb, 
			ca_exb = subview.ca_exb, 
			nb_ghs = subview.nb_ghs, 
			ca_ghs = subview.ca_ghs
			FROM pmsi.p_rss, 
			( 
			SELECT rss_id,  
			SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S1%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as t2a_facture,  
			SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S2%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as dmi_facture,  
			SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S3%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as phc_facture, 
			
			SUM(CASE WHEN t_prestations.code = 'EXH' THEN p_rsf_detail.nombre ELSE 0 END) as nb_exh,  
			SUM(CASE WHEN t_prestations.code = 'EXH' THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exh, 
			SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient > 0 AND coefficient < 1 THEN p_rsf_detail.nombre ELSE 0 END) as nb_exb,  
			SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient > 0 AND coefficient < 1 THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exb, 
			SUM(CASE WHEN t_prestations.code = 'GHS' THEN p_rsf_detail.nombre ELSE 0 END) as nb_ghs,  
			SUM(CASE WHEN t_prestations.code = 'GHS' THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_ghs,
			SUM(CASE WHEN t_prestations.section_code[9] LIKE 'S13%' THEN p_rsf_detail.base_remboursement ELSE 0 END) as forfait_facture 

			FROM pmsi.p_rsf_detail
				JOIN pmsi.t_prestations ON p_rsf_detail.prestation_id =  t_prestations.oid
			WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' 
			GROUP BY rss_id) subview 
			WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id AND p_rsf_total.rss_id = subview.rss_id  ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	

	// Correction EXB
	$sqlcmd = "UPDATE pmsi.p_rsf_total SET 
			nb_exb = subview.nb_exb, 
			ca_exb = subview.ca_exb 
			FROM pmsi.p_rss, 
			( 
			SELECT rss_id,  
			SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient > 0 AND coefficient < 1 THEN p_rsf_detail.nombre ELSE 0 END) as nb_exb,  
			SUM(CASE WHEN t_prestations.code = 'GHS' AND coefficient > 0 AND coefficient < 1 THEN p_rsf_detail.base_remboursement ELSE 0 END) as ca_exb 
			FROM pmsi.p_rsf_detail, pmsi.t_prestations
			WHERE p_rsf_detail.prestation_id =  t_prestations.oid  AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' 
			GROUP BY rss_id) subview 
			WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id AND p_rsf_total.rss_id = subview.rss_id 
			AND p_rsf_total.rss_id IN (SELECT rss_id FROM pmsi.p_rsf_detail, pmsi.t_prestations 
			WHERE p_rsf_detail.prestation_id =  t_prestations.oid AND t_prestations.code = 'GHS' AND coefficient > 0 AND coefficient < 1) ";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	// A partir de mars 2015 Sur les GHS 9606 et 9616, si le coeff est différent de 1, il ne s'agit pas d'un EXB mais d'une minoration forfaitaire sur la chimio
	$sqlcmd = "	UPDATE pmsi.p_rsf_total SET 
					nb_exb = 0, 
					ca_exb = 0,
					nb_ghsmin = 1
				FROM 
					pmsi.p_rss 
					JOIN pmsi.t_ghs ON t_ghs.oid = p_rss.ghs_id
				WHERE 1=1
					AND p_rsf_total.rss_id = p_rss.oid 
					AND t_ghs.code IN (9606, 9616)
					AND (p_rsf_total.nb_exb > 0 OR p_rsf_total.ca_exb > 0);";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	// CA Théorique
	$sqlcmd = "UPDATE pmsi.p_rsf_total SET ca_ghs_theorique = subview.ca_ghs_theorique 
			FROM pmsi.p_rss,  
			(  
			SELECT rss_id, SUM(CASE WHEN coefficient >= 1 THEN p_rsf_detail.base_remboursement WHEN coefficient > 0 THEN round(prix_unitaire * nombre * coefficient_mco,2) ELSE 0 END) as ca_ghs_theorique  
			FROM pmsi.p_rsf_detail  
			WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND p_rsf_detail.prestation_id IN (SELECT oid FROM pmsi.t_prestations WHERE code = 'GHS')  
			GROUP BY rss_id  
			) subview  
			WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id AND p_rsf_total.rss_id = subview.rss_id AND p_rsf_total.ca_ghs_theorique <> subview.ca_ghs_theorique ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	$sqlcmd = "UPDATE pmsi.p_rsf_total 
			SET ca_ghs_theorique = p_rsf_total.ca_ghs  
			FROM pmsi.p_rss  
			WHERE p_rsf_total.rss_id = p_rss.oid AND p_rss.import_id = $import_id 
				AND ((p_rsf_total.ca_ghs_theorique = 0 AND p_rsf_total.ca_ghs <> 0) OR p_rsf_total.ca_ghs_theorique IS NULL); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	/* christophe */
	// RSS Id de la mère
	logInfoMsg("Recherche des ID RSS De la mère pours les bébés");
	$sqlcmd = "DROP TABLE IF EXISTS w_mere;
			CREATE TEMP TABLE w_mere AS 
					SELECT 
						p_rsf_total.no_rss AS no_rss_mere,
						p_rsf_total.rss_id AS rss_mere_id,
						p_rsf_total_bb.no_rss AS no_rss_bb,
						p_rsf_total_bb.rss_id AS rss_bb_id,
						lpad(p_rsf_total.no_facture, 9, '0') as no_facture
					FROM pmsi.p_rsf_total
						JOIN pmsi.p_rss ON p_rsf_total.rss_id = p_rss.oid
						JOIN pmsi.t_ghm ON p_rss.ghm_id = t_ghm.oid
						JOIN pmsi.p_rsf_total p_rsf_total_bb ON lpad(p_rsf_total.no_facture, 9, '0') = p_rsf_total_bb.no_facture_sejour_mere
						JOIN pmsi.p_rss p_rss_bb ON p_rsf_total_bb.rss_id = p_rss_bb.oid
						JOIN pmsi.t_ghm t_ghm_bb ON p_rss_bb.ghm_id = t_ghm_bb.oid AND t_ghm_bb.code LIKE '15%' 
					WHERE t_ghm.code LIKE '14%' AND p_rsf_total.no_facture <> '' AND p_rsf_total.no_facture <> '0' AND p_rsf_total.no_facture <> '000000000' AND
						p_rss_bb.date_entree BETWEEN p_rss.date_entree AND p_rss.date_sortie;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	$sqlcmd = "UPDATE pmsi.p_rss 
				SET rss_mere_id = w_mere.rss_mere_id
				FROM w_mere
				WHERE p_rss.oid = w_mere.rss_bb_id AND
					p_rss.rss_mere_id IS DISTINCT FROM w_mere.rss_mere_id;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	

	logInfoMsg("Réaffecation des GHS");
	
	// On ne remonte pas tout le temps le détail des factures depuis les prestataires
	// Dans certains le GHS est présent dans p_rss mais pas dans p_rsf_detail (ghs_id =0)
	// On récupère alors le ghs depuis p_rss mais on exclue le cas des mère et bébé (CMD 14 et 15)
	// Car la mère possède les 2 GHS si on ne les a pas réaffecté séparement
	// On le fait à l'étape suivante
	
	// A faire : Voir pour modifier la mere aussi et laisser le bebe tel quel

	$sqlcmd = "
		DROP TABLE IF EXISTS w_rsf_detail_sans_ghs;
			
		CREATE TEMP TABLE w_rsf_detail_sans_ghs AS (
		SELECT p_rsf_detail.ctid AS  ctid_to_change, t_ghs.oid As ghs_id_to_keep
		FROM pmsi.p_rsf_detail
			JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id
			JOIN pmsi.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
			JOIN pmsi.t_prestations ON p_rsf_detail.prestation_id = t_prestations.oid
			JOIN pmsi.t_ghs ON t_ghs.oid = p_rss.ghs_id
			JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
		WHERE t_prestations.code = 'GHS'
			AND en_cours = '1'
			AND p_rsf_detail.ghs_id = 0
			AND t_ghm.code NOT LIKE '14%' 
			AND t_ghm.code NOT LIKE '15%'  
		);
		
		UPDATE pmsi.p_rsf_detail
		SET ghs_id = ghs_id_to_keep
		FROM w_rsf_detail_sans_ghs 
		WHERE p_rsf_detail.ctid = ctid_to_change
	;";
	
	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );

	
	logInfoMsg("Réaffecation des GHS pour CMD 14 ET 15");
	
	// Pour les CMD 14 et 15 on se base sur les tarifs des GHS pour les réaffecter
	// Si 2 GHS ont le même tarifs on les exclu (dans w_id_to_change)
	// Certaine lignes de p_rsf_detail auront des ghs_id à 0

	//On utilise les tariifs de base.t_ghs_tarifs (plus simple à utiliser) mais les id du schéma pmsi
	
	$sqlcmd = "DROP TABLE IF EXISTS w_ghs;
		CREATE TEMP TABLE w_ghs AS (
			SELECT t_ghs.code ghs_code,
				t_ghs.oid as ghs_id_ok
			FROM pmsi.t_ghs
				JOIN pmsi.t_ghm ON t_ghs.ghm_id = t_ghm.oid
			WHERE t_ghm.code LIKE '15%'
				OR t_ghm.code LIKE '14%'
		);
		DROP TABLE IF EXISTS w_ghs_tarifs_cmd_14_15;
		CREATE TEMP TABLE w_ghs_tarifs_cmd_14_15 AS (
			SELECT ghs_id_ok,
				t_ghs.code,
				date_debut,
				date_fin,
				tarif_ghs,
				secteur,
				CASE
					WHEN secteur = 1 THEN 'PUBLIC'
					ELSE 'PRIVE'
				END AS secteur_name
			FROM base.t_ghs_tarifs
				JOIN base.t_ghs ON t_ghs_tarifs.ghs_id = t_ghs.oid
				JOIN w_ghs ON t_ghs.code = w_ghs.ghs_code
			WHERE date_debut > (CURRENT_DATE - INTERVAL '2 year')::date
			GROUP BY 1,
				2,
				3,
				4,
				5,
				6
			ORDER BY CODE,
				date_debut,
				secteur
		);
		
		DROP TABLE IF EXISTS w_rsf_detail_mere_bebe_sans_ghs;
		CREATE TEMP TABLE w_rsf_detail_mere_bebe_sans_ghs AS (
			SELECT p_rsf_detail.ctid as ctid_detail_to_change,
				round(
					p_rsf_detail.base_remboursement / p_rsf_detail.coefficient_mco,
					2
				) AS ghs_brut,
				p_rss.date_sortie --p_rsf_detail.ctid AS  ctid_to_change, t_ghs.oid As ghs_id_to_keep
			FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id
				JOIN pmsi.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
				JOIN pmsi.t_prestations ON p_rsf_detail.prestation_id = t_prestations.oid
				JOIN pmsi.t_ghs ON t_ghs.oid = p_rss.ghs_id
				JOIN pmsi.t_ghm ON t_ghm.oid = p_rss.ghm_id
			WHERE t_prestations.code = 'GHS'
				AND en_cours = '1'
				AND p_rsf_detail.ghs_id = 0
				AND (t_ghm.code LIKE '14%' OR t_ghm.code LIKE '15%')
			order by p_rss.oid
		);
		WITH w_id_to_change AS(
			SELECT ctid_detail_to_change,
				MAX(ghs_id_ok) AS ghs_id_to_keep
			FROM w_ghs_tarifs_cmd_14_15,
				base.t_finess,
				w_rsf_detail_mere_bebe_sans_ghs
			WHERE w_rsf_detail_mere_bebe_sans_ghs.ghs_brut = w_ghs_tarifs_cmd_14_15.tarif_ghs
				AND date_sortie BETWEEN date_debut AND date_fin
				AND CASE
					WHEN t_finess.type_etablissement = ANY (ARRAY ['2'::text, '3'::text]) THEN secteur_name LIKE 'PUBLIC'
					ELSE secteur_name LIKE 'PRIVE'
				END
			GROUP by 1
			HAVING count(*) = 1
		)
		UPDATE pmsi.p_rsf_detail
			SET ghs_id = ghs_id_to_keep
			FROM w_id_to_change
			WHERE p_rsf_detail.ctid = ctid_detail_to_change;
	";

	$toResult = execute_sql($sqlcmd, $nbE, $nbW_rum );	


	// Reprise des cumuls dans p_rss
	logInfoMsg("Report des cumuls RSS");
	$sqlcmd = "UPDATE pmsi.p_rss 
			SET base_remboursement = p_rsf_total.base_remboursement, 
				sejour_facture = p_rsf_total.sejour_facture, 
				honoraires_factures = p_rsf_total.honoraires_factures, 
				t2a_facture = p_rsf_total.t2a_facture, 
				dmi_facture = p_rsf_total.dmi_facture, 
				phc_facture = p_rsf_total.phc_facture, 
				ca_ghs_theorique = p_rsf_total.ca_ghs_theorique, 
				nb_ghs = p_rsf_total.nb_ghs, 
				ca_ghs = p_rsf_total.ca_ghs, 
				nb_exb = p_rsf_total.nb_exb, 
				ca_exb = p_rsf_total.ca_exb, 
				nb_exh = p_rsf_total.nb_exh, 
				ca_exh = p_rsf_total.ca_exh,
				forfait_facture = p_rsf_total.forfait_facture,
                nb_ghsmin = p_rsf_total.nb_ghsmin                 
			FROM pmsi.p_rsf_total 
			WHERE p_rss.oid = p_rsf_total.rss_id AND 
				p_rss.import_id = $import_id;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	logInfoMsg("Assurance");
	$sqlcmd = "UPDATE pmsi.p_rss 
				SET traitement_epmsi = 
					CASE 
					WHEN p_rss.en_cours LIKE '1' THEN '00'
					WHEN p_rss.ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code LIKE '90%' AND CODE <> '90H02Z' AND CODE <> '90H03Z')  THEN '11'
					WHEN p_rss.mode_entree = '0' AND p_rss.mode_sortie = '0'  THEN '12'
					WHEN p_rss.ghs_id IN (SELECT oid FROM pmsi.t_ghs WHERE code = 9999) THEN '13'

					WHEN t_finess.type_etablissement IN ('2', '3') AND subview.nb_vidhosp > 0 AND p_rss.ghm_id > 0 AND p_rss.oid NOT IN (SELECT rss_id FROM pmsi.p_vidhosp) THEN '21' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '1' THEN '21' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '2' THEN '22' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('3') THEN '23' 
					WHEN t_finess.type_etablissement NOT IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('2', '3', '4') THEN '24'
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '3' THEN '24' 					
					WHEN t_finess.type_etablissement IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('0') THEN '24' 
					ELSE '30' END
				FROM pmsi.p_rsf_total, base.t_finess, pmsi.p_rss p_rss_bis 
					LEFT JOIN
								(SELECT w_rss.mois_sortie, count(*) AS nb_vidhosp 
								FROM pmsi.p_rss w_rss, pmsi.p_vidhosp w_vidhosp
								WHERE w_rss.oid = w_vidhosp.rss_id
								GROUP BY w_rss.mois_sortie) subview
								ON p_rss_bis.mois_sortie = subview.mois_sortie
					LEFT JOIN pmsi.p_ctl_mt2a ON (p_rss_bis.oid = p_ctl_mt2a.rss_id)
				WHERE p_rss_bis.oid = p_rss.oid 
				AND p_rss.import_id = $import_id
				AND p_rsf_total.rss_id = p_rss.oid 
				AND t_finess.code = p_rss.finess
				AND (p_rss.traitement_epmsi <>  
					CASE 
					WHEN p_rss.en_cours LIKE '1' THEN '00'
					WHEN p_rss.ghm_id IN (SELECT oid FROM pmsi.t_ghm WHERE code LIKE '90%' AND CODE <> '90H02Z' AND CODE <> '90H03Z')  THEN '11'
					WHEN p_rss.mode_entree = '0' AND p_rss.mode_sortie = '0'  THEN '12'
					WHEN p_rss.ghs_id IN (SELECT oid FROM pmsi.t_ghs WHERE code = 9999) THEN '13'

					WHEN t_finess.type_etablissement IN ('2', '3') AND subview.nb_vidhosp > 0 AND p_rss.ghm_id > 0 AND p_rss.oid NOT IN (SELECT rss_id FROM pmsi.p_vidhosp) THEN '21' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '1' THEN '21' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '2' THEN '22' 
					WHEN t_finess.type_etablissement IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('3') THEN '23' 
					WHEN t_finess.type_etablissement NOT IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('2', '3', '4') THEN '24'
					WHEN t_finess.type_etablissement IN ('2', '3') AND p_ctl_mt2a.erreur_genrsa = '3' THEN '24' 					
					WHEN t_finess.type_etablissement IN ('2', '3') AND trim(p_rsf_total.code_pec) IN ('0') THEN '24' 
					ELSE '30' END OR p_rss.traitement_epmsi IS NULL)";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET traitement_epmsi = '0' WHERE traitement_epmsi IS NULL;";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	logInfoMsg("Initialisation Acte principal RSS");
	
    $sqlcmd = "UPDATE pmsi.p_rss SET acte_principal_id = COALESCE(subview.acte_principal_1_id, acte_principal_4_id, 0) FROM 
            (SELECT rss_id,  
                (MAX(ARRAY[CASE WHEN activite_ccam = '1' THEN CASE WHEN type_etablissement IN ('2','3') THEN t_actes_c.icr_public_atih_1 ELSE t_actes_c.icr_prive_atih_1 END ELSE 0 END, acte_id]))[2] as acte_principal_1_id ,
                (MAX(ARRAY[CASE WHEN activite_ccam = '4' THEN CASE WHEN type_etablissement IN ('2','3') THEN t_actes_c.icr_public_atih_4 ELSE t_actes_c.icr_prive_atih_4 END ELSE 0 END, acte_id]))[2] as acte_principal_4_id 
            FROM pmsi.p_rss_actes
            JOIN pmsi.t_actes_c ON p_rss_actes.acte_id = t_actes_c.oid
            LEFT JOIN base.t_finess ON p_rss_actes.finess = t_finess.code
            WHERE activite_ccam <> '5' GROUP BY rss_id) subview 
            WHERE p_rss.oid = subview.rss_id AND (p_rss.acte_principal_id = 0 or p_rss.acte_principal_id IS NULL) and p_rss.en_cours = '1'";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET acte_principal_id = 0 WHERE acte_principal_id IS NULL ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	logInfoMsg("Initialisation Prestation principale RSS");
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code = 'GHS'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code IN ('D09', 'D11'); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code = 'EXH'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id  ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'ATU', 'FFM', 'AP2', 'APE', 'FPI'); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id  ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code IN ('MAR'); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = t_prestations.oid ";
	$sqlcmd = $sqlcmd . "FROM pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE ghm_id > 0 ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) ";
	$sqlcmd = $sqlcmd . "AND t_prestations.code = 'GHS' AND p_rss.oid NOT IN (SELECT DISTINCT rss_id FROM pmsi.p_rsf_detail WHERE p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1'); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code = 'PJ'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id ";
	$sqlcmd = $sqlcmd . "FROM pmsi.p_rsf_detail, pmsi.t_prestations  ";
	$sqlcmd = $sqlcmd . "WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  ";
	$sqlcmd = $sqlcmd . "AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code = 'PJ'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = p_rsf_detail.prestation_id 
				FROM pmsi.p_rsf_detail, pmsi.t_prestations  
				WHERE p_rsf_detail.rss_id = p_rss.oid AND p_rsf_detail.prestation_id = t_prestations.oid  
				AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1' AND t_prestations.code = 'PJ'; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = to_number(subview.prestation_id, '9999999')
				FROM (SELECT rss_id, substr(MAX(to_char(p_rsf_detail.base_remboursement, '000000.00') || prestation_id::text), 11, 10) as prestation_id
					FROM pmsi.p_rss, pmsi.p_rsf_detail
					WHERE p_rss.oid = p_rsf_detail.rss_id
					AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) 
					AND p_rsf_detail.type = 'B' AND p_rsf_detail.est_ligne_rss = '1'
					GROUP BY rss_id) subview
				WHERE subview.rss_id = p_rss.oid 
				AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) 
				AND subview.prestation_id IS NOT NULL";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = to_number(subview.prestation_id, '9999999')
				FROM (SELECT rss_id, substr(MAX(to_char(p_rsf_detail.base_remboursement, '000000.00') || prestation_id::text), 11, 10) as prestation_id
					FROM pmsi.p_rss, pmsi.p_rsf_detail
					WHERE p_rss.oid = p_rsf_detail.rss_id
					AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) 
					AND p_rsf_detail.type = 'C' AND p_rsf_detail.est_ligne_rss = '1'
					GROUP BY rss_id) subview
				WHERE subview.rss_id = p_rss.oid 
				AND (p_rss.prestation_principale_id = 0 OR p_rss.prestation_principale_id IS NULL) 
				AND subview.prestation_id IS NOT NULL";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	// Si une seule prestation pour un acte principal 
	$sqlcmd = "UPDATE pmsi.p_rss
			SET prestation_principale_id = subview.prestation_principale_id
			FROM 
			(SELECT acte_principal_id, MAX(prestation_principale_id) AS prestation_principale_id
			FROM pmsi.v_rss_1
			WHERE ghm_id = 0 AND acte_principal_id <> 0 AND prestation_principale_id <> 0
			GROUP BY 1
			HAVING count(distinct prestation_principale_code) = 1) subview
			WHERE  ghm_id = 0 AND en_cours <> '0' AND p_rss.date_sortie = p_rss.date_entree AND p_rss.acte_principal_id <> 0 AND p_rss.prestation_principale_id = 0 AND
				p_rss.acte_principal_id = subview.acte_principal_id";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	

	$sqlcmd = "UPDATE pmsi.p_rss SET prestation_principale_id = 0 WHERE prestation_principale_id IS NULL ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );	
	
	
	
	logInfoMsg("Ventilation par unité médicale");
	
	// La séquence SQL est remplacée par une fonction
	
	$sqlcmd = "SELECT pmsi.cti_ventilation_ca_um()";
	$toResult = execute_sql($sqlcmd);
	
	$sqlcmd = "SELECT base.cti_vacuum_table('pmsi', 'p_rsf_detail');";
	$toResult = execute_sql($sqlcmd);
	
	
	$sqlcmd = "UPDATE pmsi.p_rsf_total
				SET taux_remboursement = subview.taux_remboursement
				FROM
					(SELECT p_rss.oid AS rss_id, subview.taux_remboursement
					FROM pmsi.p_rss
						LEFT JOIN pmsi.p_vidhosp ON p_rss.oid = p_vidhosp.rss_id
						JOIN pmsi.p_rsf_total on p_rss.oid = p_rsf_total.rss_id and en_cours = '0'
						JOIN
						(
							SELECT rss_id, max(taux_remboursement) AS taux_remboursement
							FROM pmsi.p_rsf_detail
							GROUP BY 1
						) subview ON p_rsf_total.rss_id = subview.rss_id
					WHERE p_rss.en_cours <> '0' AND p_rsf_total.taux_remboursement <> subview.taux_remboursement AND subview.taux_remboursement <> 0 AND p_vidhosp.rss_id IS NULL
				) subview 
				WHERE p_rsf_total.rss_id = subview.rss_id;";
	$toResult = execute_sql($sqlcmd);
	
	// Création des factures inexistantes
	$sqlcmd = "	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,
					forfait_facture,
					nb_exh, ca_exh, nb_exb, ca_exb, nb_ghs, ca_ghs, taux_remboursement, regime_id, exoneration_tm_id, nature_pec_id, code_pec_id, rss_id)
				SELECT
					finess, no_rss, '1', '', '01', '10', '', '', '', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, oid
				FROM pmsi.p_rss
				WHERE 
					import_id = $import_id
					AND oid NOT IN (SELECT rss_id FROM pmsi.p_rsf_total)";
	$toResult = execute_sql($sqlcmd);


	logInfoMsg("FIN TRAITEMENTS COMPLEMENTAIRES RSF. $nbE erreurs.");

	
}


function creation_chiffrier() {
	logInfoMsg("CREATION CHIFFRIER MENSUEL");
	
	
	// Chiffrier
	logInfoMsg("Chiffrier mensuel");
	
	$sqlcmd = "TRUNCATE pmsi.p_chiffrier";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	$sqlcmd = "INSERT INTO pmsi.p_chiffrier (finess, mois, nb_rsa, ca_sejour, nb_rsa_champ_ghs, ca_sejour_champ_ghs, nb_rsa_hors_champ_ghs, ca_sejour_hors_champ_ghs, 
			nb_rsa_en_cours_valides_champ_ghs, nb_rsa_en_cours_groupes_champ_ghs, nb_rsa_en_cours_sortis_non_groupes_champ_ghs, nb_rsa_en_cours_presents_champ_ghs, 
			ca_sejour_en_cours_valides_champ_ghs, ca_sejour_en_cours_groupes_champ_ghs, ca_sejour_en_cours_sortis_non_groupes_champ_ghs, ca_sejour_en_cours_presents_champ_ghs) 
			SELECT 
			p_rss.finess,  
			CASE  
			WHEN p_rss.en_cours <> '1' THEN p_rss.mois_sortie 
			WHEN p_rss.en_cours_etat <> 'P' THEN p_rss.mois_sortie	 	
			WHEN p_rss.mois_sortie <> 209912 THEN p_rss.mois_sortie  
			ELSE date_part('year',now()) * 100 + date_part('month',now())  
			END AS mois_sortie, 
			sum(p_rss.nb_rsa),  
			sum(p_rsf_total.base_remboursement),  
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rss.nb_rsa ELSE 0 END),  
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rsf_total.base_remboursement ELSE 0 END),  
			SUM(CASE WHEN t_ghm.mco NOT IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rss.nb_rsa ELSE 0 END),  
			SUM(CASE WHEN t_ghm.mco NOT IN ('M', 'C', 'O') AND p_rss.en_cours <> '1' THEN p_rsf_total.base_remboursement ELSE 0 END) , 
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat IN ('V','F') THEN p_rss.nb_rsa ELSE 0 END), 
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'G' THEN p_rss.nb_rsa ELSE 0 END), 
			SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'S' THEN p_rss.nb_rsa ELSE 0 END), 
			SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'P' THEN p_rss.nb_rsa ELSE 0 END), 
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat IN ('V','F') THEN p_rsf_total.base_remboursement ELSE 0 END), 
			SUM(CASE WHEN t_ghm.mco IN ('M', 'C', 'O') AND p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'G' THEN p_rsf_total.base_remboursement ELSE 0 END), 
			SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'S' THEN p_rsf_total.base_remboursement ELSE 0 END), 
			SUM(CASE WHEN p_rss.en_cours LIKE '1' AND p_rss.en_cours_etat = 'P' THEN p_rsf_total.base_remboursement ELSE 0 END) 
			FROM pmsi.p_rss, pmsi.p_rsf_total, pmsi.t_ghm  
			WHERE p_rss.oid = p_rsf_total.rss_id  
			AND ghm_id = t_ghm.oid AND etat = ''  
			AND (en_cours <> '1'  OR en_cours_etat IN ('S', 'G', 'V', 'F'))  
			GROUP BY 1, 2";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	
	logInfoMsg("FIN CREATION CHIFFRIER MENSUEL. $nbE erreurs.");

}


function set_oids() {

	logInfoMsg("REFERENCEMENT PARAMETRES");
	
	
	$nb = 0;
	$nbW = 0;
	$nbE = 0;
	
	// RAZ
	$sqlcmd = "TRUNCATE pmsi.p_oids ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
    // finess
    $sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT 'finess', t_finess.oid FROM pmsi.p_rss JOIN base.t_finess ON p_rss.finess = t_finess.code GROUP BY 1,2; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
    
	// medecins rss
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_rss', medecin_rss_id FROM pmsi.p_rss WHERE medecin_rss_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_rss')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// medecins actes
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_acte', medecin_id FROM pmsi.p_rss_actes WHERE medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_acte')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	// medecins interventions
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_intervention', medecin_id FROM pmsi.v_rss_actes_1 WHERE acte_regroupement_code IN ('ADC', 'ADO') AND medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_intervention')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// anesthésistes interventions
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'anesthesistes_intervention', medecin_id FROM pmsi.v_rss_actes_1 WHERE acte_regroupement_code = 'ADA' AND medecin_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'anesthesistes_intervention')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	// medecins RUM
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'medecins_rum', medecin_rum_id FROM pmsi.p_rss_rum WHERE medecin_rum_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'medecins_rum')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	//diagnostics
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'diagnostics', diagnostic_id FROM pmsi.p_rss_diagnostics WHERE diagnostic_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'diagnostics'); ";
	$sqlcmd = $sqlcmd . "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'diagnostics', diagnostic_principal_id FROM pmsi.p_rss WHERE diagnostic_principal_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'diagnostics') ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	// actes
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_id FROM pmsi.p_rss_actes WHERE acte_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_ccam_descriptif_id FROM pmsi.p_rss_actes WHERE acte_ccam_descriptif_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW);

	
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'actes', acte_id FROM pmsi.p_rsf_detail_h WHERE acte_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'actes')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// ghm
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ghm', ghm_id FROM pmsi.p_rss WHERE ghm_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ghm')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// prestations
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations', prestation_id FROM pmsi.p_rsf_detail WHERE prestation_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// prestations
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'prestations_p', prestation_principale_id FROM pmsi.p_rss WHERE prestation_principale_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'prestations_p')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	
	// lpp
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'lpp', lpp_id FROM pmsi.p_rss_lpp WHERE lpp_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'lpp')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// ucd
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ucd', ucd_id FROM pmsi.p_rss_ucd WHERE ucd_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ucd')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	// ghs
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'ghs', ghs_id FROM pmsi.p_rsf_detail WHERE ghs_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'ghs')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// departements
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'departement', t_departements.oid FROM base.t_departements, base.t_codes_postaux ";
	$sqlcmd = $sqlcmd . "WHERE t_codes_postaux.departement_id = t_departements.oid  ";
	$sqlcmd = $sqlcmd . "AND t_codes_postaux.oid in (SELECT DISTINCT code_postal_id FROM pmsi.p_rss) ";
	$sqlcmd = $sqlcmd . "AND t_departements.oid NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'departement')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	// codes postaux
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'c_postaux', oid FROM base.t_codes_postaux WHERE code in (SELECT DISTINCT code_postal FROM pmsi.p_rss) AND oid NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'c_postaux')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	// um
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'um', unite_medicale_id FROM pmsi.p_rss_rum WHERE unite_medicale_id NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'um')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	// uf
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'uf', unite_fonctionnelle_id FROM pmsi.p_rss_actes WHERE unite_fonctionnelle_id != ALL (ARRAY(SELECT oid FROM pmsi.p_oids WHERE code_table = 'uf')::bigint[])";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	// durées de séjour
	$sqlcmd = "INSERT INTO pmsi.p_oids (code_table, oid) SELECT DISTINCT 'dursej', duree_sejour FROM pmsi.p_rss WHERE duree_sejour NOT IN (SELECT oid FROM pmsi.p_oids WHERE code_table = 'dursej')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	
	analyse_table("p_oids");
		
	$sqlcmd = "SELECT base.cti_reorganize_codes_postaux_c('pmsi'); ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "SELECT pmsi.cti_reorganize_medecins_c()";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "VACUUM FULL pmsi.t_medecins_c; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "SELECT pmsi.cti_reorganize_ghm_c()";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "VACUUM FULL pmsi.t_ghm_c; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "SELECT pmsi.cti_reorganize_actes_c()";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "VACUUM FULL pmsi.t_actes_c; ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );

	$sqlcmd = "SELECT pmsi.cti_reorganize_durees_sejour_c() ";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	$sqlcmd = "SELECT pmsi.cti_update_schema_classes('*ALL')";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	
	
	$sqlcmd = "SELECT pmsi.cti_gen_ca_ghs_raac()";
	$toResult = execute_sql($sqlcmd, $nbE, $nbW );
	

	logInfoMsg("FIN REFERENCEMENT PARAMETRES. $nbE erreurs.");

}


function clean_bdd() {

	global $ENV_PMSI_DELETE_BEFORE_YEAR;

	// Suppression des vieux séjours si paramètrage 'ENV_PMSI_DELETE_BEFORE_YEAR' présent dans le Settings de l'établissment
	if ($ENV_PMSI_DELETE_BEFORE_YEAR){
		nettoyer_sejours_jusqua($ENV_PMSI_DELETE_BEFORE_YEAR);
	} else {
		nettoyer_sejours();
	}

	vacuum_tables();
}

function vacuum_tables() {

	global $iCTI_connexion;

	logInfoMsg("VACUUM ANALYSE de la base de données");

	// Vaccum des p_tables
	$sqlcmd = "SELECT table_name FROM information_schema.tables 
	WHERE table_schema = 'pmsi'
	AND table_type = 'BASE TABLE'
	AND table_name LIKE 'p_%'
	AND table_name NOT LIKE '%simulation%'";

	$record = $iCTI_connexion->query($sqlcmd);
	if ($record){
		while ($row = pg_fetch_array($record)){
			vacuum_table($row["table_name"]);
		}
	} else {
		logInfoMsg('Erreur de la récupération des p_tables');
	}

	// Vaccum des t_tables
	$t_tables = array("t_medecins","t_expert_controle_rule", "t_rapport_group", "t_rapports");
	foreach($t_tables as $table){
		vacuum_table($table);
	}
}

function analyse_tables() {

	logInfoMsg("Recréation statistiques base de données");

	
	analyse_table("t_medecins");
	analyse_table("p_chiffrier");
	analyse_table("p_identites");
	analyse_table("p_patients");
	analyse_table("p_rss");
	analyse_table("p_rsf_total");
	analyse_table("p_rsf_detail");
	analyse_table("p_rsf_detail_h");
	analyse_table("p_rss_rum");
	analyse_table("p_rss_diagnostics");
	analyse_table("p_rss_actes");
	analyse_table("p_rss_lpp");
	analyse_table("p_oids");
	
	logInfoMsg("Fin Recréation statistiques base de données");
}



function is_default_value_setting($value){
	$default_value = array("0", "");
	return in_array($value, $default_value);
}


/**
 * Sorte d'override de la fonciton native in_array($needle, $haystack) où
 * on controle en plus que $haystack est bien un tableau
 */
function cti_in_array($needle, $haystack) {
	if (is_array($haystack)) {
		return in_array($needle, $haystack);
	}
	else {
		return false;
	}
}


?>
