return: text
lang: plpgsql
src: |
  DECLARE 
  	_nb_services_absence numeric;
  BEGIN
  	-- Ajout de colonnes dans les tables pour compatibilite descendante
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'equivalent_malade_complet') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN equivalent_malade_complet numeric DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_jour_sejour_sorti') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_jour_sejour_sorti integer DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_seances_chimio') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_seances_chimio integer DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_seances_dialyse') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_seances_dialyse integer DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_seances_autre') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_seances_autre integer DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_seances_chimio') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_seances_chimio integer DEFAULT 0;
  	END IF;
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.p_mouvements_sejour' AND
  			column_name = 'nb_deces') THEN
  		ALTER TABLE activite.p_mouvements_sejour ADD COLUMN nb_deces integer DEFAULT 0;
  	END IF;
  
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.t_etages' AND
  			column_name = 'est_urgence') THEN
  		ALTER TABLE activite.t_etages ADD COLUMN est_urgence text DEFAULT '';
  	END IF;
  
  	IF NOT EXISTS (
  		SELECT column_name 
  		FROM information_schema.columns
  		WHERE table_schema || '.' || table_name = 'activite.t_services_facturation' AND
  			column_name = 'mode_calcul_journees') THEN
  		ALTER TABLE activite.t_services_facturation ADD COLUMN mode_calcul_journees text DEFAULT '';
  	END IF;
  	
  	-- Paramétrage
  	-- Par défaut, On ne compte pas le jour de sortie sauf les hospits où DE = DS
  	INSERT INTO activite.t_divers (code, texte, valeur, description, valeur2)
  	SELECT 
  		'OPTADM_DAYOUT'::text, 
  		'Activite : Comptabilisation du jour de sortie'::text, 
  		'0'::text, 
  		'0=JS non inclus sauf DE=DS | 1=JS non inclus | 2=JS inclus'::text,
  		'Jour de sortie non inclus sauf hospitalisés avec DE=DS'::text
  	WHERE 
  		'OPTADM_DAYOUT'::text NOT IN (SELECT code FROM activite.t_divers) ;
  
  	-- Par défaut, l'hospit complète génère un EMC par séjour
  	INSERT INTO activite.t_divers (code, texte, valeur, description, valeur2)
  	SELECT 
  		'EMCHCSSRPSY'::text, 
  		'Mode génération EMC HC SSR ou PSY'::text, 
  		'0'::text, 
  		'0=1 EMC par séjour, 1=1 EMC par semaine'::text,
  		'Jour de sortie non inclus sauf hospitalisés avec DE=DS'::text
  	WHERE 
  		'EMCHCSSRPSY'::text NOT IN (SELECT code FROM activite.t_divers) ;
  
  	-- Par défaut, On conserve les séances en hospit
  	INSERT INTO activite.t_divers (code, texte, valeur, description, valeur2)
  	SELECT 
  		'SEANCEHOSPIT'::text, 
  		'Traitement des séances en hospit'::text, 
  		'1'::text, 
  		'1=Conserver les séances en hospit, 2=Ne conserver que les séances de dialyse, 0=Pas de séance en hospit'::text,
  		''::text
  	WHERE 
  		'SEANCEHOSPIT'::text NOT IN (SELECT code FROM activite.t_divers) ;
  	UPDATE activite.t_divers
  	SET description = '1=Conserver les séances en hospit, 2=Ne conserver que les séances de dialyse, 0=Pas de séance en hospit'
  	WHERE code = 'SEANCEHOSPIT' AND
  		description <> '1=Conserver les séances en hospit, 2=Ne conserver que les séances de dialyse, 0=Pas de séance en hospit'
  	;
  		
  	-- Désactivation index
  	RAISE NOTICE '%' , 'Desactivation index'; 
  	PERFORM base.cti_stash_table_indexes('activite.p_mouvements_sejour');
  	RAISE NOTICE '%' , 'Extraction des mouvements';  
  	DROP TABLE IF EXISTS w_mvt;
  	CREATE TEMP TABLE w_mvt AS SELECT * FROM activite.p_mouvements_sejour;
  
  	CREATE INDEX w_mvt_i1
  	  ON w_mvt
  	  USING btree
  	  (no_sejour);
  
  	
  	CREATE INDEX w_mvt_i2
  	  ON w_mvt
  	  USING btree
  	  (lieu_id);
  
  	
  
  	-- Table des services associéss aux lieux
  	DROP TABLE IF EXISTS w_lieux_etendus;
  	CREATE TEMP TABLE w_lieux_etendus AS
  	SELECT t_lieux.*,
  		t_lits.etage_id,
  		CASE WHEN COALESCE(t_services_facturation.mode_calcul_journees,'') <> '' THEN t_services_facturation.mode_calcul_journees ELSE t_divers_dayout.valeur END AS service_mode_calcul_journees,
  		t_services_facturation.est_absence AS service_est_absence,
  		t_services_facturation.type_sejour AS service_type_sejour,
  		t_services_facturation.type_t2a AS service_type_t2a,
  		t_lits.chambre_particuliere AS lit_chambre_particuliere,
  		t_etages.est_urgence AS etage_est_urgence,
  		t_modes_traitement.code AS mode_traitement_code,
  		t_dmt.code AS dmt_code
  	FROM activite.t_lieux 
  	JOIN activite.t_services_facturation On service_facturation_id = t_services_facturation.oid
  	JOIN activite.t_lits ON lit_id = t_lits.oid
  	JOIN activite.t_etages ON t_lits.etage_id = t_etages.oid
  	JOIN base.t_modes_traitement ON t_modes_traitement.oid = t_services_facturation.mode_traitement_id
  	JOIN base.t_dmt on dmt_id = t_dmt.oid
  	JOIN activite.t_divers t_divers_dayout ON t_divers_dayout.code = 'OPTADM_DAYOUT'
  	; 
  	CREATE INDEX w_lieux_etendus_i1
  	  ON w_lieux_etendus
  	  USING btree
  	  (oid);
  	ANALYSE w_lieux_etendus
  	;
  
  	-- Correction heure sortie dans mouvements
  	UPDATE activite.p_sejours
  	SET heure_sortie = (substr(to_char(heure_sortie,'FM000000'),1,2) || '59' || substr(to_char(heure_sortie,'FM000000'),5,2))::numeric
  	WHERE substr(to_char(heure_sortie,'FM000000'),3,2) > '59'
  	;
  
  	UPDATE activite.p_sejours
  	SET heure_sortie = 240000
  	WHERE heure_sortie > 240000
  	;
  	
  	UPDATE w_mvt p_mouvements_sejour
  	SET heure_fin = p_sejours.heure_sortie
  	FROM activite.p_sejours
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_mouvements_sejour.nb_sorties_directes = 1 AND
  		p_mouvements_sejour.date = p_sejours.date_sortie AND
  		p_mouvements_sejour.heure_fin <> p_sejours.heure_sortie AND
  		p_sejours.code_sorti = '1' AND
  		p_sejours.type_sejour = '1' AND
  		p_sejours.heure_sortie >= p_mouvements_sejour.heure_debut
  		;
  	UPDATE w_mvt p_mouvements_sejour
  	SET heure_fin = p_sejours.heure_sortie
  	FROM activite.p_sejours
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_mouvements_sejour.nb_ambulatoires = 1 AND
  		p_mouvements_sejour.date = p_sejours.date_sortie AND
  		p_mouvements_sejour.heure_fin <> p_sejours.heure_sortie AND
  		p_sejours.code_sorti = '1' AND
  		p_sejours.type_sejour IN ('2') AND
  		p_sejours.heure_sortie >= p_mouvements_sejour.heure_debut
  		;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET heure_fin = p_sejours.heure_sortie
  	FROM activite.p_sejours
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_mouvements_sejour.nb_externes = 1 AND
  		p_mouvements_sejour.date = p_sejours.date_sortie AND
  		p_mouvements_sejour.heure_fin <> p_sejours.heure_sortie AND
  		p_sejours.code_sorti = '1' AND
  		p_sejours.type_sejour IN ('3') AND
  		p_sejours.heure_sortie >= p_mouvements_sejour.heure_debut
  		;
  
  	-- Correction mouvements pour jour de sortie HDJ HM
  	UPDATE w_mvt p_mouvements_sejour
  	SET est_jour_sortie = '1'
  	FROM activite.p_sejours 
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		p_sejours.code_sorti = '1' AND
  		p_sejours.type_sejour = '1' AND
  		p_mouvements_sejour.date = p_sejours.date_sortie AND
  		p_mouvements_sejour.est_jour_sortie <> '1'
  	;
  
  	DROP TABLE IF EXISTS w_correction_hdj;
  	CREATE TEMP TABLE w_correction_hdj AS
  	SELECT 
  		p_mouvements_sejour.no_sejour,
  		p_mouvements_sejour.date,
  		p_mouvements_sejour.heure_debut,
  		p_mouvements_sejour.heure_fin,
  		MAX(p_mouvements_sejour2.heure_debut) AS heure_debut2,
  		(MAX(Array[p_mouvements_sejour2.heure_debut, p_mouvements_sejour2.lieu_id]))[2]::bigint AS lieu_id2
  	FROM w_mvt p_mouvements_sejour
  	JOIN w_mvt  p_mouvements_sejour2 ON 
  		p_mouvements_sejour.no_sejour = p_mouvements_sejour2.no_sejour AND
  		p_mouvements_sejour.date = p_mouvements_sejour2.date AND
  		p_mouvements_sejour.heure_debut > p_mouvements_sejour2.heure_fin
  	WHERE p_mouvements_sejour.est_jour_hospitalisation = '0' AND 
  		p_mouvements_sejour2.est_jour_hospitalisation = '1' AND 
  		p_mouvements_sejour.nb_sorties_directes = 1 AND 
  		p_mouvements_sejour2.nb_sorties_directes = 0
  	GROUP BY 1,2,3,4
  	HAVING (MAX(Array[p_mouvements_sejour2.heure_debut,p_mouvements_sejour2.lieu_id]))[2]::bigint = MAX(p_mouvements_sejour.lieu_id) ;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET est_jour_hospitalisation = '1', est_dernier_mouvement_jour = '1'
  	FROM w_correction_hdj
  	WHERE p_mouvements_sejour.no_sejour = w_correction_hdj.no_sejour AND
  		p_mouvements_sejour.date = w_correction_hdj.date AND
  		p_mouvements_sejour.heure_debut = w_correction_hdj.heure_debut
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET est_dernier_mouvement_jour = '0'
  	FROM w_correction_hdj
  	WHERE p_mouvements_sejour.no_sejour = w_correction_hdj.no_sejour AND
  		p_mouvements_sejour.date = w_correction_hdj.date AND
  		p_mouvements_sejour.heure_debut = w_correction_hdj.heure_debut2 AND
  		est_dernier_mouvement_jour = '1'
  	;
  
  	-- Stockage des décés
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_deces = 1
  	FROM activite.p_sejours
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_sejours.date_sortie = p_mouvements_sejour.date AND
  		p_sejours.heure_sortie = p_mouvements_sejour.heure_fin AND
  		p_sejours.code_sorti = '1' AND
  		p_sejours.mode_sortie = '9'
  	;
  
  	
  
  	-- Traitement des séances qui n'en sont pas (cas du mode generation service = 0sauf5
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances = 0,
  		nb_ambulatoires = 1
  	FROM activite.p_sejours,
  		w_lieux_etendus t_lieux
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		date_entree = date_sortie AND
  		lieu_id = t_lieux.oid AND
  		p_sejours.type_sejour = '5' AND
  		service_type_sejour = '0sauf5'  AND
  		nb_seances <> 0
  	;
  
  	UPDATE activite.p_sejours
  	SET type_sejour = '2'
  	FROM w_lieux_etendus t_lieux
  	WHERE lieu_sortie_id = t_lieux.oid AND
  		date_entree = date_sortie AND
  		p_sejours.type_sejour = '5' AND
  		service_type_sejour = '0sauf5' 
  	;
  
  	-- Normalement, une seule séance par jour
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances = 1
  	WHERE nb_seances > 1;
  
  	
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances = 0
  	FROM
  	(
  	SELECT w_mvt.no_sejour, w_mvt.date, min(w_mvt.heure_debut) AS heure_seance
  	FROM w_mvt
  	JOIN activite.p_sejours ON w_mvt.no_sejour = p_sejours.no_sejour
  	JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
  	WHERE nb_seances > 0 AND 
  		t_ghm.code <> '28Z04Z'
  	GROUP BY 1,2
  	HAVING SUM(nb_seances) > 1
  	) subview
  	WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
  		p_mouvements_sejour.date = subview.date AND
  		p_mouvements_sejour.heure_debut <> heure_seance
  	;
  
  	-- Deux séances de dialyse le même jour, modif selon facturation
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances = 2
  	FROM
  	(
  	SELECT no_sejour, p_factures_lignes_h.date_debut, SUM(nb_prestation)
  	FROM activite.p_factures_lignes_h
  	JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
  	JOIN base.t_actes ON acte_id = t_actes.oid
  	WHERE code_facture = '1' AND t_actes.code LIKE 'JVJF%' AND p_factures_lignes_h.date_debut = p_factures_lignes_h.date_fin
  	GROUP BY 1,2
  	HAVING SUM(nb_prestation) > 1
  	) subview
  	WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
  		p_mouvements_sejour.date = subview.date_debut AND
  		p_mouvements_sejour.nb_seances = 1
  	;
  	
  	-- Correction pour mouvements CEGI qui finissent à 235959 et redémarrent le lendemain à 0h -> Dans ce cas il manque une journée
  	UPDATE w_mvt
  	SET heure_fin = 240000
  	WHERE heure_fin = 235959
  	;
  	-- Recherche date fin journée pour journées avec absence démarrant après midi (dans ce cas la journée doit être imputée)
  	_nb_services_absence = (SELECT count(*) FROM activite.t_services_facturation WHERE est_absence = '1');
  	IF _nb_services_absence > 0 THEN
  		RAISE NOTICE '%' , 'Traitement special absences'; 
  		DROP TABLE IF EXISTS w_absences;
  		CREATE TEMP TABLE w_absences AS
  		SELECT no_sejour, 
  			date,
  			MIN(CASE WHEN service_est_absence <> '1' THEN heure_debut ELSE 999999 END) AS heure_debut_journee,
  			MAX(CASE WHEN service_est_absence <> '1' THEN heure_fin ELSE 0 END) AS heure_fin_journee,
  			MIN(CASE WHEN service_est_absence = '1' THEN heure_debut ELSE 999999 END) AS heure_debut_absence,
  			MAX(CASE WHEN service_est_absence = '1' THEN heure_fin ELSE 0 END) AS heure_fin_absence
  		FROM w_mvt
  		JOIN w_lieux_etendus t_lieux ON lieu_id = t_lieux.oid
  		GROUP BY 1,2
  		HAVING MAX(service_est_absence) = '1' AND
  			MIN(service_est_absence) <> '1' 
  		ORDER BY 1,2;
  		UPDATE w_mvt SET
  			est_premier_mouvement_jour = 
  				CASE
  				WHEN 120000 BETWEEN heure_debut_journee AND heure_fin_journee AND heure_debut = heure_debut_journee THEN '1'
  				WHEN 120000 BETWEEN heure_debut_absence AND heure_fin_absence AND heure_debut = heure_debut_absence THEN '1'
  				ELSE '9' END,
  			est_dernier_mouvement_jour = 
  				CASE
  				WHEN 120000 BETWEEN heure_debut_journee AND heure_fin_journee AND heure_debut = heure_debut_journee THEN '1'
  				WHEN 120000 BETWEEN heure_debut_absence AND heure_fin_absence AND heure_debut = heure_debut_absence THEN '1'
  				ELSE '9' END
  		FROM w_absences
  		WHERE w_absences.no_sejour = w_mvt.no_sejour AND
  			w_absences.date = w_mvt.date ;
  
  		UPDATE w_mvt SET
  			nb_chambres_particulieres = 0,
  			nb_entrees_mutation_service = 0,
  			nb_entrees_mutation_etage = 0,
  			nb_sorties_mutation_service = 0,
  			nb_sorties_mutation_etage = 0
  		FROM w_lieux_etendus t_lieux
  		WHERE lieu_id = t_lieux.oid AND
  			service_est_absence = '1' AND
  			(
  			nb_chambres_particulieres <> 0 OR
  			nb_entrees_mutation_service <> 0 OR
  			nb_entrees_mutation_etage <> 0 OR
  			nb_sorties_mutation_service <> 0 OR
  			nb_sorties_mutation_etage <> 0
  			)
  		;
  
  		-- enlever mutations absences
  		DROP TABLE IF EXISTS w_mvt_for_mutations;
  		CREATE TEMP TABLE w_mvt_for_mutations AS
  		SELECT no_sejour, date, heure_debut,
  			ROW_NUMBER() OVER (PARTITION BY no_sejour
                              ORDER BY no_sejour, date, heure_debut
  							) AS rang_mvt,
  			service_facturation_id, etage_id, unite_fonctionnelle_id, unite_medicale_id,
  			nb_entrees_directes,
  			nb_entrees_mutation_service,
  			nb_entrees_mutation_etage,
  			nb_sorties_directes,
  			nb_sorties_mutation_service,
  			nb_sorties_mutation_etage
  		FROM w_mvt p_mouvements_sejour
  		JOIN w_lieux_etendus t_lieux ON lieu_id = t_lieux.oid
  		WHERE service_est_absence <> '1'
  		ORDER BY 1,2,3
  		;
  
  		UPDATE w_mvt p_mouvements_sejour SET
  			nb_entrees_mutation_service = subview.nb_entrees_mutation_service,
  			nb_entrees_mutation_etage = subview.nb_entrees_mutation_etage
  		FROM
  		(
  		SELECT w_mvt_for_mutations.no_sejour, w_mvt_for_mutations.date, w_mvt_for_mutations.heure_debut,
  			CASE WHEN w_mvt_for_mutations.service_facturation_id = w_mvt_for_mutations_2.service_facturation_id THEN 0 ELSE 1 END AS nb_entrees_mutation_service,
  			CASE WHEN w_mvt_for_mutations.etage_id = w_mvt_for_mutations_2.etage_id THEN 0 ELSE 1 END AS nb_entrees_mutation_etage
  		FROM w_mvt_for_mutations
  		JOIN w_mvt_for_mutations w_mvt_for_mutations_2 ON 
  			w_mvt_for_mutations.no_sejour = w_mvt_for_mutations_2.no_sejour AND
  			w_mvt_for_mutations.rang_mvt = w_mvt_for_mutations_2.rang_mvt+ 1
  		WHERE (
  			w_mvt_for_mutations.nb_entrees_mutation_service = 1 AND w_mvt_for_mutations.service_facturation_id = w_mvt_for_mutations_2.service_facturation_id OR
  			w_mvt_for_mutations.nb_entrees_mutation_etage = 1 AND w_mvt_for_mutations.etage_id = w_mvt_for_mutations_2.etage_id
  			)
  		) subview
  		WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
  			p_mouvements_sejour.date = subview.date AND
  			p_mouvements_sejour.heure_debut = subview.heure_debut
  		;
  
  		UPDATE w_mvt p_mouvements_sejour SET
  			nb_sorties_mutation_service = subview.nb_sorties_mutation_service,
  			nb_sorties_mutation_etage = subview.nb_sorties_mutation_etage
  		FROM
  		(
  		SELECT w_mvt_for_mutations.no_sejour, w_mvt_for_mutations.date, w_mvt_for_mutations.heure_debut,
  			CASE WHEN w_mvt_for_mutations.service_facturation_id = w_mvt_for_mutations_2.service_facturation_id AND w_mvt_for_mutations.nb_sorties_directes <> 1 THEN 0 ELSE 1 END AS nb_sorties_mutation_service,
  			CASE WHEN w_mvt_for_mutations.etage_id = w_mvt_for_mutations_2.etage_id AND w_mvt_for_mutations.nb_sorties_directes <> 1 THEN 0 ELSE 1 END AS nb_sorties_mutation_etage
  		FROM w_mvt_for_mutations
  		JOIN w_mvt_for_mutations w_mvt_for_mutations_2 ON 
  			w_mvt_for_mutations.no_sejour = w_mvt_for_mutations_2.no_sejour AND
  			w_mvt_for_mutations.rang_mvt = w_mvt_for_mutations_2.rang_mvt- 1
  		WHERE (
  			w_mvt_for_mutations.nb_sorties_mutation_service = 1 AND w_mvt_for_mutations.service_facturation_id = w_mvt_for_mutations_2.service_facturation_id OR
  			w_mvt_for_mutations.nb_sorties_mutation_etage = 1 AND w_mvt_for_mutations.etage_id = w_mvt_for_mutations_2.etage_id
  			)
  		) subview
  		WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
  			p_mouvements_sejour.date = subview.date AND
  			p_mouvements_sejour.heure_debut = subview.heure_debut
  		;
  	END IF;
  
  	
  		
  	RAISE NOTICE '%' , 'Seances dans taux occupation'; 
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_dans_taux = CASE WHEN p_sejours.type_sejour = '5' THEN p_mouvements_sejour.nb_seances ELSE 0 END
  	FROM activite.p_sejours
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		p_mouvements_sejour.nb_seances > 0 AND
  		p_mouvements_sejour.nb_seances_dans_taux <> CASE WHEN p_sejours.type_sejour = '5' THEN p_mouvements_sejour.nb_seances ELSE 0 END
  	; 
  	RAISE NOTICE '%' , 'Chambres particulieres des ambulatoires';  
  	UPDATE w_mvt
  	SET est_chambre_particuliere = '1'
  	WHERE lieu_id = ANY
  		(
  		SELECT t_lieux.oid 
  		FROM w_lieux_etendus t_lieux
  		WHERE lit_id <> 0 AND lit_chambre_particuliere = 'O'
  		) AND
  		nb_ambulatoires > 0 AND
  		est_chambre_particuliere <> '1'
  	;
  	RAISE NOTICE '%' , 'Chambres particulieres des hospitalisés';  
  	UPDATE w_mvt
  	SET est_chambre_particuliere = '1'
  	WHERE lieu_id = ANY
  		(
  		SELECT t_lieux.oid 
  		FROM w_lieux_etendus t_lieux
  		WHERE lit_id <> 0 AND lit_chambre_particuliere = 'O'
  		) AND
  		est_jour_hospitalisation = '1' AND
  		est_chambre_particuliere <> '1'
  	;
  
  	RAISE NOTICE '%' , 'Precalcul EMC';  
  	DROP TABLE IF EXISTS w_mvt_emc;
  	CREATE TEMP TABLE w_mvt_emc AS
  	SELECT no_sejour, 
  		CASE 
  			WHEN service_type_t2a IN ('2','3') AND mode_traitement_code IN ('04','06','19','20','22') THEN to_char(date,'YYYYMMDD') 
  			WHEN service_type_t2a IN ('2','3') AND t_divers.valeur = '1' THEN to_char(date,'YYYYIW') 
  			ELSE '' END AS week,
  		SUM(
  		CASE WHEN est_jour_hospitalisation = '1'
  		THEN EXTRACT(EPOCH FROM (to_char(heure_fin,'FM000000')::time without time zone - to_char(heure_debut,'FM000000')::time without time zone))
  		ELSE 0 END
  		)::numeric AS totseconds
  	FROM w_mvt
  		JOIN w_lieux_etendus t_lieux ON lieu_id = t_lieux.oid
  		JOIN activite.t_divers ON t_divers.code = 'EMCHCSSRPSY'
  	GROUP BY 1,2
  	;
  	CREATE INDEX w_mvt_emc_i1
  	  ON w_mvt_emc
  	  USING btree
  	  (no_sejour);
  	RAISE NOTICE '%' , 'Calcul des journees';  
  	UPDATE w_mvt SET 
  		nb_jours_d =
  			CASE
  				WHEN service_mode_calcul_journees = '1'::text THEN
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  							)
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar AND w_mvt.heure_debut <= p_sejours.heure_entree
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				
  				WHEN service_mode_calcul_journees = '2'::text THEN
  					CASE 
  						WHEN 1=1 
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				
  				ELSE
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  								OR (mode_traitement_code = ANY (ARRAY ['04'::text, '06'::text, '19'::text, '20'::text, '22'::text])) AND w_mvt.nb_sorties_directes = 1::NUMERIC
  								OR w_mvt.est_jour_entree = '1'::bpchar AND w_mvt.est_jour_sortie = '1'::bpchar
  							)
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  			END
  		,
  		
  		nb_jours_f =
  			CASE
  				WHEN service_mode_calcul_journees = '1' THEN
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  							)
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				
  				WHEN service_mode_calcul_journees = '2' THEN
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  								OR w_mvt.nb_sorties_directes = 1::NUMERIC
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				
  				ELSE
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  								OR (mode_traitement_code = ANY (ARRAY ['04'::text, '06'::text, '19'::text, '20'::text, '22'::text])) AND w_mvt.nb_sorties_directes = 1::NUMERIC
  								OR w_mvt.est_jour_entree = '1'::bpchar AND w_mvt.est_jour_sortie = '1'::bpchar
  							)
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  								OR w_mvt.nb_sorties_directes = 1::NUMERIC
  							) 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER
  					END
  			END
  		,
  		
  		nb_jours_12 =
  			CASE
  				WHEN service_est_absence <> '1'::bpchar AND
  					w_mvt.est_jour_hospitalisation = '1'::bpchar AND
  					120000::numeric BETWEEN w_mvt.heure_debut AND w_mvt.heure_fin THEN 1::integer 
  				WHEN service_est_absence <> '1'::bpchar AND
  					w_mvt.nb_entrees_directes = 1 AND
  					w_mvt.heure_debut > 120000 THEN 1::integer 
  				WHEN service_est_absence <> '1'::bpchar AND
  					service_mode_calcul_journees = '2' AND
  					w_mvt.nb_sorties_directes = 1 AND
  					w_mvt.heure_fin < 120000 THEN 1::integer 
  			else 0 ::integer
  				
  				
  			END
  		,
  		
  		nb_jours_prorata = 
  			CASE
  				WHEN service_est_absence <> '1'::bpchar
  				THEN ((
  					CASE
  					WHEN heure_debut <> 240000 THEN substr(to_char(heure_fin,'FM000000'),1,2)::numeric * 3600 + substr(to_char(heure_fin,'FM000000'),3,2)::numeric * 60 + substr(to_char(heure_fin,'FM000000'),5,2)::numeric
  					ELSE 86400 END
  					-
  					CASE 
  					WHEN heure_debut <> 0 THEN substr(to_char(heure_debut,'FM000000'),1,2)::numeric * 3600 + substr(to_char(heure_debut,'FM000000'),3,2)::numeric * 60 + substr(to_char(heure_debut,'FM000000'),5,2)::numeric
  					ELSE 0 END
  					) / 86400)::NUMERIC 
  						ELSE 0::NUMERIC 
  						END
  					
  		,
  		
  		nb_jours_cp_d =  
  			CASE
  				WHEN service_mode_calcul_journees = '1' THEN
  					CASE 
  						WHEN 
  							service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND w_mvt.est_jour_sortie <> '1'::bpchar
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER
  						ELSE 0::INTEGER
  					END
  				
  				WHEN service_mode_calcul_journees = '2' THEN
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				ELSE
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  								OR w_mvt.est_jour_entree = '1'::bpchar AND w_mvt.est_jour_sortie = '1'::bpchar
  							)
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.nb_entrees_directes = 1::NUMERIC
  								OR w_mvt.heure_debut = 0::NUMERIC AND w_mvt.est_premier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_premier_mouvement_jour = '1'::bpchar
  							) 
  							THEN 1::INTEGER 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  			END
  		,
  		
  		nb_jours_cp_f =  
  			CASE
  				WHEN service_mode_calcul_journees = '1' THEN
  					CASE
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND w_mvt.est_jour_sortie <> '1'::bpchar
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  								OR w_mvt.nb_sorties_directes = 1::NUMERIC
  							) 
  							THEN 1::INTEGER 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				WHEN service_mode_calcul_journees = '2' THEN
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  								OR w_mvt.nb_sorties_directes = 1::NUMERIC
  							) 
  							THEN 1::INTEGER 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  				ELSE
  					CASE 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.est_jour_sortie <> '1'::bpchar
  								OR w_mvt.est_jour_entree = '1'::bpchar AND w_mvt.est_jour_sortie = '1'::bpchar
  							)
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar
  							AND (1!=1
  								OR w_mvt.heure_fin = 240000::NUMERIC AND w_mvt.est_dernier_mouvement_jour IS DISTINCT FROM '9'
  								OR w_mvt.est_dernier_mouvement_jour = '1'::bpchar
  								OR w_mvt.nb_sorties_directes = 1::NUMERIC
  							) 
  							THEN 1::INTEGER 
  						WHEN 1=1
  							AND service_est_absence <> '1'::bpchar
  							AND w_mvt.nb_ambulatoires = 1::NUMERIC
  							AND w_mvt.est_chambre_particuliere = '1'::bpchar 
  							THEN 1::INTEGER 
  						ELSE 0::INTEGER 
  					END
  			END
  		,
  		
  		nb_jours_cp_12 = 
  			CASE
  				WHEN 1=1
  					AND service_est_absence <> '1'::bpchar
  					AND w_mvt.est_jour_hospitalisation = '1'::bpchar
  					AND w_mvt.est_chambre_particuliere = '1'::bpchar
  					AND 120000::NUMERIC >= w_mvt.heure_debut
  					AND 120000::NUMERIC <= w_mvt.heure_fin 
  					THEN 1::INTEGER 
  				WHEN 1=1
  					AND service_est_absence <> '1'::bpchar
  					AND w_mvt.nb_ambulatoires = 1::NUMERIC
  					AND w_mvt.est_chambre_particuliere = '1'::bpchar
  					AND 120000::NUMERIC >= w_mvt.heure_debut
  					AND 120000::NUMERIC <= w_mvt.heure_fin 
  					THEN 1::INTEGER
  				WHEN service_est_absence <> '1'::bpchar AND
  					w_mvt.est_chambre_particuliere = '1'::bpchar AND
  					w_mvt.nb_entrees_directes = 1 AND
  					w_mvt.heure_debut > 120000 THEN 1::integer 
  				WHEN service_est_absence <> '1'::bpchar AND
  					w_mvt.est_chambre_particuliere = '1'::bpchar AND
  					service_mode_calcul_journees = '2' AND
  					w_mvt.nb_sorties_directes = 1 AND
  					w_mvt.heure_fin < 120000 THEN 1::integer 
  				ELSE 0::INTEGER 
  				
  			END,
  		equivalent_malade_complet =
  			CASE 
  				WHEN p_sejours.type_sejour = '1' AND est_jour_hospitalisation = '1'
  					THEN base.cti_division
  						(EXTRACT(EPOCH FROM (to_char(heure_fin,'FM000000')::time without time zone - to_char(heure_debut,'FM000000')::time without time zone))::numeric,
  						totseconds
  						)
  				WHEN p_sejours.type_sejour = '2' AND nb_ambulatoires = 1 THEN 1
  				WHEN p_sejours.type_sejour = '3' AND nb_externes = 1 THEN 1
  				WHEN p_sejours.type_sejour = '5' AND nb_seances >= 1 THEN 1
  				ELSE 0 
  			END
  								
  	FROM 
  		w_lieux_etendus t_lieux,
  		activite.p_sejours,
  		w_mvt_emc, 
  		activite.t_divers t_divers_emchcssrpsy
  	WHERE 1=1
  		AND w_mvt.lieu_id = t_lieux.oid
  		AND w_mvt.no_sejour = p_sejours.no_sejour
  		AND w_mvt.no_sejour = w_mvt_emc.no_sejour 
  			AND (CASE 
  			WHEN service_type_t2a IN ('2','3') AND mode_traitement_code IN ('04','06','19','20','22') THEN to_char(date,'YYYYMMDD') 
  			WHEN service_type_t2a IN ('2','3') AND t_divers_emchcssrpsy.valeur = '1' THEN to_char(date,'YYYYIW') 
  			ELSE '' END) = w_mvt_emc.week
  		AND t_divers_emchcssrpsy.code = 'EMCHCSSRPSY';
  	-- remise en place jours d'absence
  	IF _nb_services_absence > 0 THEN
  	RAISE NOTICE '%' , 'Traitement special absences (2)'; 
  		UPDATE w_mvt SET
  			est_premier_mouvement_jour = '0',
  			est_dernier_mouvement_jour = '0'
  		FROM w_absences
  		WHERE w_absences.no_sejour = w_mvt.no_sejour AND
  			w_absences.date = w_mvt.date ;
  	END IF;
  
  	RAISE NOTICE '%' , 'Entrees en urgence'; 
  
  	-- entrées en urgence selon etage
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_urgences = 1
  	FROM w_lieux_etendus t_lieux
  	WHERE lieu_id = t_lieux.oid AND
  		etage_est_urgence = '1' AND
  		nb_urgences = 0 AND
  		(nb_entrees_directes = 1 OR
  		nb_ambulatoires = 1 OR
  		nb_externes = 1
  		)
  	;
  
  	
  	UPDATE activite.p_sejours
  	SET provenance = '5'
  	FROM w_mvt p_mouvements_sejour 
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_mouvements_sejour.nb_urgences = 1 AND
  		p_sejours.provenance <> '5'
  	;
  	
  	-- entrées en urgence selon dmt
  	UPDATE w_mvt
  	SET nb_urgences = 1
  	FROM w_lieux_etendus t_lieux 
  	WHERE lieu_id = t_lieux.oid AND
  		dmt_code = ANY(ARRAY['303', '307', '308', '401', '402', '403', '404', '405', '406', '407', '408', '409']) AND
  		nb_urgences <> 1 AND
  		(
  		nb_entrees_directes = 1 OR
  		nb_ambulatoires = 1 OR
  		nb_externes = 1
  		)
  	;
  	UPDATE w_mvt
  	SET nb_urgences = 1
  	FROM activite.p_sejours
  	WHERE w_mvt.no_sejour = p_sejours.no_sejour AND 
  		nb_urgences <> 1 AND
  		provenance = '5' AND
  		(
  		nb_entrees_directes = 1 OR
  		nb_ambulatoires = 1 OR
  		nb_externes = 1)
  	;
  
  	-- Enlever les séances en hospit si paramétrage
  	UPDATE w_mvt
  	SET nb_seances = 0
  	FROM activite.p_sejours
  	JOIN activite.t_divers ON t_divers.code = 'SEANCEHOSPIT' AND t_divers.valeur = '0'
  	WHERE w_mvt.no_sejour = p_sejours.no_sejour AND 
  		type_sejour <> '5' AND
  		nb_seances <> 0 
  	;
  
  	-- Enlever les séances (sauf dialyse) en hospit si paramétrage
  	DROP TABLE IF EXISTS w_seances_all;
  	CREATE TEMP TABLE w_seances_all AS
  	SELECT p_sejours.no_sejour, date, '0'::text AS dialyse
  	FROM w_mvt
  	JOIN activite.p_sejours ON w_mvt.no_sejour = p_sejours.no_sejour
  	JOIN activite.t_divers ON t_divers.code = 'SEANCEHOSPIT' AND t_divers.valeur = '2'
  	WHERE type_sejour <> '5' AND
  		nb_seances <> 0
  	; 
  
  	UPDATE w_seances_all
  	SET dialyse = '1'
  	FROM activite.p_factures_lignes_h p_factures_lignes
  	JOIN base.t_actes ON acte_id = t_actes.oid AND t_actes.code LIKE 'JVJF%'
  	JOIN activite.p_factures ON p_factures_lignes.no_facture = p_factures.no_facture
  	WHERE p_factures.no_sejour = w_seances_all.no_sejour AND
  		p_factures_lignes.date_debut = w_seances_all.date
  	;
  
  	UPDATE w_seances_all
  	SET dialyse = '1'
  	FROM activite.p_factures_lignes_non_facturees_h p_factures_lignes
  	JOIN base.t_actes ON acte_id = t_actes.oid AND t_actes.code LIKE 'JVJF%'
  	JOIN activite.p_factures ON p_factures_lignes.no_facture = p_factures.no_facture
  	WHERE p_factures.no_sejour = w_seances_all.no_sejour AND
  		p_factures_lignes.date_debut = w_seances_all.date
  	;
  
  	UPDATE w_seances_all
  	SET dialyse = '1'
  	FROM activite.p_factures_lignes_c p_factures_lignes
  	JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND (t_prestations.code LIKE 'D0%' OR t_prestations.code LIKE 'D1%' )
  	JOIN activite.p_factures ON p_factures_lignes.no_facture = p_factures.no_facture
  	WHERE p_factures.no_sejour = w_seances_all.no_sejour AND
  		p_factures_lignes.date_debut = w_seances_all.date
  	;
  
  	UPDATE w_seances_all
  	SET dialyse = '1'
  	FROM activite.p_factures_lignes_non_facturees_c p_factures_lignes
  	JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND (t_prestations.code LIKE 'D0%' OR t_prestations.code LIKE 'D1%' )
  	JOIN activite.p_factures ON p_factures_lignes.no_facture = p_factures.no_facture
  	WHERE p_factures.no_sejour = w_seances_all.no_sejour AND
  		p_factures_lignes.date_debut = w_seances_all.date
  	;
  
  	UPDATE w_mvt
  	SET nb_seances = 0
  	FROM w_seances_all
  	WHERE w_mvt.no_sejour = w_seances_all.no_sejour AND
  		w_mvt.date = w_seances_all.date AND
  		dialyse = '0'
  	;
  
  	-- Nb jours des sortis pour calcul DMS
  	UPDATE w_mvt
  	SET nb_jour_sejour_sorti = subview.nb_jour_sejour_sorti
  	FROM
  		(SELECT no_sejour, 
  		SUM(nb_jours_f) AS nb_jour_sejour_sorti,
  		MAX(CASE WHEN nb_sorties_directes > 0 THEN date ELSE NULL END) AS date,
  		MAX(CASE WHEN nb_sorties_directes > 0 THEN heure_fin ELSE NULL END) AS heure_fin
  		FROM w_mvt
        WHERE est_mouvement_previsionnel <> '1'
  		GROUP BY 1
  		HAVING SUM(nb_sorties_directes) > 0
  		) subview
  		WHERE w_mvt.no_sejour = subview.no_sejour AND
  			w_mvt.date = subview.date AND
  			w_mvt.heure_fin = subview.heure_fin AND
  			nb_sorties_directes > 0
  	;
  	
  	UPDATE w_mvt
  	SET nb_jour_sejour_sorti = nb_ambulatoires
  	WHERE est_mouvement_previsionnel <> '1' AND
  		nb_ambulatoires <> 0
  	;
  
  	UPDATE w_mvt
  	SET nb_jour_sejour_sorti = nb_seances
  	FROM activite.p_sejours 
  	WHERE w_mvt.no_sejour = p_sejours.no_sejour AND
  		p_sejours.type_sejour = '5' AND
  		est_mouvement_previsionnel <> '1' AND
  		nb_seances <> 0
  	;
  
  	-- Distinction des types de séances
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_dialyse = nb_seances
  	FROM activite.p_sejours
  	JOIN base.t_ghm ON ghm_id = t_ghm.oid
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		p_sejours.type_sejour = '5' AND
  		nb_seances <> 0 AND
  		t_ghm.code = ANY(Array['28Z01Z','28Z02Z','28Z03Z','28Z04Z','28Z05Z','28Z06Z']) AND
  		nb_seances_dialyse IS DISTINCT FROM nb_seances
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_chimio = nb_seances
  	FROM activite.p_sejours
  	JOIN base.t_ghm ON ghm_id = t_ghm.oid
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		p_sejours.type_sejour = '5' AND
  		nb_seances <> 0 AND
  		t_ghm.code = ANY(Array['28Z07Z','28Z17Z']) AND
  		nb_seances_dialyse IS DISTINCT FROM nb_seances
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_chimio = nb_seances
  	FROM activite.p_sejours
  	JOIN base.t_ghs ON ghs_id = t_ghs.oid
  	WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
  		p_sejours.type_sejour = '5' AND
  		nb_seances <> 0 AND
  		t_ghs.code = ANY(Array[9606]) AND
  		nb_seances_chimio = 0
  	;
  
  	DROP TABLE IF EXISTS w_seances_hospit_fac;
  	CREATE TEMP TABLE w_seances_hospit_fac AS
  	SELECT p_factures.no_sejour
  	FROM activite.p_factures_lignes_c
  	JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
  	JOIN activite.t_prestations ON prestation_id = t_prestations.oid
  	JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
  	WHERE p_sejours.type_sejour <> '5' AND 
  		t_prestations.code = ANY(Array['D09','D11','D15','D16','DTP'])
  	GROUP BY 1
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_dialyse = nb_seances
  	WHERE nb_seances <> 0 AND
  		nb_seances_dialyse IS DISTINCT FROM nb_seances AND
  		no_sejour IN (SELECT no_sejour FROM w_seances_hospit_fac)
  	;
  
  	DROP TABLE IF EXISTS w_seances_hospit_nfac;
  	CREATE TEMP TABLE w_seances_hospit_nfac AS
  	SELECT p_factures.no_sejour
  	FROM activite.p_factures_lignes_non_facturees_c p_factures_lignes_c
  	JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
  	JOIN activite.t_prestations ON prestation_id = t_prestations.oid
  	JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
  	WHERE p_sejours.type_sejour <> '5' AND 
  		t_prestations.code = ANY(Array['D09','D11','D15','D16','DTP'])
  	GROUP BY 1
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_dialyse = nb_seances
  	WHERE nb_seances <> 0 AND
  		nb_seances_dialyse IS DISTINCT FROM nb_seances AND
  		no_sejour IN (SELECT no_sejour FROM w_seances_hospit_nfac)
  	;
  
  	DROP TABLE IF EXISTS w_seances_dialyse_dmt;
  	CREATE TEMP TABLE w_seances_dialyse_dmt AS
  	SELECT no_sejour
  	FROM activite.p_mouvements_sejour
  	JOIN activite.t_lieux ON lieu_id = t_lieux.oid
  	JOIN activite.t_services_facturation ON service_facturation_id = t_services_facturation.oid
  	JOIN base.t_dmt ON dmt_id = t_dmt.oid
  	WHERE nb_seances_autre > 0 AND
  		t_dmt.texte ILIKE '%dialyse%'
  	GROUP BY 1
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_dialyse = nb_seances
  	WHERE nb_seances <> 0 AND
  		nb_seances_dialyse IS DISTINCT FROM nb_seances AND
  		no_sejour IN (SELECT no_sejour FROM w_seances_dialyse_dmt)
  	;
  
  	UPDATE w_mvt p_mouvements_sejour
  	SET nb_seances_autre = nb_seances - nb_seances_dialyse - nb_seances_chimio
  	WHERE nb_seances <> 0 AND
  		nb_seances_autre IS DISTINCT FROM (nb_seances - nb_seances_dialyse - nb_seances_chimio)
  	;
  	
  	UPDATE w_mvt p_mouvements_sejour SET
  		nb_preadmission_validee = 1,
  		nb_preadmission_validee_j1 = subview.preadmission_j1,
  		nb_preadmission_validee_j2 = subview.preadmission_j2
  	FROM 
  	(
  	SELECT p_sejours_preadmission.no_sejour, 
  		p_mouvements_sejour.date,
  		preadmission_j1,
  		preadmission_j2
  	FROM activite.p_sejours_preadmission
  	JOIN activite.p_sejours on p_sejours_preadmission.no_sejour = p_sejours.no_sejour
  	JOIN w_mvt p_mouvements_sejour on 
  		p_sejours_preadmission.no_sejour = p_mouvements_sejour.no_sejour AND
  		date(p_sejours_preadmission.date_entree) = p_mouvements_sejour.date AND
  		(
  		nb_entrees_directes = 1 OR
  		nb_ambulatoires = 1 OR
  		nb_externes = 1 OR
  		nb_seances > 0
  		)
  	WHERE date_validation_preadmission IS NOT NULL AND
  		code_prevu = '0' 
  	) subview
  	WHERE p_mouvements_sejour.no_sejour = subview.no_sejour AND
  		 p_mouvements_sejour.date = subview.date AND
  		 (
  		nb_entrees_directes = 1 OR
  		nb_ambulatoires = 1 OR
  		nb_externes = 1 OR
  		nb_seances > 0
  		)
  	;
  	
  	-- Enlever les journées pour les bébés (type séjour 6 - MEDSPHERE, HM)
  	UPDATE w_mvt p_mouvements_sejour
  	SET 
  		nb_ambulatoires = 0,
  		nb_chambres_particulieres = 0,
  		nb_entrees_directes = 0,
  		nb_entrees_mutation_activite = 0,
  		nb_entrees_mutation_etage = 0,
  		nb_entrees_mutation_service = 0,
  		nb_entrees_mutation_unite_medicale = 0,
  		nb_entrees_mutations = 0,
  		nb_externes = 0,
  		nb_jour_sejour_sorti = 0,
  		nb_jours_12 = 0,
  		nb_jours_cp_12 = 0,
  		nb_jours_cp_d = 0,
  		nb_jours_cp_f = 0,
  		nb_jours_d = 0,
  		nb_jours_f = 0,
  		nb_jours_js_inclus = 0,
  		nb_jours_js_non_inclus = 0,
  		nb_jours_prorata = 0,
  		nb_passage_externe = 0,
  		nb_seances = 0,
  		nb_seances_autre = 0,
  		nb_seances_chimio = 0,
  		nb_seances_dans_taux = 0,
  		nb_seances_dialyse = 0,
  		nb_sorties_directes = 0,
  		nb_sorties_mutation_activite = 0,
  		nb_sorties_mutation_etage = 0,
  		nb_sorties_mutation_service = 0,
  		nb_sorties_mutation_unite_medicale = 0,
  		nb_sorties_mutations = 0,
  		nb_urgences = 0
  	FROM activite.p_sejours
  	WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
  		p_sejours.type_sejour IN ('6')
  	;
  
  RAISE NOTICE '%' , 'Décomposition par type pmsi';  
    
    	--Décomposition par type_pmsi et type_sejour
    	DROP TABLE IF EXISTS w_mvt_pmsi;
    	CREATE TEMP TABLE w_mvt_pmsi AS 
    	SELECT w_mvt.*,  
    	p_sejours.type_pmsi,
    	p_sejours.mode_traitement_id ,
    	p_sejours.type_sejour,
    	p_sejours.forme_activite_id
    	FROM w_mvt
    	JOIN  activite.p_sejours ON p_sejours.no_sejour = w_mvt.no_sejour
    	JOIN  w_lieux_etendus ON w_lieux_etendus.oid = w_mvt.lieu_id;
    
    
    	-- MAJ MCO hospi
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 11
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 1 AND w_mvt_pmsi.type_sejour = 1;	
    
    	-- MAJ MCO ambu
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 12
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 1 AND w_mvt_pmsi.type_sejour = 2;
    
    	-- MAJ MCO seances
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 15
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 1 AND w_mvt_pmsi.type_sejour = 5;	
    
    
    	-- MAJ SSR hospitalisation complète 
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 21
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 2 AND w_mvt_pmsi.type_sejour = 1;	
    	
    	-- MAJ SSR hospitalisation partiel ou HDJ 
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 22
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 2 AND w_mvt_pmsi.type_sejour = 2;	
    
    	-- MAJ SSR Autres
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 24
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 2 AND w_mvt_pmsi.type_sejour not in ('1','2');	
    
    	-- MAJ SSR Autres
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 24
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 2 AND w_mvt_pmsi.type_sejour not in ('1','2');	
    
    	-- MAJ PSY HC
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 31
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 3 AND w_mvt_pmsi.type_sejour = 1;	
    
    	-- MAJ PSY HP (HDJ)
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 32
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 3 AND w_mvt_pmsi.type_sejour = 2;	
    
    	-- MAJ PSY Autres
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 33
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 3 AND w_mvt_pmsi.type_sejour not in ('1','2');	
    
    	-- MAJ HAD Hospi
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 41
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_pmsi = 4 AND w_mvt_pmsi.type_sejour = 1;	
    
    	-- MAJ Externes 
    	UPDATE activite.p_sejours 
    	SET type_hospi_pmsi_id = 30
    	FROM w_mvt_pmsi 
    	WHERE 1=1 
    	     AND p_sejours.no_sejour = w_mvt_pmsi.no_sejour
    	     AND w_mvt_pmsi.type_sejour = 3;
  
    	RAISE NOTICE '%' , 'sequence de changement du lieu';  
  
  	with clustering as (
                      select
                          sejour_id,
                          lieu_id,
                          date,
                          case when lag(lieu_id) over w  = coalesce(lieu_id) then null else true end as new_cluster
                      from w_mvt
                      window w as (partition by sejour_id order by date, nb_jours_js_non_inclus)
                      )
  	,assigned_clustering as (
                      select
                          sejour_id,
                          lieu_id,
                          date,
                          count(new_cluster) over (order by sejour_id, date rows unbounded preceding) as cluster_id
                      from clustering)
  	UPDATE w_mvt 
  		SET sequences = assigned_clustering.cluster_id
          FROM assigned_clustering
          WHERE w_mvt.sejour_id = assigned_clustering.sejour_id 
                AND w_mvt.lieu_id = assigned_clustering.lieu_id 
                AND w_mvt.date = assigned_clustering.date
              ;
              
  	-- Réécriture des données dans la table de production
  	RAISE NOTICE '%' , 'Ecriture des donnees dans la table de production';  
  	TRUNCATE activite.p_mouvements_sejour;
  	
  	INSERT INTO activite.p_mouvements_sejour
  		SELECT * FROM w_mvt;
  		
  	-- Activation index
  	RAISE NOTICE '%' , 'Reactivation index';  
  	PERFORM base.cti_stash_pop_table_indexes('activite.p_mouvements_sejour');
  	
  	ANALYZE activite.p_mouvements_sejour;
  	
      RETURN 'OK' ;
  END;