<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" type="common" />
	<NODE name="PROD" label="Préparattion données">
		<NODE label="Salariés">
			<sqlcmd><![CDATA[
			-- définition des personnes
            DROP TABLE IF EXISTS prod_kelio_pers
            ;
            CREATE TEMP TABLE prod_kelio_pers AS
                SELECT
                    matricule_,
					personne.*
                FROM prod_kelio.salarie
				 JOIN prod_kelio.personne ON salarie.personne_ = personne.personne_
            ;
			
			DROP TABLE IF EXISTS prod_kelio_absence
				;
				CREATE TEMP TABLE prod_kelio_absence AS
					SELECT affectation_absence.*, libelle_,abrege_,calc_hspe_ as est_presence, mode_cumul_, ''::text AS salarie_corr 
					FROM prod_kelio.affectation_absence
					LEFT JOIN prod_kelio.motif_calcul ON absence_motif_absence_ = motif_calcul_
					WHERE absence_date_fin_ > '[ENV_PLANNING_DATEDEBUT]'::date
				;

			-- surcharge de types d'absence
			UPDATE prod_kelio_absence
			SET est_presence = CASE WHEN to_id IS NOT NULL THEN 1 ELSE 0 END
			FROM rh.t_planning_type_absence 
				LEFT JOIN (
					SELECT
						to_id,
						t_planning_type_absence.code
					FROM rh.t_listes
					JOIN rh.t_listes_contenu ON liste_id = t_listes.oid
						JOIN rh.t_planning_type_absence ON to_id = t_planning_type_absence.oid
					WHERE t_listes.code = 'CTI_ABS_TRAVAILLEES'
				) sub ON sub.code = t_planning_type_absence.code
			WHERE 1=1
				AND abrege_ = t_planning_type_absence.code;

			]]></sqlcmd>
		</NODE>

		<NODE label="Kelio type HP Metz">
			<condition><![CDATA[
				SELECT 1=1
				FROM information_schema.columns
				WHERE column_name = 'affectation_horaire_journalie_' 
				AND table_name = 'affectation_horaire_journalier'
				AND table_schema = 'prod_kelio'
				-- sans base, ventilation par population_salarie, utilisation de datamart pour absences et heures spéciales (pauses annulées)
				;
            ]]></condition>
			<NODE label="Préparation des affectation">
				<sqlcmd><![CDATA[

				-- Technique : reconstitution d'une table d'ajustement en partant des horaire et en modulant par la planification et les jours fériés pour obtenir le réalisé
				DROP TABLE IF EXISTS prod_kelio_affectation_horaire_journalier
				;
				CREATE TEMP TABLE prod_kelio_affectation_horaire_journalier AS
					SELECT affectation_horaire_journalier.*,
				false AS plage_updated,
				periode_travail.debut_/3600.0 AS debut_th,
				periode_travail.fin_/3600.0 as fin_th,
				(periode_travail.fin_-periode_travail.debut_)/3600.0 AS duree_th,
				CASE WHEN periode_realise.debut_ IS NULL THEN periode_travail.debut_/3600.0 ELSE periode_realise.debut_/3600.0 END AS debut,
				CASE WHEN periode_realise.fin_ IS NULL THEN periode_travail.fin_/3600.0 ELSE periode_realise.fin_/3600.0 END AS fin,
				CASE WHEN periode_realise.debut_ IS NULL THEN (periode_travail.fin_-periode_travail.debut_)/3600.0 ELSE (periode_realise.fin_-periode_realise.debut_)/3600.0 END As duree,
				COALESCE(-dh_4,0)/3600.0 AS pause_th,
				COALESCE(h72_1,0)/3600.0 AS pause_deb_th,
				COALESCE(dh_2,0)/3600.0 AS pause_fin_th,
				0::numeric AS pause,
				''::text AS salarie_corr 
				FROM prod_kelio.affectation_horaire_journalier
				LEFT JOIN prod_kelio.periode_travail ON affectation_horaire_journalier.horaire_journalier_ = periode_travail.horaire_journalier_
				LEFT JOIN prod_kelio.periode_travail periode_realise ON affectation_horaire_journalier.affectation_horaire_journalie_ = periode_realise.affectation_horaire_journalie_
				LEFT JOIN prod_kelio.plage_horaire ON affectation_horaire_journalier.horaire_journalier_ = plage_horaire.horaire_journalier_ 
							AND plage_horaire.dh_4 < 0
				LEFT JOIN (
					SELECT distinct date_application_ AS ferie FROM prod_kelio.jour_ferie) feries ON ferie = date_application_
				LEFT JOIN prod_kelio.jour_ferie ON affectation_horaire_journalier.salarie_ = jour_ferie.salarie_ 
					AND jour_ferie.date_application_ = affectation_horaire_journalier.date_application_
				WHERE affectation_horaire_journalier.date_application_ > '2015-01-01'
					AND (ferie IS NULL OR (ferie IS NOT NULL AND jour_travaille_ = 1))
			--	AND (periode_realise.debut_ IS NULL OR (periode_realise.debut_ BETWEEN periode_travail.debut_ AND periode_travail.fin_
			--	 OR periode_travail.debut_ BETWEEN periode_realise.debut_ AND  periode_realise.fin_
			--	))
				;
					
						-- cas 0 2 devient 2 ou 1 devient ou 2 devient 1
				UPDATE prod_kelio_affectation_horaire_journalier to_update
				SET 
					plage_updated = true,
					debut = CASE WHEN to_update.debut_th = debut_th_max THEN 0 ELSE to_update.debut END,
					fin = CASE WHEN to_update.debut_th = debut_th_max THEN 0 ELSE to_update.fin END,
					duree = CASE WHEN to_update.debut_th = debut_th_max THEN 0 ELSE to_update.duree END,
					debut_th = CASE WHEN to_update.debut = debut_max THEN 0 ELSE to_update.debut END,
					fin_th = CASE WHEN to_update.debut = debut_max THEN 0 ELSE to_update.fin_th END,
					duree_th = CASE WHEN to_update.debut = debut_max THEN 0 ELSE to_update.duree END 
				FROM (
					SELECT 
						affectation_horaire_journalie_, debut, fin, MAX(debut_th) AS debut_th_max 
						FROM prod_kelio_affectation_horaire_journalier GROUP BY 1,2,3
						HAVING count(*) > 1
						) sub,
						(
					SELECT 
						affectation_horaire_journalie_, debut_th, fin_th, MAX(debut) AS debut_max 
						FROM prod_kelio_affectation_horaire_journalier GROUP BY 1,2,3
						HAVING count(*) > 1
						) sub2
				WHERE 
					to_update.affectation_horaire_journalie_ = sub.affectation_horaire_journalie_
					AND to_update.affectation_horaire_journalie_ = sub2.affectation_horaire_journalie_
				;
				
				
				
				-- cas 1 période th devient 2 rea
				UPDATE prod_kelio_affectation_horaire_journalier
				SET 
					debut_th = 0,
					fin_th = 0,
					duree_th = 0,
					pause_th = 0,
					pause_deb_th = 0,
					pause_fin_th = 0
				FROM (
					SELECT 
						affectation_horaire_journalie_, debut_th, fin_th, MAX(debut) AS debut_max 
						FROM prod_kelio_affectation_horaire_journalier GROUP BY 1,2,3
						HAVING count(*) > 1
						) sub
				WHERE 
					prod_kelio_affectation_horaire_journalier.affectation_horaire_journalie_ = sub.affectation_horaire_journalie_
					AND debut_max = debut
					AND plage_updated = false
				;
				
				-- cas 2 périodes th deviennent 1 rea
				UPDATE prod_kelio_affectation_horaire_journalier
				SET 
					debut = 0,
					fin = 0,
					duree = 0 
				FROM (
					SELECT 
						affectation_horaire_journalie_, debut, fin, MAX(debut_th) AS debut_max 
						FROM prod_kelio_affectation_horaire_journalier GROUP BY 1,2,3
						HAVING count(*) > 1
						) sub
				WHERE 
					prod_kelio_affectation_horaire_journalier.affectation_horaire_journalie_ = sub.affectation_horaire_journalie_
					AND debut_max = debut_th
					AND plage_updated = false
				;
				]]></sqlcmd>
			</NODE>
			<NODE label="Préparation des données">
				<sqlcmd><![CDATA[
				-- calcul pause reelle
				UPDATE prod_kelio_affectation_horaire_journalier
				SET 
					pause = CASE 
								WHEN pause_deb_th BETWEEN debut AND fin AND pause_deb_th + pause_th BETWEEN debut AND fin THEN pause_th
								--WHEN pause_deb_th BETWEEN debut AND fin AND pause_deb_th + pause_th NOT BETWEEN debut AND fin THEN LEAST(pause_th,fin - pause_deb_th)
								WHEN pause_fin_th BETWEEN debut AND fin AND pause_fin_th - pause_th BETWEEN debut AND fin THEN pause_th
								--WHEN pause_fin_th BETWEEN debut AND fin AND pause_fin_th - pause_th NOT BETWEEN debut AND fin THEN LEAST(pause_th,pause_fin_th - debut)
								ELSE 0 END
				;
				
				
				-- reconstitution de l'organigramme
				DROP TABLE IF EXISTS prod_kelio_organigramme
				;
				CREATE TEMP TABLE prod_kelio_organigramme AS
					SELECT 
						organigramme.organigramme_ AS service_,
						organigramme.organigramme_ AS code_original,
						COALESCE(code_, organigramme.organigramme_::text) AS codeNiv3, 
						organigramme.libelle_ AS libNiv3, 
						niv2.organigramme_ AS codeNiv2,
						niv2.libelle_ AS libNiv2,
						niv1.organigramme_ AS codeNiv1,
						niv1.libelle_ AS libNiv1
					FROM prod_kelio.organigramme 
						LEFT JOIN (SELECT service_, centre_de_charge_ FROM prod_kelio.activite_par_defaut GROUP BY 1,2) sub ON sub.service_ = organigramme_
						JOIN prod_kelio.organigramme niv2 ON organigramme.parent_ = niv2.organigramme_
						JOIN prod_kelio.organigramme niv1 ON niv2.parent_ = niv1.organigramme_
						LEFT JOIN prod_kelio.motif_calcul ON motif_calcul.libelle_ = organigramme.libelle_
						ORDER BY organigramme.organigramme_
						;
				;
								
				-- affectation des salariés au service avec remplissage des trou et gestion des overlap sur une journée
					-- affectation des salariés au service avec remplissage des trou et gestion des overlap sur une journée
				DROP TABLE IF EXISTS w_histo_ser;
				CREATE TEMP TABLE w_histo_ser AS 
				SELECT
					salarie_,
					debut_,
					fin_,
					0 AS heure_debut_periode_,
					24 AS heure_fin_periode_,
					service_,
					''::text AS niv_cod1,
					''::text AS niv_cod2,
					''::text AS niv_cod3,
					''::text AS niv_cod4,
					''::text AS niv_cod5,
					1 AS src
				FROM prod_kelio.population_salarie 
				GROUP BY 1,2,3,4,5,6,7,8
				;
			
				UPDATE w_histo_ser
				SET fin_ = w_histo_ser_ref.debut_ - '1 day'::interval 
				FROM w_histo_ser w_histo_ser_ref
				WHERE w_histo_ser.salarie_ = w_histo_ser_ref.salarie_ AND w_histo_ser_ref.debut_ between w_histo_ser.debut_ AND w_histo_ser.fin_ AND 
				(w_histo_ser.debut_ != w_histo_ser_ref.debut_ OR w_histo_ser.fin_ != w_histo_ser_ref.fin_) AND
					 w_histo_ser.fin_ != w_histo_ser.debut_
				;

				DROP SEQUENCE IF EXISTS w_periode_seq
				;

							CREATE TEMP SEQUENCE w_periode_seq
				;

				DROP TABLE IF EXISTS w_histo_ser_overlap;
				CREATE TEMP TABLE w_histo_ser_overlap AS 
				SELECT 
					affectation_activite.salarie_,
					service_,
					jour_ as debut_,
					jour_ as fin_,
					heure_debut_periode_ as heure_debut_periode_,
					CASE WHEN heure_fin_periode_ = 0 THEN 24 ELSE heure_fin_periode_ END AS heure_fin_periode_
				FROM prod_kelio.affectation_activite
					JOIN prod_kelio.activite_par_defaut ON affectation_activite.centre_de_charge_ = activite_par_defaut.centre_de_charge_
					WHERE heure_debut_periode_ != 0 AND affectation_activite.salarie_ != 0
					;

				-- insert overlap
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
				SELECT 
					salarie_,
					debut_,
					fin_,
					heure_debut_periode_,
					heure_fin_periode_,
					service_,
					2
				FROM w_histo_ser_overlap
				;
				
				-- ajout de la periodes supplementaires
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
					SELECT 
					w_histo_ser.salarie_,
					w_histo_ser.fin_ + CASE WHEN w_histo_ser.fin_ = 24 THEN  interval '1 day' ELSE interval '0 day' END,
					w_histo.fin_,
					CASE WHEN MAX(w_histo_ser.fin_) = 24 THEN 0 ELSE MAX(w_histo_ser.heure_fin_periode_) END as heure_debut_periode_,
					24 as heure_fin_periode_,
					w_histo.service_,
					3
				FROM w_histo_ser
					JOIN w_histo_ser w_histo ON 
						w_histo.salarie_ = w_histo_ser.salarie_ AND
						w_histo_ser.src != 1 AND
						w_histo.src = 1 AND 
						w_histo_ser.debut_ BETWEEN w_histo.debut_ AND w_histo.fin_
						--and w_histo_ser.salarie_ = 4181 
				GROUP BY 1,2,3,5,6,7
				;


				
				-- maj des dates de fin si overlap 
					UPDATE w_histo_ser
				SET
					fin_ = next_day - CASE WHEN next_hour = 0 THEN interval '1 day' ELSE interval '0 day' END,
					heure_fin_periode_ = CASE WHEN next_hour = 0 THEN 24 ELSE next_hour END
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(heure_debut_periode_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_hour,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_day
					FROM w_histo_ser
					) sub
				WHERE 
					salarie_ = sal AND
					src = 3 AND
					debut_ = deb AND
					fin_ = fin AND
					service_ = ser AND
					next_day IS NOT NULL;


				DELETE FROM w_histo_ser
				USING w_histo_ser ref
				WHERE 1=1 AND
					w_histo_ser.salarie_ = ref.salarie_ AND
					w_histo_ser.src = 3 AND
					ref.src != 3 AND
					w_histo_ser.debut_ = ref.debut_ AND
					w_histo_ser.fin_ = ref.fin_
					;

					
				-- maj des dates de fin d'origin
				UPDATE w_histo_ser
				SET
					fin_ = next_day - CASE WHEN next_hour = 0 THEN interval '1 day' ELSE interval '0 day' END,
					heure_fin_periode_ = CASE WHEN next_hour = 0 THEN 24 ELSE next_hour-1 END
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(heure_debut_periode_) OVER (PARTITION BY salarie_ ORDER BY debut_, fin_) as next_hour,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, fin_) as next_day
					FROM w_histo_ser
					) sub
				WHERE 
					salarie_ = sal AND
					src = 1 AND
					debut_ = deb AND
					(fin_ = fin OR (fin_ IS NULL AND fin IS NULL)) AND
					service_ = ser AND
					heure_debut_periode_ = 0 AND
					next_day IS NOT NULL;

				--UPDATE w_histo_ser SET src = 1;

				-- insertion de prets
				
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
				SELECT 
					salarie_,
					debut_pret_,
					fin_pret_,
					0 as heure_debut_periode_,
					24 as heure_fin_periode_,
					service_,
					4
				FROM prod_kelio.pret_salarie
				;

				DELETE FROM w_histo_ser
				USING w_histo_ser ref
				WHERE 1=1 AND
					w_histo_ser.salarie_ = ref.salarie_ AND
					w_histo_ser.src != 4 AND
					ref.src = 4 AND
					w_histo_ser.debut_ between ref.debut_ AND ref.fin_ AND
					w_histo_ser.fin_ between ref.debut_ AND ref.fin_
					;
					
				-- ajout de la periodes supplementaires
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
				SELECT 
					w_histo_ser.salarie_,
					w_histo_ser.fin_ + interval '1 day',
					w_histo.fin_,
					0 as heure_debut_periode_,
					24 as heure_fin_periode_,
					w_histo.service_,
					5
				FROM w_histo_ser
					JOIN w_histo_ser w_histo ON 
						w_histo.salarie_ = w_histo_ser.salarie_ AND
						w_histo_ser.src = 4 AND
						w_histo.src != 4 AND 
						w_histo_ser.fin_ BETWEEN w_histo.debut_ AND w_histo.fin_ AND
						w_histo_ser.fin_ + interval '1 day' < w_histo.fin_
				GROUP BY 1,2,3,5,6,7
				;
				
				-- maj des dates de fin si overlap 
				UPDATE w_histo_ser
				SET
					fin_ = next - interval '1 day'
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, fin_) as next
					FROM w_histo_ser
					) sub
				WHERE 
					salarie_ = sal AND
					src = 5 AND
					debut_ = deb AND
					fin_ = fin AND
					service_ = ser AND
					heure_debut_periode_ = 0 AND
					next IS NOT NULL;


				DELETE FROM w_histo_ser
				USING w_histo_ser ref
				WHERE 1=1 AND
					w_histo_ser.salarie_ = ref.salarie_ AND
					w_histo_ser.src = 5 AND
					ref.src != 5 AND
					(w_histo_ser.debut_ = ref.debut_ AND
					w_histo_ser.fin_ = ref.fin_)
					;

					
				-- maj des dates de fin si overlap 
				UPDATE w_histo_ser
				SET
					fin_ = next_day - CASE WHEN next_hour = 0 THEN interval '1 day' ELSE interval '0 day' END,
					heure_fin_periode_ = CASE WHEN next_hour = 0 THEN 24 ELSE next_hour  END
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(heure_debut_periode_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_hour,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_day
					FROM w_histo_ser

					order by debut_ desc
					) sub
				WHERE 
					salarie_ = sal AND
					debut_ = deb AND
					fin_ = fin AND
					service_ = ser AND
					next_day IS NOT NULL;


				DELETE FROM w_histo_ser
				USING w_histo_ser ref
				WHERE 1=1 AND
					w_histo_ser.salarie_ = ref.salarie_ AND
					w_histo_ser.src = 5 AND
					ref.src != 5 AND
					w_histo_ser.debut_ = ref.debut_ AND
					w_histo_ser.fin_ = ref.fin_
					;

				DELETE FROM w_histo_ser
				WHERE 1=1 AND
					w_histo_ser.src = 5 AND
					fin_ < debut_
					;

				]]></sqlcmd>
			</NODE>
			<NODE label="Constitution planning">
				<sqlcmd><![CDATA[
				
				-- Maintenance table temporaire prod_kelio_affectation_horaire_journalier.
				VACUUM ANALYSE prod_kelio_affectation_horaire_journalier
				;

				CREATE INDEX prod_kelio_affectation_horaire_journalier_ik_salarie_ ON prod_kelio_affectation_horaire_journalier USING btree (salarie_)
				;

				-- Alimenter le champ prod_kelio_affectation_horaire_journalier.salarie_corr. cas avec SHS
				UPDATE prod_kelio_affectation_horaire_journalier SET
					salarie_corr = matricule_
				FROM prod_kelio_pers 
				WHERE prod_kelio_pers.personne_ = prod_kelio_affectation_horaire_journalier.salarie_
				;
				
				UPDATE prod_kelio_absence SET
					salarie_corr = matricule_
				FROM prod_kelio_pers 
				WHERE prod_kelio_pers.personne_ = prod_kelio_absence.salarie_
				;
				
				--UPDATE prod_kelio_affectation_horaire_journalier
				--		SET 
				--			debut = periode_travail.debut_/3600.0,
				--			fin =  periode_travail.fin_/3600.0,
				--			duree =  (periode_travail.fin_-periode_travail.debut_)/3600.0
				--FROM prod_kelio.periode_travail
				--WHERE periode_travail.affectation_horaire_journalie_ = prod_kelio_affectation_horaire_journalier.affectation_horaire_journalie_
				--AND (
				--prod_kelio_affectation_horaire_journalier.debut BETWEEN periode_travail.debut_/3600.0 AND periode_travail.fin_/3600.0
				-- OR periode_travail.debut_/3600.0 BETWEEN prod_kelio_affectation_horaire_journalier.debut AND  prod_kelio_affectation_horaire_journalier.fin
				-- ) 
				-- AND periodes_redefinies_ = 1;
				--
				--UPDATE prod_kelio_affectation_horaire_journalier
				--SET 
				--	debut = 0,
				--	fin = 0,
				--	duree = 0 
				--FROM (
				--	SELECT 
				--		affectation_horaire_journalie_, debut, fin, MAX(debut_th) AS debut_max 
				--		FROM prod_kelio_affectation_horaire_journalier GROUP BY 1,2,3
				--		HAVING count(*) > 1
				--		) sub
				--WHERE 
				--	prod_kelio_affectation_horaire_journalier.affectation_horaire_journalie_ = sub.affectation_horaire_journalie_
				--	AND debut_max = debut_th
				--;
				
				-- Recensement des salariés et établissements.
				DROP TABLE IF EXISTS w_sal_pla
				;
				CREATE TEMP TABLE w_sal_pla AS
					SELECT 
						p_salaries.oid AS salarie_id,
						p_salaries.matricule,
						t_entreprises.code_original AS entreprise_code_original,
						t_etablissements.code_original AS etablissement_code_original,
						t_entreprises.code AS entreprise_code,
						t_entreprises.planning_code AS entreprise_planning_code,
						t_etablissements.code AS etablissement_code,
						right(t_etablissements.code,3) as etablissement_planning_code, 
						''::text AS salarie_corr
					FROM rh.p_salaries
						-- Il faut absoluement faire le produit cartésien matricule/établissement même si un salarié n'a jamais travaillé dans un des établissement.
						-- En effet, cela pourrait être le cas dans gestor et ce traitement pourrait ne pas remonter les données associées.
						JOIN rh.t_entreprises ON t_entreprises.oid = p_salaries.entreprise_id
						JOIN rh.t_etablissements ON t_etablissements.entreprise_id = p_salaries.entreprise_id
					WHERE 1=1
						AND salarie_fusionne_id = 0
					GROUP BY 1,2,3,4,5,6,7,8,9
					ORDER BY 1,2,3
				;
			

				-- Alimenter le champ w_sal_pla.salarie_corr.
				UPDATE w_sal_pla SET
					salarie_corr = matricule;
					
				-- Création d'index.
				CREATE INDEX w_sal_pla_i_matricule          ON w_sal_pla USING btree (matricule)
				;

				DROP SEQUENCE IF EXISTS w_affectation_horaire_journalier_seq
				;
				
				CREATE TEMP SEQUENCE w_affectation_horaire_journalier_seq
				;

				DROP TABLE IF EXISTS w_affectation_horaire_journalier
				;

				-- consitution des compteurs heures travaillées en ommetant les pauses
				CREATE TEMP TABLE w_affectation_horaire_journalier AS
				SELECT
					nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
					 prod_kelio_affectation_horaire_journalier.salarie_corr,
					 null::bigint AS salarie_id,
					 null::bigint AS contrat_id,
					 null::bigint AS contrat_mois_id,
					 date(date_application_) AS date,
					debut,
					fin,
					debut_th,
					fin_th,
					pause_th,
					pause_deb_th,
					pause_fin_th,
					 codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
					 codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
					 libNiv2 AS entets_code,
					 ''::text AS abs_cod,
					CASE
						WHEN heure_debut_periode_ = 0 THEN duree_th - pause_th
						WHEN heure_debut_periode_ < fin_th THEN fin_th - heure_debut_periode_ - pause_th
						ELSE duree_th  - pause_th END AS temps_du_initial,
					CASE 
						WHEN heure_debut_periode_ = 0 THEN duree - pause
						WHEN heure_debut_periode_ < fin THEN fin - heure_debut_periode_ - pause
						ELSE duree  - pause END
					AS temps_du,
					 CASE 
						--WHEN theorique_applique_ = 1 AND heure_debut_periode_ = 0 THEN temps_theorique_/3600.0  - pause_th-- cas simple
						--WHEN theorique_applique_ = 1 AND heure_debut_periode_ < fin THEN fin_th- heure_debut_periode_/3600.0  - pause_th-- re affectation
						WHEN periodes_redefinies_ = 0 AND heure_debut_periode_ = 0 THEN duree_th - pause_th -- redefinition						
						WHEN periodes_redefinies_ = 0 AND heure_debut_periode_ < fin_th THEN fin_th- heure_debut_periode_/3600.0  - pause_th-- redefinition et reaff	
						WHEN periodes_redefinies_ = 1 AND heure_debut_periode_ = 0 THEN duree  - pause-- redefinition						
						WHEN periodes_redefinies_ = 1 AND heure_debut_periode_ < fin THEN fin- heure_debut_periode_/3600.0  - pause-- redefinition et reaff	
						ELSE duree  - pause END
					AS temps_valide,
					 0::numeric AS temps_absence
				FROM prod_kelio_affectation_horaire_journalier
					LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_affectation_horaire_journalier.salarie_ AND date_application_ BETWEEN w_histo_ser.debut_ AND w_histo_ser.fin_ 
					LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
				;

				-- absence en jours
				UPDATE w_affectation_horaire_journalier
				SET 
					abs_cod = abrege_,
					temps_absence = temps_valide * (CASE WHEN absence_date_debut_ = date THEN absence_commence_matin_ ELSE 1 END + CASE WHEN absence_date_fin_ = date THEN absence_termine_ap_midi_ ELSE 1 END) / 2,
					temps_valide = temps_valide - temps_valide * (CASE WHEN absence_date_debut_ = date THEN absence_commence_matin_ ELSE 1 END + CASE WHEN absence_date_fin_ = date THEN absence_termine_ap_midi_ ELSE 1 END) / 2
				FROM 
					prod_kelio_absence
				WHERE  1=1 AND
					prod_kelio_absence.salarie_corr = w_affectation_horaire_journalier.salarie_corr AND
					date BETWEEN absence_date_debut_ AND CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END AND
					absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0 AND  mode_cumul_ < 2 AND abrege_ != 'CA' AND
					temps_valide != 0 AND est_presence = 0
				;
				
				-- maj des jours d'absence avec présence
				UPDATE w_affectation_horaire_journalier
				SET 
					abs_cod = abrege_
				FROM 
					prod_kelio_absence
				WHERE  1=1 AND
					prod_kelio_absence.salarie_corr = w_affectation_horaire_journalier.salarie_corr AND
					date BETWEEN absence_date_debut_ AND CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END AND
					absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0 AND  mode_cumul_ = 2 AND
					temps_valide != 0 AND est_presence = 1
				;

				-- suppression des hoarires travaillés restants correspondant aux absences en jours
				DELETE FROM  w_affectation_horaire_journalier
				USING
					prod_kelio_absence
				WHERE  1=1 AND
					prod_kelio_absence.salarie_corr = w_affectation_horaire_journalier.salarie_corr AND
					date BETWEEN absence_date_debut_ AND CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END AND
					absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0 AND  (mode_cumul_ = 2 OR abrege_ = 'CA') AND 
					temps_valide != 0 AND est_presence = 0
				;
				
				--nettoyage des horaires vides
				DELETE FROM  w_affectation_horaire_journalier
				WHERE  1=1 AND
					COALESCE(temps_du,0) = 0 AND
					COALESCE(temps_du_initial,0) = 0 AND
					COALESCE(temps_valide,0) = 0 AND
					COALESCE(temps_absence,0) = 0 ;
				
				
				-- absences en heures
				DROP TABLE IF EXISTS w_abs_h;
				CREATE TEMP TABLE w_abs_h AS
					SELECT 
						affectation_horaire_journalier_id,
						abrege_,
						libelle_,
						absence_duree_abs_heures_, -- pause_th AS absence_duree_abs_heures_,
						absence_heure_deb1_,
						absence_heure_deb2_,
						absence_heure_fin1_,
						absence_heure_fin2_,
						pause_deb_th,
						pause_fin_th,
						SUM(temps_valide) OVER (PARTITION BY prod_kelio_absence.salarie_corr,date ORDER by date,absence_heure_deb1_,affectation_horaire_journalier_id) as somme,
						CASE 
							WHEN heure_debut_periode_ = 0 OR heure_debut_periode_ IS NULL THEN
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN (least(absence_heure_fin2_,fin*3600) - absence_heure_deb2_)/3600.0 + (least(absence_heure_fin1_,fin*3600) - absence_heure_deb1_)/3600.0 
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0)
										 OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0)))
										 AND absence_heure_deb1_ < fin_th			
										 AND rank() OVER (PARTITION BY prod_kelio_absence.salarie_corr,date,abrege_,absence_heure_deb1_ ORDER by date,absence_heure_deb1_,affectation_horaire_journalier_id) = 1 THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_
									ELSE 0 END
							ELSE 
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN 
										CASE WHEN heure_debut_periode_ < absence_heure_fin1_ THEN (least(absence_heure_fin1_,fin*3600) - absence_heure_deb1_)/3600.0 ELSE 0 END
										+ CASE WHEN heure_debut_periode_ < absence_heure_fin2_ AND heure_debut_periode_ > absence_heure_fin1_ THEN (least(absence_heure_fin2_,fin*3600) - absence_heure_deb2_)/3600.0 ELSE 0 END
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0
										AND pause_deb_th < absence_heure_fin2_/3600.0))) AND absence_heure_deb1_ < fin_th
										AND rank() OVER (PARTITION BY prod_kelio_absence.salarie_corr,date,abrege_,absence_heure_deb1_ ORDER by date,absence_heure_deb1_,affectation_horaire_journalier_id) = 1 
										THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_ -- répartition tres tres tres basique et dangeureuse si plusieurs plages horaires 
									ELSE 0 END
							END
							+ temps_valide - SUM(temps_valide) OVER (PARTITION BY prod_kelio_absence.salarie_corr,date,abrege_,absence_heure_deb1_ ORDER by date,absence_heure_deb1_,affectation_horaire_journalier_id) as restant,
							est_presence
					FROM prod_kelio_absence
						JOIN w_affectation_horaire_journalier ON w_affectation_horaire_journalier.salarie_corr = prod_kelio_absence.salarie_corr
							AND date BETWEEN absence_date_debut_ AND 
								CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
								AND ((absence_heure_fin1_/3600.0 > debut AND absence_heure_deb1_/3600.0< fin) OR (absence_heure_fin2_/3600.0 > debut AND absence_heure_deb2_/3600.0< fin))
						LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_absence.salarie_ AND date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
						LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
					WHERE NOT(absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0) --OR (absence_commence_matin_ + absence_termine_ap_midi_) != 2
				;

				--modification des horaires travaillés par les absences en heures
					UPDATE w_affectation_horaire_journalier	
				SET
					temps_du = temps_du - LEAST(temps_du,restant),
					temps_valide = temps_valide - LEAST(temps_valide,restant)
				FROM 
				(SELECT 
					affectation_horaire_journalier_id,
					SUM(restant) AS restant
					FROM w_abs_h
					GROUP BY 1 
					HAVING COUNT(*) = 1
					) w_abs_h
				WHERE
					w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_abs_h.affectation_horaire_journalier_id
					--and est_presence = 0
				;

				UPDATE w_affectation_horaire_journalier	
				SET
					temps_du = temps_du - LEAST(temps_du,restant),
					temps_valide = temps_valide - LEAST(temps_valide,restant)
				FROM 
				(SELECT 
					affectation_horaire_journalier_id,
					SUM(restant) AS restant
					FROM w_abs_h
					GROUP BY 1 
					HAVING COUNT(*) > 1
					) w_abs_h
				WHERE
					w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_abs_h.affectation_horaire_journalier_id
					--and est_presence = 0
				;
			  
				--modification des horaires travaillés par les absences en heures
			--	UPDATE w_affectation_horaire_journalier	
			--	SET
			--		abs_code = abrege_,
			--		temps_du = GREATEST(temps_du,restant),
			--		temps_valide = temps_valide - GREATEST(temps_valide,restant)
			--	FROM 
			--		w_abs_h
			--	WHERE
			--		w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_abs_h.affectation_horaire_journalier_id
			--		AND est_presence = 1 and mode_cumul_ = 2
			--	;
			  
				-- insetion des absences en heures celles sans horaire 
				  INSERT INTO w_affectation_horaire_journalier
					 SELECT
					   nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
						prod_kelio_absence.salarie_corr,
						null::bigint AS salarie_id,
						null::bigint AS contrat_id,
						null::bigint AS contrat_mois_id,
						COALESCE(date(date_application_), p_calendrier.date) AS date,
						debut,
						fin,
						debut_th,
						fin_th,
						pause_th,
						pause_deb_th,
						pause_fin_th,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
						libNiv2 AS entets_code,
						abrege_ AS abs_cod,
						0 AS temps_du_initial,
						CASE 
							WHEN heure_debut_periode_ = 0 OR heure_debut_periode_ IS NULL THEN
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 + (absence_heure_fin1_ - absence_heure_deb1_)/3600.0
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_
									ELSE duree_th - pause_th END
							ELSE 
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN 
										CASE WHEN heure_debut_periode_ < absence_heure_fin1_ THEN (absence_heure_fin1_ - absence_heure_deb1_)/3600.0 ELSE 0 END
										+ CASE WHEN heure_debut_periode_ < absence_heure_fin2_ AND heure_debut_periode_ > absence_heure_fin1_ THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 ELSE 0 END
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_ -- répartition tres tres tres basique et dangeureuse
									ELSE heure_fin_periode_ - heure_debut_periode_ END
							END AS temps_du,
						CASE WHEN est_presence = 1 THEN CASE 
							WHEN heure_debut_periode_ = 0 OR heure_debut_periode_ IS NULL THEN
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 + (absence_heure_fin1_ - absence_heure_deb1_)/3600.0
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_
									ELSE duree_th END
							ELSE 
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN 
										CASE WHEN heure_debut_periode_ < absence_heure_fin1_ THEN (absence_heure_fin1_ - absence_heure_deb1_)/3600.0 ELSE 0 END
										+ CASE WHEN heure_debut_periode_ < absence_heure_fin2_ AND heure_debut_periode_ > absence_heure_fin1_ THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 ELSE 0 END
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_ -- répartition tres tres tres basique et dangeureuse
									ELSE heure_fin_periode_ - heure_debut_periode_ END
							END ELSE 0 END AS temps_valide,
						CASE WHEN est_presence = 0 THEN CASE 
							WHEN heure_debut_periode_ = 0 OR heure_debut_periode_ IS NULL THEN
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 + (absence_heure_fin1_ - absence_heure_deb1_)/3600.0
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_
									ELSE duree_th END
							ELSE 
								CASE 
									WHEN absence_heure_deb1_ != 0 THEN 
										CASE WHEN heure_debut_periode_ < absence_heure_fin1_ THEN (absence_heure_fin1_ - absence_heure_deb1_)/3600.0 ELSE 0 END
										+ CASE WHEN heure_debut_periode_ < absence_heure_fin2_ AND heure_debut_periode_ > absence_heure_fin1_ THEN (absence_heure_fin2_ - absence_heure_deb2_)/3600.0 ELSE 0 END
										- CASE WHEN (pause_deb_th IS NOT NULL AND ((pause_fin_th > absence_heure_deb1_/3600.0 AND pause_deb_th < absence_heure_fin1_/3600.0) OR (pause_fin_th > absence_heure_deb2_/3600.0 AND pause_deb_th < absence_heure_fin2_/3600.0))) THEN pause_th ELSE 0 END
									WHEN absence_duree_abs_heures_ > 0 THEN absence_duree_abs_heures_ -- répartition tres tres tres basique et dangeureuse
									ELSE heure_fin_periode_ - heure_debut_periode_ END
							END ELSE 0 END
						AS temps_absence
					FROM prod_kelio_absence
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN absence_date_debut_ AND 
								CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
						LEFT JOIN prod_kelio_affectation_horaire_journalier ON prod_kelio_affectation_horaire_journalier.salarie_ = prod_kelio_absence.salarie_
							AND prod_kelio_affectation_horaire_journalier.date_application_ BETWEEN absence_date_debut_ AND 
								CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
								AND ((absence_heure_fin1_ > 0 AND (absence_heure_fin1_/3600.0 > debut AND absence_heure_deb1_/3600.0< fin))
								 OR (absence_heure_fin2_ > 0 AND (absence_heure_fin2_/3600.0 > debut AND absence_heure_deb2_/3600.0< fin)))
						LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_absence.salarie_ AND COALESCE(date_application_,p_calendrier.date) BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
						LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
					WHERE mode_cumul_ < 2 AND NOT(absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0)  -- prise en charge au niveau du jour
				;
				
				-- absence sans affectation d'horaire en jours ou sans code d'absence dans Kelio 
				INSERT INTO w_affectation_horaire_journalier
				SELECT
					   nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
						employee_identification_number,
						null::bigint AS salarie_id,
						null::bigint AS contrat_id,
						null::bigint AS contrat_mois_id,
						COALESCE(w_affectation_horaire_journalier.date, total_date) AS date,
						debut,
						fin,
						debut_th,
						fin_th,
						pause_th,
						pause_deb_th,
						pause_fin_th,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
						libNiv2 AS entets_code,
						abs_type_abbreviation AS abs_cod,
						0 AS temps_du_initial,
						hours AS temps_du,
						CASE WHEN COALESCE(est_presence,0) = 1 THEN hours ELSE 0 END AS temps_valide,
						CASE WHEN COALESCE(est_presence,0) != 1 THEN hours ELSE 0 END AS temps_absence
					 FROM prod_keliod.estimated_daily_absence
						LEFT JOIN w_affectation_horaire_journalier ON
							total_date = date
							AND w_affectation_horaire_journalier.salarie_corr = employee_identification_number
						--LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = estimated_daily_absence.section_key
						LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = employee_key AND total_date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
						LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
						LEFT JOIN (
						SELECT CASE WHEN to_id IS NOT NULL THEN 1 ELSE 0 END AS est_presence, t_planning_type_absence.code FROM 
							rh.t_listes JOIN rh.t_listes_contenu ON liste_id = t_listes.oid
							JOIN rh.t_planning_type_absence ON to_id = t_planning_type_absence.oid
						WHERE
							t_listes.code = 'CTI_ABS_TRAVAILLEES'
					) sub ON sub.code = abs_type_abbreviation
					WHERE (w_affectation_horaire_journalier.date IS NULL OR COALESCE(abs_cod, '') != abs_type_abbreviation)
						AND (TOTAL_DATE != ALL (ARRAY(SELECT DISTINCT date_application_ FROM prod_kelio.jour_ferie)::date[]) OR est_presence = 1)
				;

				--INSERT INTO w_affectation_horaire_journalier
				--SELECT
				--       nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
				--        prod_kelio_absence.salarie_corr,
				--        null::bigint AS salarie_id,
				--        null::bigint AS contrat_id,
				--        null::bigint AS contrat_mois_id,
				--        COALESCE(w_affectation_horaire_journalier.date, p_calendrier.date) AS date,
				--		debut,
				--		fin,
				--		debut_th,
				--		fin_th,
				--		pause_th,
				--		pause_deb_th,
				--		pause_fin_th,
				--        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
				--        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
				--        libNiv2 AS entets_code,
				--        abrege_ AS abs_cod,
				--        (tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END) AS temps_du_initial,
				--		(tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END) AS temps_du,
				--        0 AS temps_valide,
				--		(tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END)  AS temps_absence
				--	FROM prod_kelio_absence
				--		JOIN base.p_calendrier ON p_calendrier.date BETWEEN absence_date_debut_ AND 
				--			CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
				--		JOIN base.v_calendrier_indicateurs_1 ON v_calendrier_indicateurs_1.date = p_calendrier.date
				--		LEFT JOIN w_affectation_horaire_journalier ON
				--			CASE WHEN mode_cumul_ = 2 THEN p_calendrier.date = w_affectation_horaire_journalier.date
				--			ELSE w_affectation_horaire_journalier.date BETWEEN absence_date_debut_ AND 
				--			CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
				--			END
				--			AND w_affectation_horaire_journalier.salarie_corr = prod_kelio_absence.salarie_corr
				--		LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_absence.salarie_ AND p_calendrier.date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
				--		LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
				--		JOIN prod_kelio.affectation_duree_travail ON salarie_g_t_p_ = prod_kelio_absence.salarie_ and p_calendrier.date BETWEEN affectation_duree_travail.date_debut_ AND COALESCE(affectation_duree_travail.date_fin_,'2099-12-31')
				--		LEFT JOIN prod_keliod.SCHEDULE_ASSIGNMENT ON employee_identification_number = prod_kelio_absence.salarie_corr
				--			AND p_calendrier.date BETWEEN assignment_date and assignment_end_date
				--		LEFT JOIN ( 
				--			SELECT 
				--				schedule_abbreviation AS tx_code,
				--				replace(split_part(regexp_replace(regexp_replace(schedule_description,'[^0-9\.%]','','g'),'[0-9\.]*%([0-9\.]*)%$','\1'),'%',1),'..','')::numeric AS tx_temps
				--			FROM 
				--				prod_keliod.SCHEDULE_ASSIGNMENT GROUP BY 1,2) sub ON tx_code = schedule_abbreviation
				--	WHERE absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0 AND w_affectation_horaire_journalier.date IS NULL AND mode_cumul_ < 2
				--	
				--;
				--
				--INSERT INTO w_affectation_horaire_journalier
				--SELECT
				--       nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
				--        prod_kelio_absence.salarie_corr,
				--        null::bigint AS salarie_id,
				--        null::bigint AS contrat_id,
				--        null::bigint AS contrat_mois_id,
				--        p_calendrier.date AS date,
				--		0 AS debut,
				--		0 AS fin,
				--		0 AS debut_th,
				--		0 AS fin_th,
				--		0 AS pause_th,
				--		0 AS pause_deb_th,
				--		0 AS pause_fin_th,
				--        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
				--        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
				--        libNiv2 AS entets_code,
				--        abrege_ AS abs_cod,
				--        (tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END) AS temps_du_initial,
				--		(tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END) AS temps_du,
				--        0 AS temps_valide,
				--		(tx_temps / 100.0) * (CASE 
				--			WHEN mode_cumul_ < 2 AND nb_jour_ouvre = 1 THEN base_horaire_ / (5 * 3600.0)
				--			WHEN mode_cumul_ = 2 THEN base_horaire_ / (7 * 3600.0)
				--			ELSE 0 END)  AS temps_absence
				--	FROM prod_kelio_absence
				--		JOIN base.p_calendrier ON p_calendrier.date BETWEEN absence_date_debut_ AND 
				--			CASE WHEN absence_date_fin_ IS NOT NULL THEN absence_date_fin_ ELSE absence_date_debut_ + (absence_nbre_jours_abs_ || 'days')::interval END
				--		JOIN base.v_calendrier_indicateurs_1 ON v_calendrier_indicateurs_1.date = p_calendrier.date
				--		LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_absence.salarie_ AND p_calendrier.date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
				--		LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
				--		JOIN prod_kelio.affectation_duree_travail ON salarie_g_t_p_ = prod_kelio_absence.salarie_ and p_calendrier.date BETWEEN affectation_duree_travail.date_debut_ AND COALESCE(affectation_duree_travail.date_fin_,'2099-12-31')
				--		LEFT JOIN prod_keliod.SCHEDULE_ASSIGNMENT ON employee_identification_number = prod_kelio_absence.salarie_corr
				--			AND p_calendrier.date BETWEEN assignment_date and assignment_end_date
				--		LEFT JOIN ( 
				--			SELECT 
				--				schedule_abbreviation AS tx_code,
				--				replace(split_part(regexp_replace(regexp_replace(schedule_description,'[^0-9\.%]','','g'),'[0-9\.]*%([0-9\.]*)%$','\1'),'%',1),'..','')::numeric AS tx_temps
				--			FROM 
				--				prod_keliod.SCHEDULE_ASSIGNMENT GROUP BY 1,2) sub ON tx_code = schedule_abbreviation
				--	WHERE absence_heure_fin1_ = 0 AND absence_duree_abs_heures_ = 0 AND mode_cumul_ = 2
					
				;
				-- ajout des heures spéciales (pour l'instant heures de pause annulées)
				INSERT INTO w_affectation_horaire_journalier
					   SELECT
					   nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
						employee_identification_number,
						null::bigint AS salarie_id,
						null::bigint AS contrat_id,
						null::bigint AS contrat_mois_id,
						total_date AS date,
						0,
						0,
						0,
						0,
						0,
						0,
						0,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
						codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
						libNiv2 AS entets_code,
						special_hour_type_abbreviation AS abs_cod,
						0 AS temps_du_initial,
						hours AS temps_du,
						hours AS temps_valide,
						0 AS temps_absence
					FROM prod_keliod.ESTIMATED_DAILY_SPEC_HOUR
						--LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.code_original = ESTIMATED_DAILY_SPEC_HOUR.section_key
						LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = employee_key AND total_date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_ 
						LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
					WHERE 
						special_hour_type_abbreviation = 'NBHPA'
				;

                -- Ajout des jours d'absence "blanc" (pas de theorique ni de temps d'absence; typiquement les jours fériés; permet de compter correctement le nombre de jours d'absence).
                INSERT INTO w_affectation_horaire_journalier
                    SELECT
                        nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
                        prod_kelio_absence.salarie_corr  as employee_identification_number,
                        null::bigint AS salarie_id,
                        null::bigint AS contrat_id,
                        null::bigint AS contrat_mois_id,
                        cal.date AS date,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
                        codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
                        libNiv2 AS entets_code,
                        abrege_ AS abs_cod,
                        0 AS temps_du_initial,
                        0 AS temps_du,
                        0 AS temps_valide,
                        0 AS temps_absence
                    from prod_kelio_absence
                        join base.p_calendrier as cal on cal.date between prod_kelio_absence.absence_date_debut_ and prod_kelio_absence.absence_date_fin_
                        left join  w_affectation_horaire_journalier  on true
                            and w_affectation_horaire_journalier.salarie_corr = prod_kelio_absence.salarie_corr
                            and w_affectation_horaire_journalier.date = cal.date
                            LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_absence.salarie_ AND cal.date BETWEEN w_histo_ser.debut_ and w_histo_ser.fin_
                            LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
                    where true
                        and w_affectation_horaire_journalier.date is null
                ;
				
				DROP TABLE IF EXISTS w_ser;
				CREATE TEMP TABLE w_ser AS 
				SELECT
					codeNiv1 || '|' || codeNiv2 || '|' || code_original AS service_code_original,
					codeNiv1,
					codeNiv2,
					codeNiv3,
					libNiv1 as niv_cod1,
					libNiv2 AS niv_cod2,
					codeniv3 AS niv_cod3,
					libNiv1 || '-' || libNiv2 || '-' || libniv3 AS texte,
					libNiv1 || '-' || libNiv2 || '-' || libniv3 AS texte_court
				FROM
					prod_kelio_organigramme
				
				;
				
				INSERT INTO rh.t_planning_type_absence(code_original, code, texte, texte_court)
					SELECT
						special_hour_type_key,
						special_hour_type_abbreviation,
						special_hour_type_description,
						substr(special_hour_type_description,1,50)
					FROM prod_keliod.ESTIMATED_DAILY_SPEC_HOUR
					WHERE 1=1
						AND special_hour_type_abbreviation IN (SELECT abs_cod FROM w_affectation_horaire_journalier)
						AND special_hour_type_key NOT IN (SELECT code_original FROM rh.t_planning_type_absence WHERE code_original IS NOT NULL)
					GROUP BY 1,2,3,4
				;
				
				]]></sqlcmd>
			</NODE>
		</NODE>


		<NODE label="Kelio type Gaston metivet">
			<condition><![CDATA[
				SELECT 1=1
				FROM information_schema.tables
				WHERE table_name = 'horaire_journalier_base'
				AND table_schema = 'prod_kelio'
				-- avec base, ventilation par activite et table resulats utilisable pour indicateurs
				;
            ]]></condition>
			<NODE label="Préparation des affectation">
				<sqlcmd><![CDATA[

				-- Technique : reconstitution d'une table d'ajustement en partant des horaire et en modulant par la planification et les jours fériés pour obtenir le réalisé
				DROP TABLE IF EXISTS prod_kelio_affectation_horaire_journalier
				;
				CREATE TEMP TABLE prod_kelio_affectation_horaire_journalier AS
				 SELECT
					resultats_,
					periode_travail.horaire_journalier_,
					calcule_horairehoraire_journal,
					date_ as date_application_,
					resultats.salarie_,
				false AS plage_updated,
				periode_travail.debut_/3600.0  AS debut_th,
				periode_travail.fin_/3600.0   as fin_th,
				(periode_travail.fin_-periode_travail.debut_)/3600.0   AS duree_th,
				0 as debut,--periode_realise.debut_/3600.0  AS debut,
				0 as fin,--periode_realise.fin_/3600.0  AS fin,
				0 as duree,--(periode_realise.fin_-periode_realise.debut_)/3600.0  As duree,
				COALESCE(-dh_3,0)/3600.0 AS pause_th,
				COALESCE(h72_1,0)/3600.0 AS pause_deb_th,
				COALESCE(dh_2,0)/3600.0 AS pause_fin_th,
				ferie,
				jour_travaille_,
				''::text AS salarie_corr
				FROM  prod_kelio.resultats 
				LEFT JOIN prod_kelio.periode_travail ON calcule_horairehor_jour_prevu = periode_travail.horaire_journalier_
				--LEFT JOIN prod_kelio.periode_travail periode_realise ON calcule_horairehoraire_journal = periode_realise.horaire_journalier_
				LEFT JOIN prod_kelio.plage_horaire ON calcule_horairehor_jour_prevu = plage_horaire.horaire_journalier_ 
							AND plage_horaire.dh_3 < 0
							AND groupe_ = 1
				LEFT JOIN (
					SELECT distinct date_application_ AS ferie FROM prod_kelio.jour_ferie) feries ON ferie = date_
				LEFT JOIN prod_kelio.jour_ferie ON resultats.salarie_ = jour_ferie.salarie_ 
					AND jour_ferie.date_application_ = resultats.date_
				WHERE 1=1
					AND type_calcul_ = 2
					AND date_ > '2015-01-01'
					--AND (ferie IS NULL OR (ferie IS NOT NULL AND jour_travaille_ = 1))
			--	AND (periode_realise.debut_ IS NULL OR (periode_realise.debut_ BETWEEN periode_travail.debut_ AND periode_travail.fin_
			--	 OR periode_travail.debut_ BETWEEN periode_realise.debut_ AND  periode_realise.fin_
			--	))
				;
			
				UPDATE prod_kelio_affectation_horaire_journalier
				SET 
					debut_th = 9,
					fin_th = 17,
					duree_th = 8,
					pause_th = 1,
					pause_deb_th = 12,
					pause_fin_th = 13
				WHERE
					horaire_journalier_ = 35
				;
					
				UPDATE prod_kelio_affectation_horaire_journalier
				SET 
					debut = 9,
					fin = 17,
					duree = 8
				WHERE
					calcule_horairehoraire_journal = 35
				;	
				]]></sqlcmd>
			</NODE>
			<NODE label="Préparation des données">
				<sqlcmd><![CDATA[
			
		
				 -- Alimenter le champ prod_kelio_affectation_horaire_journalier.salarie_corr. cas avec SHS
				UPDATE prod_kelio_affectation_horaire_journalier SET
					salarie_corr = matricule_
				FROM prod_kelio_pers 
				WHERE prod_kelio_pers.personne_ = prod_kelio_affectation_horaire_journalier.salarie_
				;
				
				-- reconstitution de l'organigramme
				DROP TABLE IF EXISTS prod_kelio_organigramme
				;
				CREATE TEMP TABLE prod_kelio_organigramme AS
					SELECT 
						organigramme.organigramme_ AS service_,
						organigramme.organigramme_ AS code_original,
						COALESCE(code_, organigramme.organigramme_::text) AS codeNiv3, 
						organigramme.libelle_ AS libNiv3, 
						niv2.organigramme_ AS codeNiv2,
						niv2.libelle_ AS libNiv2,
						niv1.organigramme_ AS codeNiv1,
						niv1.libelle_ AS libNiv1
					FROM prod_kelio.organigramme 
						LEFT JOIN (SELECT service_, centre_de_charge_ FROM prod_kelio.activite_par_defaut GROUP BY 1,2) sub ON sub.service_ = organigramme_
						JOIN prod_kelio.organigramme niv2 ON organigramme.parent_ = niv2.organigramme_
						JOIN prod_kelio.organigramme niv1 ON niv2.parent_ = niv1.organigramme_
						LEFT JOIN prod_kelio.motif_calcul ON motif_calcul.libelle_ = organigramme.libelle_
						ORDER BY organigramme.organigramme_
				;
				
				
				DROP TABLE IF EXISTS w_histo_ser;
				 CREATE TEMP TABLE w_histo_ser AS 
					SELECT
					salarie_,
					date_debut_::date as debut_,
					(CASE WHEN date_fin_ = '0' THEN '2099-12-31' ELSE date_fin_ END)::date as fin_,
					0 AS heure_debut_periode_,
					24 AS heure_fin_periode_,
					activite_ as service_,
					''::text AS niv_cod1,
					''::text AS niv_cod2,
					''::text AS niv_cod3,
					''::text AS niv_cod4,
					''::text AS niv_cod5,
					1 AS src
				FROM prod_kelio.activite_par_defaut
				GROUP BY 1,2,3,4,5,6,7
				;

				-- maj des dates de fin si overlap 
				
				UPDATE w_histo_ser
				SET fin_ = w_histo_ser_ref.debut_::date - '1 day'::interval 
				FROM w_histo_ser w_histo_ser_ref
				WHERE w_histo_ser.salarie_ = w_histo_ser_ref.salarie_ AND w_histo_ser_ref.debut_ between w_histo_ser.debut_ AND w_histo_ser.fin_ AND 
				(w_histo_ser.debut_ != w_histo_ser_ref.debut_ OR w_histo_ser.fin_ != w_histo_ser_ref.fin_) AND
					 w_histo_ser.fin_ != w_histo_ser.debut_
				;

		
				-- ajout de la periodes supplementaires
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
					SELECT 
					affectation_activite.salarie_,
					affectation_activite.jour_::date,
					affectation_activite.jour_::date,
					0 as heure_debut_periode_,
					24 as heure_fin_periode_,
					affectation_activite.activite_,
					2 as src
				FROM prod_kelio.affectation_activite
					JOIN w_histo_ser ON 
						affectation_activite.salarie_ = w_histo_ser.salarie_ AND
						affectation_activite.jour_ BETWEEN w_histo_ser.debut_ AND w_histo_ser.fin_
						--and w_histo_ser.salarie_ = 4181 
				GROUP BY 1,2,3,5,6,7
				;

				UPDATE w_histo_ser
				SET
					fin_ = next_day::date - CASE WHEN next_hour = 0 THEN interval '1 day' ELSE interval '0 day' END,
					heure_fin_periode_ = CASE WHEN next_hour = 0 THEN 24 ELSE next_hour END
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(heure_debut_periode_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_hour,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, heure_debut_periode_) as next_day
					FROM w_histo_ser
					) sub
				WHERE 
					salarie_ = sal AND
					debut_ = deb AND
					fin_ = fin AND
					service_ = ser AND
					next_day IS NOT NULL;

						-- ajout de la periodes supplementaires
				INSERT INTO w_histo_ser (salarie_, debut_, fin_, heure_debut_periode_, heure_fin_periode_, service_, src)
				SELECT 
					w_histo_ser.salarie_,
					w_histo_ser.fin_ + interval '1 day',
					w_histo.fin_,
					0 as heure_debut_periode_,
					24 as heure_fin_periode_,
					w_histo.service_,
					3
				FROM w_histo_ser
					JOIN w_histo_ser w_histo ON 
						w_histo.salarie_ = w_histo_ser.salarie_ AND
						w_histo_ser.src = 2 AND
						w_histo.src != 2 AND 
						w_histo_ser.fin_ BETWEEN w_histo.debut_ AND w_histo.fin_
				GROUP BY 1,2,3,5,6,7
				;


				
				-- maj des dates de fin si overlap 
				UPDATE w_histo_ser
				SET
					fin_ = next - interval '1 day'
				FROM (
					SELECT
						salarie_ AS sal,
						debut_ AS deb,
						fin_ AS fin,
						service_ AS ser,
						lead(debut_) OVER (PARTITION BY salarie_ ORDER BY debut_, fin_) as next
					FROM w_histo_ser
					) sub
				WHERE 
					salarie_ = sal AND
					src = 1 AND
					debut_ = deb AND
					fin_ = fin AND
					service_ = ser AND
					heure_debut_periode_ = 0 AND
					next IS NOT NULL;


					-- reconstitution de l'organigramme
				DROP TABLE IF EXISTS prod_kelio_organigramme
				;
				CREATE TEMP TABLE prod_kelio_organigramme AS
					SELECT 
						service_,
						service_ AS code_original,
						code_ AS codeNiv3, 
						'' AS libNiv3, 
						'' AS codeNiv2,
						'' AS libNiv2,
						'' AS codeNiv1,
						libelle_ AS libNiv1
					FROM w_histo_ser
						LEFT JOIN prod_kelio.motif_calcul ON motif_calcul.motif_calcul_ = w_histo_ser.service_
						GROUP BY 1,2,3,4,5,6,7,8
						ORDER BY code_
				;
				]]></sqlcmd>
			</NODE>
			<NODE label="Constitution planning">
				<sqlcmd><![CDATA[
				
				-- Maintenance table temporaire prod_kelio_affectation_horaire_journalier.
				VACUUM ANALYSE prod_kelio_affectation_horaire_journalier
				;

				CREATE INDEX prod_kelio_affectation_horaire_journalier_ik_salarie_ ON prod_kelio_affectation_horaire_journalier USING btree (salarie_)
				;
				
				UPDATE prod_kelio_absence SET
					salarie_corr = matricule_
				FROM prod_kelio_pers 
				WHERE prod_kelio_pers.personne_ = prod_kelio_absence.salarie_
				;
								
				-- Recensement des salariés et établissements.
				DROP TABLE IF EXISTS w_sal_pla
				;
				CREATE TEMP TABLE w_sal_pla AS
					SELECT 
						p_salaries.oid AS salarie_id,
						p_salaries.matricule,
						t_entreprises.code_original AS entreprise_code_original,
						t_etablissements.code_original AS etablissement_code_original,
						t_entreprises.code AS entreprise_code,
						t_entreprises.planning_code AS entreprise_planning_code,
						t_etablissements.code AS etablissement_code,
						right(t_etablissements.code,3) as etablissement_planning_code, 
						''::text AS salarie_corr
					FROM rh.p_salaries
						-- Il faut absoluement faire le produit cartésien matricule/établissement même si un salarié n'a jamais travaillé dans un des établissement.
						-- En effet, cela pourrait être le cas dans gestor et ce traitement pourrait ne pas remonter les données associées.
						JOIN rh.t_entreprises ON t_entreprises.oid = p_salaries.entreprise_id
						JOIN rh.t_etablissements ON t_etablissements.entreprise_id = p_salaries.entreprise_id
					WHERE 1=1
						AND salarie_fusionne_id = 0
					GROUP BY 1,2,3,4,5,6,7,8,9
					ORDER BY 1,2,3
				;
			
				-- Alimenter le champ w_sal_pla.salarie_corr.
				UPDATE w_sal_pla SET
					salarie_corr = matricule;
					
				-- Création d'index.
				CREATE INDEX w_sal_pla_i_matricule          ON w_sal_pla USING btree (matricule)
				;

				DROP SEQUENCE IF EXISTS w_affectation_horaire_journalier_seq
				;
				
				CREATE TEMP SEQUENCE w_affectation_horaire_journalier_seq
				;

				DROP TABLE IF EXISTS w_affectation_horaire_journalier
				;

				-- consitution des compteurs heures travaillées en ommetant les pauses
				CREATE TEMP TABLE w_affectation_horaire_journalier AS
				SELECT
					nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
					 prod_kelio_affectation_horaire_journalier.salarie_corr,
					 null::bigint AS salarie_id,
					 null::bigint AS contrat_id,
					 null::bigint AS contrat_mois_id,
					 date(date_application_) AS date,
					debut,
					fin,
					debut_th,
					fin_th,
					pause_th,
					pause_deb_th,
					pause_fin_th,
					codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
					codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
					libNiv2 AS entets_code,
					''::text AS motif_,
					''::text AS abs_cod,
					duree_th  - pause_th AS temps_du_initial,
					CASE
						WHEN 1=1 or  horaire_journalier_ != 35 THEN heures_jour_/3600.0
						--WHEN heure_debut_periode_ = 0 THEN duree - pause_th
						--WHEN heure_debut_periode_ < fin_ THEN fin - heure_debut_periode_ - pause_th
						ELSE duree  - pause_th END
					AS temps_du,
					duree  - pause_th AS temps_valide,
					CALCULE_ACTIVITE.heures_jour_/3600.0 as temps_effectif,
					0::numeric as temps_absences,
					0::numeric AS temps_absence,
					 ferie,
					 jour_travaille_
				FROM prod_kelio_affectation_horaire_journalier
					LEFT JOIN prod_kelio.CALCULE_ACTIVITE ON prod_kelio_affectation_horaire_journalier.resultats_ = CALCULE_ACTIVITE.resultats_ 
					LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = CALCULE_ACTIVITE.motif_
				;

			
				-- insetion des absences en heures celles sans horaire 
				  INSERT INTO w_affectation_horaire_journalier
					 SELECT
					  nextval('w_affectation_horaire_journalier_seq') as affectation_horaire_journalier_id,
					 prod_kelio_affectation_horaire_journalier.salarie_corr,
					 null::bigint AS salarie_id,
					 null::bigint AS contrat_id,
					 null::bigint AS contrat_mois_id,
					 date(date_application_) AS date,
					debut,
					fin,
					debut_th,
					fin_th,
					pause_th,
					pause_deb_th,
					pause_fin_th,
					codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS niveaux_code_original,
					codeNiv1 || '|' || codeNiv2 || '|' || prod_kelio_organigramme.service_ AS service_code_original,
					libNiv2 AS entets_code,
					''::text AS motif_,
					abrege_ AS abs_cod,
					0 AS temps_du_initial,
					heures_jour_/3600.0 AS temps_du,
					0 AS temps_valide,
					0 AS temps_effectif,
					heures_jour_/3600.0 AS temps_absences,
					0,
					0,
					0
					FROM prod_kelio_affectation_horaire_journalier
					JOIN prod_kelio.CALCULE_ABSENCE ON prod_kelio_affectation_horaire_journalier.resultats_ = CALCULE_ABSENCE.resultats_  AND heures_jour_ != 0 AND heures_jour_ IS NOT NULL
					LEFT JOIN prod_kelio.motif_calcul ON motif_ = motif_calcul_
					LEFT JOIN w_histo_ser ON w_histo_ser.salarie_ = prod_kelio_affectation_horaire_journalier.salarie_ AND date_application_ BETWEEN w_histo_ser.debut_ AND w_histo_ser.fin_ 
					LEFT JOIN prod_kelio_organigramme ON prod_kelio_organigramme.service_ = w_histo_ser.service_
					WHERE heures_jour_ IS NOT NULL
				;		
					

				DROP TABLE IF EXISTS w_ser;
				CREATE TEMP TABLE w_ser AS 
				SELECT
					codeNiv1 || '|' || codeNiv2 || '|' || code_original AS service_code_original,
					codeNiv1,
					codeNiv2,
					codeNiv3,
					libNiv1 as niv_cod1,
					libNiv2 AS niv_cod2,
					codeniv3 AS niv_cod3,
					libNiv1 || '-' || libNiv2 || '-' || libniv3 AS texte,
					left(libNiv1,15) || '-' || left(libNiv2,15) || '-' || left(libniv3,15) AS texte_court
				FROM
					prod_kelio_organigramme
				
				;
				
				
				]]></sqlcmd>
			</NODE>
		</NODE>
		<NODE label="Préparation de l'insertion">
			<sqlcmd><![CDATA[
		
			UPDATE w_affectation_horaire_journalier
			SET 
				salarie_id = w_sal_pla.salarie_id
			FROM
				w_sal_pla 
			WHERE 1=1
				AND UPPER(w_sal_pla.salarie_corr) = UPPER(w_affectation_horaire_journalier.salarie_corr)
				-- désactivé pour test
				-- AND entets_code = etablissement_planning_code
			;		
			
			VACUUM ANALYSE w_affectation_horaire_journalier
			;

				-- Association aux contrats et contrat_mois.
			-- En général, les heures planning sont effectuées AVANT un contrat/paie à cause du décallage avec la paie :
			-- => les heures effectuées en fin de mois sont à associer avec le mois suivant.
			with w_asso as (
				select
					affectation_horaire_journalier_id,
					(max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
					(max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
				from w_affectation_horaire_journalier
					join rh.p_contrats_mois on 1=1
						and p_contrats_mois.salarie_id = w_affectation_horaire_journalier.salarie_id
						and w_affectation_horaire_journalier.date between p_contrats_mois.date_debut and p_contrats_mois.date_fin -- Sélection des contrats pendant heures planning.
				where 1!=1
					OR w_affectation_horaire_journalier.contrat_id is null
					OR w_affectation_horaire_journalier.contrat_mois_id is null
				group by 1)
			UPDATE w_affectation_horaire_journalier SET
				contrat_id = w_asso.contrat_id,
				contrat_mois_id = w_asso.contrat_mois_id
			FROM w_asso
			WHERE w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_asso.affectation_horaire_journalier_id
			;

			with w_asso as (
				select
					affectation_horaire_journalier_id,
					(min(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
					(min(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
				from w_affectation_horaire_journalier
					join rh.p_contrats_mois on 1=1
						and p_contrats_mois.salarie_id = w_affectation_horaire_journalier.salarie_id
						and p_contrats_mois.date_debut > w_affectation_horaire_journalier.date -- Sélection des contrats APRES heures planning.
				where 1!=1
					OR w_affectation_horaire_journalier.contrat_id is null
					OR w_affectation_horaire_journalier.contrat_mois_id is null
				group by 1)
			UPDATE w_affectation_horaire_journalier SET
				contrat_id = w_asso.contrat_id,
				contrat_mois_id = w_asso.contrat_mois_id
			FROM w_asso
			WHERE w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_asso.affectation_horaire_journalier_id
			;

			with w_asso as (
				select
					affectation_horaire_journalier_id,
					(max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
					(max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
				from w_affectation_horaire_journalier
					join rh.p_contrats_mois on 1=1
						and p_contrats_mois.salarie_id = w_affectation_horaire_journalier.salarie_id
						and p_contrats_mois.date_debut < w_affectation_horaire_journalier.date -- Sélection des contrats AVANT heures planning.
				where 1!=1
					OR w_affectation_horaire_journalier.contrat_id is null
					OR w_affectation_horaire_journalier.contrat_mois_id is null
				group by 1)
			UPDATE w_affectation_horaire_journalier SET
				contrat_id = w_asso.contrat_id,
				contrat_mois_id = w_asso.contrat_mois_id
			FROM w_asso
			WHERE w_affectation_horaire_journalier.affectation_horaire_journalier_id = w_asso.affectation_horaire_journalier_id
			;

			-- Création d'index.
			CREATE INDEX w_affectation_horaire_journalier_i_contrat_id      ON w_affectation_horaire_journalier USING btree (contrat_id)
			;
			CREATE INDEX w_affectation_horaire_journalier_i_contrat_mois_id ON w_affectation_horaire_journalier USING btree (contrat_mois_id)
			;
			CREATE INDEX w_affectation_horaire_journalier_i_date            ON w_affectation_horaire_journalier USING btree (date)
			;
			CREATE INDEX w_affectation_horaire_journalier_i_salarie_id      ON w_affectation_horaire_journalier USING btree (salarie_id)
			;


			-- Màj des niveauxx du Planning.
			INSERT INTO rh.t_planning_niveau(code_original, code, texte, texte_court)
				   SELECT
					service_code_original,
					service_code_original,
					texte,
					texte_court
			FROM w_ser
			WHERE service_code_original NOT IN (SELECT code_original FROM rh.t_planning_niveau WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;


			-- Alimentation des tables de paramètres.
			-- Màj des Services du Planning.
			INSERT INTO rh.t_planning_service(code_original, code, texte, texte_court, service_id)
				SELECT
					service_code_original,
					service_code_original,
					texte,
					texte_court,
					0 as service_id
				FROM w_ser
				WHERE service_code_original NOT IN (SELECT code_original FROM rh.t_planning_service WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;
			
			-- Màj des Types d'absences du Planning.
			INSERT INTO rh.t_planning_type_absence(code_original, code, texte, texte_court)
				SELECT
					absence_motif_absence_,
					abrege_,
					libelle_,
					substr(libelle_,1,50)
				FROM prod_kelio_absence AS absence
				WHERE 1=1
					AND abrege_ IN (SELECT abs_cod FROM w_affectation_horaire_journalier)
					AND absence_motif_absence_ NOT IN (SELECT code_original FROM rh.t_planning_type_absence WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;
				
			-- Création d'une table Entreprise/Etablissement.
			DROP TABLE IF EXISTS w_entets
			;

			CREATE TEMP TABLE w_entets AS -- manque SSI, DG et HAD à reventiler correctement
				select
					ets.oid as etablissement_id,
					ent.planning_code||ets.planning_code as entets_code
				from rh.t_entreprises as ent
					join rh.t_etablissements as ets on ets.entreprise_id = ent.oid
				Where 1=1
					and ent.oid != 0
					and ets.oid != 0
			;
	
			-- suppression du planning si employé parti
			DELETE FROM w_affectation_horaire_journalier
			USING rh.p_salaries
			WHERE p_salaries.oid = salarie_id
				AND date > date_sortie_ets
			;
			
			]]></sqlcmd>
		</NODE>

		<NODE label="Insertion de mouvements (Metz)">
			<condition><![CDATA[
				SELECT 1=1
				FROM information_schema.columns
				WHERE column_name = 'affectation_horaire_journalie_' 
				AND table_name = 'affectation_horaire_journalier'
				AND table_schema = 'prod_kelio'
				-- sans base, ventilation par population_salarie, utilisation de datamart pour absences et heures spéciales (pauses annulées)
				;
            ]]></condition>
			<sqlcmd><![CDATA[

                -- Transcodage service (à tort sur niveau 2) => établissement.

                UPDATE w_affectation_horaire_journalier SET
                    entets_code = 'HSB'
                WHERE entets_code in ('DG', 'HAD', 'SSIAB')
                ;

				-- Alimentation de la table de mouvement.
				TRUNCATE rh.p_planning_mouvement
				;
				INSERT INTO rh.p_planning_mouvement(
					salarie_id,
					contrat_id,
					contrat_mois_id,
					date,
					semaine,
					mois,
					etablissement_id, -- @todo à renseigner en fonction du paramétrage dans t_divers.
					service_id,
					qualification_id,
					type_absence_id,
					niveau_id,
					temps_du,
					temps_du_initial,
					temps_valide,
					temps_absence)
					SELECT
						salarie_id,
						contrat_id,
						contrat_mois_id,
						date,
						to_char(w_affectation_horaire_journalier.date, 'IYYYIW'::text)::numeric AS semaine,
						to_char(w_affectation_horaire_journalier.date, 'YYYYMM'::text)::numeric AS mois,
						coalesce(w_entets.etablissement_id, 0) as etablissement_id,
						coalesce(t_planning_service.oid, 0) AS service_id,
						coalesce(t_planning_qualification.oid, 0) AS qualification_id,
						coalesce(t_planning_type_absence.oid, 0) AS type_absence_id,
						coalesce(t_planning_niveau.oid, 0) as niveau_id,
						CASE WHEN date < now() THEN temps_du ELSE 0 END,
						temps_du_initial::numeric,
						CASE WHEN date < now() THEN temps_valide ELSE 0 END,
						CASE WHEN date < now() THEN temps_absence ELSE 0 END
					FROM w_affectation_horaire_journalier
						LEFT JOIN rh.t_planning_niveau        ON t_planning_niveau.code_original        = w_affectation_horaire_journalier.niveaux_code_original
						LEFT JOIN rh.t_planning_service       ON t_planning_service.code_original       = w_affectation_horaire_journalier.service_code_original
						LEFT JOIN rh.t_planning_qualification ON t_planning_qualification.code_original = 0
						LEFT JOIN rh.t_planning_type_absence  ON t_planning_type_absence.code  = w_affectation_horaire_journalier.abs_cod
						LEFT JOIN w_entets                    ON w_entets.entets_code                   = w_affectation_horaire_journalier.entets_code
					WHERE salarie_id IS NOT NULL
					;

			]]></sqlcmd>
		</NODE>
		<NODE label="Insertion de mouvements (Metivet)">
			<condition><![CDATA[
				SELECT 1=1
				FROM information_schema.tables
				WHERE table_name = 'horaire_journalier_base'
				AND table_schema = 'prod_kelio'
				-- avec base et table resulats utilisable pour indicateurs
				;
            ]]></condition>
			<sqlcmd><![CDATA[

				-- Alimentation de la table de mouvement.
				delete from rh.p_planning_mouvement
                where date between '[ENV_PLANNING_DATEDEBUT]'::date and '[ENV_PLANNING_DATEFIN]'::date
                ;
				INSERT INTO rh.p_planning_mouvement(
					salarie_id,
					contrat_id,
					contrat_mois_id,
					date,
					semaine,
					mois,
					etablissement_id, -- @todo à renseigner en fonction du paramétrage dans t_divers.
					service_id,
					qualification_id,
					type_absence_id,
					niveau_id,
					code_horaire_id,
					temps_du,
					temps_du_initial,
					temps_valide,
					temps_absence)
					SELECT
						salarie_id,
						contrat_id,
						contrat_mois_id,
						date,
						to_char(w_affectation_horaire_journalier.date, 'IYYYIW'::text)::numeric AS semaine,
						to_char(w_affectation_horaire_journalier.date, 'YYYYMM'::text)::numeric AS mois,
						coalesce(w_entets.etablissement_id, 0) as etablissement_id,
						coalesce(t_planning_service.oid, 0) AS service_id,
						coalesce(t_planning_qualification.oid, 0) AS qualification_id,
						coalesce(t_planning_type_absence.oid, 0) AS type_absence_id,
						coalesce(t_planning_niveau.oid, 0) as niveau_id,
						0::bigint as code_horaire_id,
						temps_effectif + temps_absences,
						CASE WHEN (ferie IS NULL OR jour_travaille_ = 1 OR temps_absences != 0) THEN temps_du_initial::numeric ELSE 0 END,
						temps_effectif,
						temps_absences
					FROM w_affectation_horaire_journalier
						LEFT JOIN rh.t_planning_niveau        ON t_planning_niveau.code_original        = w_affectation_horaire_journalier.niveaux_code_original
						LEFT JOIN rh.t_planning_service       ON t_planning_service.code_original       = w_affectation_horaire_journalier.service_code_original
						LEFT JOIN rh.t_planning_qualification ON t_planning_qualification.code_original = 0
						LEFT JOIN rh.t_planning_type_absence  ON t_planning_type_absence.code  = w_affectation_horaire_journalier.abs_cod
						LEFT JOIN w_entets                    ON w_entets.entets_code                   = w_affectation_horaire_journalier.entets_code
					WHERE 1=1
                        and salarie_id IS NOT NULL
                        and date between '[ENV_PLANNING_DATEDEBUT]'::date and '[ENV_PLANNING_DATEFIN]'::date
					;

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

			VACUUM ANALYSE rh.p_planning_mouvement
			;

			-- Pas de qualification kelio trouvée => on prend celles de la rh
            INSERT INTO rh.t_planning_qualification (code, code_original, texte, texte_court)
                SELECT	 code, 'K_'||code_original, texte, texte_court
                FROM rh.t_qualifications
                WHERE 1=1
                    AND 'K_'||t_qualifications.code_original NOT IN (SELECT code_original FROM rh.t_planning_qualification)
                    AND t_qualifications.oid != 0
			;
						
			UPDATE rh.p_planning_mouvement SET
				qualification_id = t_planning_qualification.oid
            FROM 
                (SELECT
                    p_contrats_mois.salarie_id,
                    date_debut,
                    date_fin,
                    'K_'||qualification_code_original as planning_qualification_code_original
                FROM
                    rh.p_contrats_mois
                    join rh.p_profil_contrat_mois on contrat_mois_id = p_contrats_mois.oid 
                    join rh.p_profils on p_profil_contrat_mois.profil_id = p_profils.oid 
                GROUP BY 1,2,3,4
                ) sub,
                rh.t_planning_qualification
            WHERE 1=1
                AND sub.planning_qualification_code_original = t_planning_qualification.code_original
                AND p_planning_mouvement.salarie_id = sub.salarie_id
				AND date BETWEEN date_debut AND date_fin
            ;

        ]]></sqlcmd>
		</NODE>
	</NODE>
	<NODE name="POST" type="common" />
	<NODE name="VACUUM" type="common" />
</ROOT>