<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
		<NODE label="Mise à jour des informations permanentes">
			<sqlcmd><![CDATA[
			
			-- Màj des codes postaux
			INSERT INTO rh.t_codes_postaux(oid, code, texte, texte_court, longitude, latitude, departement_id,
				departement_code, departement_texte)
				SELECT
					t_codes_postaux.oid,
					t_codes_postaux.code,
					t_codes_postaux.texte,
					t_codes_postaux.texte_court,
					t_codes_postaux.longitude,
					t_codes_postaux.latitude,
					t_codes_postaux.departement_id,
					t_codes_postaux.departement_code,
					t_codes_postaux.departement_texte
				FROM base.t_codes_postaux
					LEFT JOIN rh.t_codes_postaux t_codes_postaux_rh ON t_codes_postaux_rh.oid = t_codes_postaux.oid
				WHERE t_codes_postaux_rh.oid IS NULL
			;

			UPDATE rh.t_codes_postaux AS t_codes_postaux_rh
			SET	
				code = t_codes_postaux.code,
				texte = t_codes_postaux.texte,
				texte_court = t_codes_postaux.texte_court,
				longitude = t_codes_postaux.longitude,
				latitude = t_codes_postaux.latitude,
				departement_id = t_codes_postaux.departement_id,
				departement_code = t_codes_postaux.departement_code,
				departement_texte = t_codes_postaux.departement_texte
			FROM base.t_codes_postaux
			WHERE
				t_codes_postaux_rh.oid = t_codes_postaux.oid
				AND (
					t_codes_postaux_rh.code IS DISTINCT FROM t_codes_postaux.code OR
					t_codes_postaux_rh.texte IS DISTINCT FROM t_codes_postaux.texte OR
					t_codes_postaux_rh.texte_court IS DISTINCT FROM t_codes_postaux.texte_court OR
					t_codes_postaux_rh.longitude IS DISTINCT FROM t_codes_postaux.longitude OR
					t_codes_postaux_rh.latitude IS DISTINCT FROM t_codes_postaux.latitude OR
					t_codes_postaux_rh.departement_id IS DISTINCT FROM t_codes_postaux.departement_id OR
					t_codes_postaux_rh.departement_code IS DISTINCT FROM t_codes_postaux.departement_code OR
					t_codes_postaux_rh.departement_texte IS DISTINCT FROM t_codes_postaux.departement_texte
					)
			;

			-- Màj des Depts.
			INSERT INTO rh.t_departements(oid, code, texte, texte_court)
				SELECT
					t_departements.oid,
					t_departements.code,
					t_departements.texte,
					t_departements.texte_court
				FROM base.t_departements
					LEFT JOIN rh.t_departements t_departements_rh ON t_departements_rh.oid = t_departements.oid
				WHERE t_departements_rh.oid IS NULL
			;

			UPDATE rh.t_departements t_departements_rh
			SET
				code = t_departements.code,
				texte = t_departements.texte,
				texte_court = t_departements.texte_court
			FROM base.t_departements
			WHERE
				t_departements_rh.oid = t_departements.oid
				AND (
					t_departements_rh.code IS DISTINCT FROM t_departements.code OR
					t_departements_rh.texte IS DISTINCT FROM t_departements.texte OR
					t_departements_rh.texte_court IS DISTINCT FROM t_departements.texte_court
					)
			;

			-- Màj des Entreprises
			INSERT INTO rh.t_entreprises(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_entreprises)
			;
			
			INSERT INTO rh.t_entreprises(code, texte, texte_court, code_original)
				SELECT et_code, et_intitule, substr(et_intitule,1,50), et_code
				FROM prod_sage100.f_eta
				WHERE et_code NOT IN (SELECT code_original FROM rh.t_entreprises)
				GROUP BY 1,2,3,4
			;
			
			-- Màj des Etablissements
			INSERT INTO rh.t_etablissements(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_etablissements)
			;
			
			INSERT INTO rh.t_etablissements(code, texte, texte_court, code_original, entreprise_id)
				SELECT et_code, et_intitule, substr(et_intitule,1,50), et_code, t_entreprises.oid
				FROM prod_sage100.f_eta
					JOIN rh.t_entreprises ON t_entreprises.code_original = et_code
				WHERE et_code NOT IN (SELECT code_original FROM rh.t_etablissements)
				GROUP BY 1,2,3,4,5
			;
			
			-- Màj des catégories socio-professionnelles
			INSERT INTO rh.t_categories_socio_professionnelle(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_categories_socio_professionnelle)
			;
			
			INSERT INTO rh.t_categories_socio_professionnelle(code, texte, texte_court, code_original)
				SELECT ta_codeemploiinsee, max(ta_intitule), max(substr(ta_intitule,1,50)), ta_codeemploiinsee
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 14
					AND ta_codeemploiinsee NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
				GROUP BY 1,4
			;

			-- Màj des groupes cotisants.
			INSERT INTO rh.t_groupes_cotisant(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_groupes_cotisant)
			;
			
			INSERT INTO rh.t_groupes_cotisant(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 27
					AND ta_code NOT IN (SELECT code_original FROM rh.t_groupes_cotisant)
				GROUP BY 1,2,3,4
			;

			-- Màj des motifs de début de contrat
			INSERT INTO rh.t_motifs_debut_contrat(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_motifs_debut_contrat)
			;
					
			INSERT INTO rh.t_motifs_debut_contrat(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 2
					AND ta_code NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
				GROUP BY 1,2,3,4
			;

			-- Màj des motifs de fin de contrat
			INSERT INTO rh.t_motifs_fin_contrat(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_motifs_fin_contrat)
			;
			
			INSERT INTO rh.t_motifs_fin_contrat(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 1 -- ou 26 ?
					AND ta_code NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
				GROUP BY 1,2,3,4
			;

			-- Màj des nationalités
			INSERT INTO rh.t_nationalites(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_nationalites)
			;
			
			INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 4
					AND ta_code NOT IN (SELECT code_original FROM rh.t_nationalites)
				GROUP BY 1,2,3,4
			;

			-- Màj des organismes de cotisation
			INSERT INTO rh.t_organismes_cotisation(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_organismes_cotisation)
			;
			
			INSERT INTO rh.t_organismes_cotisation(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 20
					AND ta_code NOT IN (SELECT code_original FROM rh.t_organismes_cotisation)
				GROUP BY 1,2,3,4
			;

			-- Màj des qualifications
			INSERT INTO rh.t_qualifications(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_qualifications)
			;
			
			INSERT INTO rh.t_qualifications(code, texte, texte_court, code_original)
				SELECT or_code, max(or_intitule), max(substr(or_intitule,1,50)), or_code
				FROM prod_sage100.f_org
				WHERE 1=1
					AND or_type = 3
					AND or_code NOT IN (SELECT code_original FROM rh.t_qualifications)
				GROUP BY 1,4
			;

			-- Màj des rubriques
			INSERT INTO rh.t_rubriques(oid, code_original, code, texte, texte_court, rang_edition)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R', 0
				WHERE 0 NOT IN (SELECT oid FROM rh.t_rubriques)
			;
			
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT lpad(ru_rubrique, 4, '0'), ru_intitule, substr(ru_intitule,1,50), ru_rubrique, ru_nodordre::numeric
				FROM prod_sage100.f_rub
				WHERE ru_rubrique NOT IN (SELECT code_original FROM rh.t_rubriques)
				GROUP BY 1,2,3,4,5
			;

			-- (création des rubriques CTI de cumul)
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT 'C000', 'Ecart cumulé', 'Ecart cumulé', 'C000', -1
				WHERE 'C000' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT 'C086', 'Heures payées', 'Heures payées', 'C086', -1
				WHERE 'C086' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT 'C003', 'Net à payer', 'Net à payer', 'C003', -1
				WHERE 'C003' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT 'C004', 'Net imposable', 'Net imposable', 'C004', -1
				WHERE 'C004' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_situations_famille)
			;
			
			INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
				SELECT af_situationfamiliale, af_situationfamiliale, substr(af_situationfamiliale,1,50), af_situationfamiliale
				FROM prod_sage100.f_hst_famille
				WHERE 1=1
					AND af_situationfamiliale NOT IN (SELECT code_original FROM rh.t_situations_famille)
					AND af_situationfamiliale IS NOT NULL
				GROUP BY 1,2,3,4
			;
	
			-- Màj des types de contrat
			INSERT INTO rh.t_types_contrat(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_types_contrat)
			;
			
			INSERT INTO rh.t_types_contrat(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 2
					AND ta_code NOT IN (SELECT code_original FROM rh.t_types_contrat)
				GROUP BY 1,2,3,4
			;

			-- Màj des statuts
			INSERT INTO rh.t_statuts(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_statuts)
			;
			
			INSERT INTO rh.t_statuts(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 19
					AND ta_code NOT IN (SELECT code_original FROM rh.t_statuts)
				GROUP BY 1,2,3,4
			;

			-- Màj des types de temps de travail
			INSERT INTO rh.t_types_temps_travail(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_types_temps_travail)
			;
			
			INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 18 -- ou 7 ?
					AND ta_code NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
				GROUP BY 1,2,3,4
			;

			-- Màj des services
			INSERT INTO rh.t_services(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_services)
			;
			
			INSERT INTO rh.t_services(code, texte, texte_court, code_original)
				SELECT or_code, max(or_intitule), max(substr(or_intitule,1,50)), or_code
				FROM prod_sage100.f_org
				WHERE 1=1
					AND or_type = 1
					AND or_code NOT IN (SELECT code_original FROM rh.t_services)
				GROUP BY 1,4
			;
			
			-- Màj des spécialités
			INSERT INTO rh.t_specialites(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_specialites)
			;
			
			INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
				SELECT or_code, or_code, max(or_intitule), max(substr(or_intitule,1,50))
				FROM prod_sage100.f_org
				WHERE 1=1
					AND or_type = 0
					AND or_code NOT IN (SELECT code_original FROM rh.t_specialites)
				GROUP BY 1,2
			;

			-- Màj des codes emploi
			INSERT INTO rh.t_codes_emploi(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_codes_emploi)
			;
			
			INSERT INTO rh.t_codes_emploi(code, texte, texte_court, code_original)
				SELECT or_code, max(or_intitule), max(substr(or_intitule,1,50)), or_code
				FROM prod_sage100.f_org
				WHERE 1=1
					AND or_type = 2
					AND or_code NOT IN (SELECT code_original FROM rh.t_codes_emploi)
				GROUP BY 1,4
			;

			-- Màj des types d'horaire -- aucun jeu de données
			INSERT INTO rh.t_types_horaire(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_types_horaire)
			;
			
			-- Màj des sociétés d'interim -- aucun jeu de données
			INSERT INTO rh.t_societes_interim(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_societes_interim)
			;

			-- @TODO: Màj des grilles
			INSERT INTO rh.t_grilles(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_grilles)
			;
			
			/* INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
				SELECT
					lpad(c_group,2,'0')||lpad(qualif,4,'0'),
					lpad(c_group,2,'0')||lpad(qualif,4,'0'),
					lib_group||CASE WHEN qualif <> '' THEN ' Q'||qualif ELSE '' END,
					substr(lib_group||CASE WHEN qualif <> '' THEN ' Q'||qualif ELSE '' END,1,50)
				FROM prod_sigems.groupe_fiehp
				WHERE lpad(c_group,2,'0')||lpad(qualif,4,'0') NOT IN (SELECT code_original FROM rh.t_grilles_groupes)
				GROUP BY 1,2,3,4
			;*/

			-- @TODO: Màj des groupes de grilles
			INSERT INTO rh.t_grilles_groupes(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_grilles_groupes)
			;
			
			/* INSERT INTO rh.t_grilles_groupes(code_original, code, texte, texte_court)
				SELECT c_group, c_group, lib_group, substr(lib_group,1,50)
				FROM prod_sigems.groupe_fiehp
				WHERE c_group NOT IN (SELECT code_original FROM rh.t_grilles_groupes)
				GROUP BY 1,2,3,4
			;*/

			-- Màj des motifs d'arret
			INSERT INTO rh.t_motifs_arret(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_motifs_arret)
			;
			
			INSERT INTO rh.t_motifs_arret(code, texte, texte_court, code_original)
				SELECT ta_code, ta_intitule, substr(ta_intitule,1,50), ta_code
				FROM prod_sage100.f_tab
				WHERE 1=1
					AND ta_typetable = 0
					AND ta_code NOT IN (SELECT code_original FROM rh.t_motifs_arret)
				GROUP BY 1,2,3,4
			;

			-- Màj des précisions du motif d'arrêt
			INSERT INTO rh.t_precisions_motif_arret(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseignée', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_precisions_motif_arret)
			;
			
			-- @TODO: Màj des motifs de visite médicale
			INSERT INTO rh.t_motifs_visite(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_motifs_visite)
			;
			
			/* INSERT INTO rh.t_motifs_visite(code_original, code, texte, texte_court)
				SELECT code, code, libelle, substr(libelle,1,50)
				FROM prod_sigems.MOTIF_VISMED
				WHERE code NOT IN (SELECT code_original FROM rh.t_motifs_visite)
				GROUP BY 1,2,3,4
			;*/

			-- @TODO: Màj des circonstances d'accident du travail
			INSERT INTO rh.t_accident_circonstance(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_accident_circonstance)
			;
			
			/* INSERT INTO rh.t_accident_circonstance(code_original, code, texte, texte_court)
				SELECT code, code, libelle, substr(libelle,1,50)
				FROM prod_sigems.acc_circst
				WHERE 
					code NOT IN (SELECT code_original FROM rh.t_accident_circonstance)
					AND code <> ''
					AND code IS DISTINCT FROM NULL
				GROUP BY 1,2,3,4
			;*/

			-- @TODO: Màj des lieux d'accident du travail
			INSERT INTO rh.t_accident_lieu(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_accident_lieu)
			;
			
			/* INSERT INTO rh.t_accident_lieu(code_original, code, texte, texte_court)
				SELECT code_original, code, code_original, substr(code_original,1,50)
				FROM w_tmp_lieu_1
				WHERE 
					code_original NOT IN (SELECT code_original FROM rh.t_accident_lieu)
				GROUP BY 1,2,3,4
			;*/

			-- @TODO: Màj de la nature de l'accident du travail
			INSERT INTO rh.t_accident_nature(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_accident_nature)
			;
			
			/* INSERT INTO rh.t_accident_nature(code_original, code, texte, texte_court)
				SELECT code, code, libelle, substr(libelle,1,50)
				FROM prod_sigems.acc_nature
				WHERE 
					code NOT IN (SELECT code_original FROM rh.t_accident_nature)
					AND code <> ''
					AND code IS DISTINCT FROM NULL
				GROUP BY 1,2,3,4
			;*/

			-- @TODO: Màj des sièges d'accident du travail
			INSERT INTO rh.t_accident_siege(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_accident_siege)
			;
			
			/* INSERT INTO rh.t_accident_siege(code_original, code, texte, texte_court)
				SELECT code, code, libelle, substr(libelle,1,50)
				FROM prod_sigems.acc_siege
				WHERE 
					code NOT IN (SELECT code_original FROM rh.t_accident_siege)
					AND code <> ''
					AND code IS DISTINCT FROM NULL
				GROUP BY 1,2,3,4
			;*/

			-- Màj des listes de formations
			INSERT INTO rh.t_liste_formations(oid, code_original, code, texte, texte_court)
				SELECT 0, '', chr(1) || '*', 'Non renseigné', 'N/R'
				WHERE 0 NOT IN (SELECT oid FROM rh.t_liste_formations)
			;
			
			INSERT INTO rh.t_liste_formations(code_original, code, texte, texte_court)
				SELECT fo_code, fo_code, fo_intitule, substr(fo_intitule,1,50)
				FROM prod_sage100.f_formation
				WHERE fo_code NOT IN (SELECT code_original FROM rh.t_liste_formations)
				GROUP BY 1,2,3,4
			;

			]]></sqlcmd>
		</NODE>
	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
		<NODE label="Chiffrier">
			<sqlcmd><![CDATA[

			TRUNCATE rh.p_chiffrier_production
			;

			INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
				SELECT
					0,--t_entreprises.oid,
					0,--t_etablissements.oid,
					to_char(f_hcum.hu_date::date,'YYYYMM')::numeric,
					count(DISTINCT sa_matricule),
					sum(CASE WHEN hu_constante = 8 THEN hu_valeurcumul::numeric ELSE 0 END),
					sum(CASE WHEN hu_constante = 86 THEN hu_valeurcumul::numeric ELSE 0 END)
				FROM prod_sage100.f_hcum
					--JOIN rh.t_entreprises ON t_entreprises.code_original = stat_paie.ste
					--JOIN rh.t_etablissements ON t_etablissements.code_original = stat_paie.etb
				WHERE 1=1
                    AND date_part('year', f_hcum.hu_date::date) >= 2008
                    AND date_part('year', f_hcum.hu_date::date) <= 2020
				GROUP BY 1,2,3
			;					

			]]></sqlcmd>
		</NODE>
		<NODE label="Pré-traitements">
			<sqlcmd><![CDATA[

			-- Création d'une table temporaire des affectations
			DROP TABLE IF EXISTS w_aff
			;
			
			CREATE TEMP TABLE w_aff AS
				SELECT
					sa_matricule AS matricule,
					et_etablissement AS eta_code,
					ha_debutpaiement::date AS date_debut,
					ha_finpaiement::date AS date_fin,
					or_departement AS departement,
					or_service AS service,
					or_unite AS unite,
					or_categorie AS categorie
				FROM prod_sage100.f_haff
				WHERE 1=1
					AND ha_debutpaiement IS NOT NULL
					AND ha_finpaiement IS NOT NULL
			;
			
			DELETE FROM w_aff
			WHERE date_debut > date_fin
			;
			
			-- Création d'une table temporaire des contrats
			DROP TABLE IF EXISTS w_cnt
			;
			
			CREATE TEMP TABLE w_cnt AS
				SELECT
					matricule,
					'' AS numero_contrat,
					eta_code,
					min(date_debut) AS date_debut,
					max(date_fin) AS date_fin,
					coalesce(fp_contrat_nature,chr(1)||'*') AS type_contrat
				FROM w_aff
					LEFT JOIN prod_sage100.f_renssal ON f_renssal.sa_matricule = w_aff.matricule
				GROUP BY 1,2,3,6

			;
			
			UPDATE w_cnt
			SET numero_contrat = matricule||replace(date_debut,'-','')
			;
			
			-- Création d'une table temporaire de l'histo salarié dans établissements
			/*DROP TABLE IF EXISTS w_ets
			;
			
			CREATE TEMP TABLE w_ets AS
				SELECT
					sa_matricule AS matricule,
					ae_datededebut::date AS date_debut,
					(ae_date::date - interval '1 day')::date AS date_fin,
					ae_etab_code AS eta_code
				FROM prod_sage100.f_hst_etablissement
			;
			
			DELETE FROM w_ets
			WHERE date_debut > date_fin
			;
			
			UPDATE w_ets
			SET date_debut = date_fin
			WHERE date_debut IS NULL
			;*/
			
			]]></sqlcmd>
		</NODE>
		<NODE label="Profils">
			<sqlcmd><![CDATA[
			
			-- Création d'une table temp de profils
			DROP TABLE IF EXISTS w_profils
			;
			
			CREATE TEMP TABLE w_profils AS
				SELECT
					-- Identifiant CTI du profil CTI
					0 AS profil_id,
					-- Cléfs naturelles permettant le matching du profil CTI au données Sage
					0 AS last_profil,
					w_aff.eta_code AS eta_code,
					w_cnt.matricule AS matricule,
					w_cnt.matricule AS numero_salarie,
					w_cnt.numero_contrat AS numero_contrat,
					w_cnt.date_debut AS cnt_date_debut,
					w_cnt.date_fin AS cnt_date_fin,
					w_aff.date_debut AS aff_date_debut,
					w_aff.date_fin AS aff_date_fin,
					--w_ets.date_debut AS ets_date_debut,
					--w_ets.date_fin AS ets_date_fin,
					-- Données du Profil CTI
					greatest(w_aff.categorie, chr(1)||'*') AS categorie_socio_professionnelle_code_original,
					greatest(w_aff.unite, chr(1)||'*') AS code_emploi_code_original,
					chr(1)||'*' AS grille_code_original,
					chr(1)||'*' AS grille_groupe_code_original,
					chr(1)||'*' AS groupe_cotisant_code_original,
					chr(1)||'*' AS motif_debut_code_original,
					chr(1)||'*' AS motif_fin_code_original,
					greatest(w_aff.categorie, chr(1)||'*') AS qualification_code_original,
					chr(1)||'*' AS section_analytique_code_original,
					chr(1)||'*' AS section_analytique_paie_code_original,
					greatest(w_aff.service, chr(1)||'*') AS service_code_original,
					chr(1)||'*' AS societe_interim_code_original,
					greatest(w_aff.departement, chr(1)||'*') AS specialite_code_original,
					chr(1)||'*' AS statut_code_original,
					greatest(w_cnt.type_contrat, chr(1)||'*') AS type_contrat_code_original,
					chr(1)||'*' AS type_horaire_code_original,
					chr(1)||'*' AS type_temps_travail_code_original
				FROM w_cnt
					LEFT JOIN w_aff ON 1=1
						AND w_aff.matricule = w_cnt.matricule
						AND base.cti_overlaps(w_cnt.date_debut,w_cnt.date_fin,w_aff.date_debut,w_aff.date_fin)
					/*LEFT JOIN w_ets ON 1=1
						AND w_ets.matricule = w_aff.matricule
						AND base.cti_overlaps(w_ets.date_debut,w_ets.date_fin,w_aff.date_debut,w_aff.date_fin)
						AND base.cti_overlaps(w_ets.date_debut,w_ets.date_fin,w_cnt.date_debut,w_cnt.date_fin)*/
				WHERE 1=1
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25 --,26,27
			;
			
			-- Alimentation de la table CTI des profils
			INSERT INTO rh.p_profils
				(
				  categorie_socio_professionnelle_code_original,
				  code_emploi_code_original,
				  grille_code_original,
				  grille_groupe_code_original,
				  groupe_cotisant_code_original,
				  motif_debut_code_original,
				  motif_fin_code_original,
				  qualification_code_original,
				  section_analytique_code_original,
				  section_analytique_paie_code_original,
				  service_code_original,
				  societe_interim_code_original,
				  specialite_code_original,
				  statut_code_original,
				  type_contrat_code_original,
				  type_horaire_code_original,
				  type_temps_travail_code_original
				)
				SELECT
				  w_profils.categorie_socio_professionnelle_code_original,
				  w_profils.code_emploi_code_original,
				  w_profils.grille_code_original,
				  w_profils.grille_groupe_code_original,
				  w_profils.groupe_cotisant_code_original,
				  w_profils.motif_debut_code_original,
				  w_profils.motif_fin_code_original,
				  w_profils.qualification_code_original,
				  w_profils.section_analytique_code_original,
				  w_profils.section_analytique_paie_code_original,
				  w_profils.service_code_original,
				  w_profils.societe_interim_code_original,
				  w_profils.specialite_code_original,
				  w_profils.statut_code_original,
				  w_profils.type_contrat_code_original,
				  w_profils.type_horaire_code_original,
				  w_profils.type_temps_travail_code_original
			  FROM w_profils
				LEFT JOIN rh.p_profils ON 1=1
					AND	p_profils.type_contrat_code_original 					= w_profils.type_contrat_code_original
					AND p_profils.type_horaire_code_original                    = w_profils.type_horaire_code_original
					AND p_profils.motif_debut_code_original                     = w_profils.motif_debut_code_original
					AND p_profils.motif_fin_code_original                       = w_profils.motif_fin_code_original
					AND p_profils.qualification_code_original                   = w_profils.qualification_code_original
					AND p_profils.service_code_original                         = w_profils.service_code_original
					AND p_profils.specialite_code_original                      = w_profils.specialite_code_original
					AND p_profils.type_temps_travail_code_original              = w_profils.type_temps_travail_code_original
					AND p_profils.categorie_socio_professionnelle_code_original = w_profils.categorie_socio_professionnelle_code_original
					AND p_profils.statut_code_original                          = w_profils.statut_code_original
					AND p_profils.code_emploi_code_original                     = w_profils.code_emploi_code_original
					AND p_profils.societe_interim_code_original                 = w_profils.societe_interim_code_original
					AND p_profils.section_analytique_paie_code_original         = w_profils.section_analytique_paie_code_original
					AND p_profils.section_analytique_code_original              = w_profils.section_analytique_code_original
					AND p_profils.grille_code_original                          = w_profils.grille_code_original
					AND p_profils.grille_groupe_code_original                   = w_profils.grille_groupe_code_original
					AND p_profils.groupe_cotisant_code_original                 = w_profils.groupe_cotisant_code_original
			  WHERE	p_profils.type_contrat_code_original IS NULL
			  GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
			;

			-- màj les oids et textes des profils
			SELECT rh.cti_reorganize_profils()
			;

			-- maj des profil_id dans la table temporaire
			UPDATE w_profils
			SET profil_id = p_profils.oid
			FROM rh.p_profils
			WHERE 1=1
				AND	p_profils.type_contrat_code_original                 	= w_profils.type_contrat_code_original
				AND p_profils.type_horaire_code_original                    = w_profils.type_horaire_code_original
				AND p_profils.motif_debut_code_original                     = w_profils.motif_debut_code_original
				AND p_profils.motif_fin_code_original                       = w_profils.motif_fin_code_original
				AND p_profils.qualification_code_original                   = w_profils.qualification_code_original
				AND p_profils.service_code_original                         = w_profils.service_code_original
				AND p_profils.specialite_code_original                      = w_profils.specialite_code_original
				AND p_profils.type_temps_travail_code_original              = w_profils.type_temps_travail_code_original
				AND p_profils.categorie_socio_professionnelle_code_original = w_profils.categorie_socio_professionnelle_code_original
				AND p_profils.statut_code_original                          = w_profils.statut_code_original
				AND p_profils.code_emploi_code_original                     = w_profils.code_emploi_code_original
				AND p_profils.societe_interim_code_original                 = w_profils.societe_interim_code_original
				AND p_profils.section_analytique_paie_code_original         = w_profils.section_analytique_paie_code_original
				AND p_profils.section_analytique_code_original              = w_profils.section_analytique_code_original
				AND p_profils.grille_code_original                          = w_profils.grille_code_original
				AND p_profils.grille_groupe_code_original                   = w_profils.grille_groupe_code_original
				AND p_profils.groupe_cotisant_code_original                 = w_profils.groupe_cotisant_code_original
			;
			
			-- Marquage du profil le + récent pour chaque salarié tout établissement confondu
			UPDATE w_profils
			SET last_profil = 1
			FROM 
				(
				SELECT
					matricule,
					max(aff_date_fin) AS aff_date_fin
				FROM w_profils
				GROUP BY 1
				) AS subq
			WHERE 1=1
				AND w_profils.matricule = subq.matricule
				AND w_profils.aff_date_fin = subq.aff_date_fin
			;
				
			]]></sqlcmd>
		</NODE>
		<NODE label="Salariés">
			<sqlcmd><![CDATA[
			
			DROP TABLE IF EXISTS w_salarie
			;
			
			CREATE TEMP TABLE w_salarie AS
				SELECT 
					'[FINESS]' AS finess,
					fp_identite_nom AS nom,
					fp_identite_prenom AS prenom,
					fp_naissance_date::date AS date_naissance,
					CASE WHEN fp_identite_civilite = 0 
						THEN 'M' 
						ELSE 'F' 
					END AS sexe,
					sa_matricule AS matricule,
					sa_matricule AS code_original,
					coalesce(t_entreprises.oid,0) AS entreprise_id,
					coalesce(t_nationalites.oid,0) AS nationalite_id,
					coalesce(t_codes_postaux.oid,0) AS code_postal_id,
					fp_identite_nomjeunefille AS nom_naissance,
					coalesce(t_situations_famille.oid,0) AS situation_famille_id,
					coalesce(profil_id,0) AS profil_id,
					min(cnt_date_debut)::date AS date_debut,
					max(coalesce(cnt_date_fin, '20991231'))::date AS date_fin
				FROM prod_sage100.f_renssal
					JOIN w_profils ON w_profils.numero_salarie = sa_matricule
					LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = fp_famille_situation
					LEFT JOIN rh.t_entreprises ON t_entreprises.code_original = fp_etab_code
					LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = fp_adr_codepostal
					LEFT JOIN rh.t_nationalites ON t_nationalites.code_original = fp_nation
				WHERE 1=1
					AND last_profil = 1
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13
			;
			
			-- Ajout des nouveaux salariés
			INSERT INTO rh.p_salaries(
				finess,
				nom,
				prenom,
				date_naissance,
				sexe,
				matricule,
				code_original,
				entreprise_id,
				nationalite_id,
				code_postal_id,
				nom_naissance,
				situation_famille_id,
				profil_id,
				date_debut,
				date_fin
				)
				SELECT *
				FROM w_salarie
				WHERE w_salarie.matricule NOT IN (SELECT matricule FROM rh.p_salaries)
			;

			-- Màj des salariés déjà présents
			UPDATE rh.p_salaries
			SET
				finess 					= w_salarie.finess,
				nom 					= w_salarie.nom,
				prenom 					= w_salarie.prenom,
				date_naissance 			= w_salarie.date_naissance,
				sexe 					= w_salarie.sexe,
				entreprise_id 			= w_salarie.entreprise_id,
				nationalite_id 			= w_salarie.nationalite_id,
				code_postal_id 			= w_salarie.code_postal_id,
				nom_naissance 			= w_salarie.nom_naissance,
				situation_famille_id 	= w_salarie.situation_famille_id,
				profil_id 				= w_salarie.profil_id,
				date_debut 				= w_salarie.date_debut,
				date_fin 				= w_salarie.date_fin
			FROM w_salarie
			WHERE 1=1
				AND p_salaries.matricule = w_salarie.matricule
				AND (1!=1
					OR p_salaries.finess 					IS DISTINCT FROM w_salarie.finess
					OR p_salaries.nom 						IS DISTINCT FROM w_salarie.nom
					OR p_salaries.prenom 					IS DISTINCT FROM w_salarie.prenom
					OR p_salaries.date_naissance 			IS DISTINCT FROM w_salarie.date_naissance
					OR p_salaries.sexe 						IS DISTINCT FROM w_salarie.sexe
					OR p_salaries.entreprise_id 			IS DISTINCT FROM w_salarie.entreprise_id
					OR p_salaries.nationalite_id 			IS DISTINCT FROM w_salarie.nationalite_id
					OR p_salaries.code_postal_id 			IS DISTINCT FROM w_salarie.code_postal_id
					OR p_salaries.nom_naissance 			IS DISTINCT FROM w_salarie.nom_naissance
					OR p_salaries.situation_famille_id 		IS DISTINCT FROM w_salarie.situation_famille_id
					OR p_salaries.profil_id 				IS DISTINCT FROM w_salarie.profil_id
					OR p_salaries.date_debut 				IS DISTINCT FROM w_salarie.date_debut
					OR p_salaries.date_fin 					IS DISTINCT FROM w_salarie.date_fin
				)
			;
				

			]]></sqlcmd>
		</NODE>
		<NODE label="Contrats">
			<sqlcmd><![CDATA[
			
			TRUNCATE rh.p_contrats
			;
			
			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;
			
			INSERT INTO rh.p_contrats
				(
				salarie_id,
				date_debut,
				date_fin,
				numero_contrat,
				code_original,
				etablissement_id,
				profil_id
				)
				SELECT
					coalesce(p_salaries.oid,0) AS salarie_id,
					w_profils.cnt_date_debut AS date_debut,
					w_profils.cnt_date_fin AS date_fin,
					w_profils.numero_contrat AS numero_contrat,
					w_profils.numero_contrat AS code_original,
					(max(ARRAY[EXTRACT(EPOCH FROM cnt_date_fin),coalesce(t_etablissements.oid,0)]))[2] AS etablissement_id,
					(max(ARRAY[EXTRACT(EPOCH FROM cnt_date_fin),w_profils.profil_id]))[2] AS profil_id
				FROM w_profils
					JOIN rh.p_salaries ON p_salaries.matricule = w_profils.matricule
					LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = w_profils.eta_code
				GROUP BY 1,2,3,4,5
			;

			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				profil_id,
				nombre_debut_contrat,
				nombre_fin_contrat,
				equivalent_temps_plein,
				age_id,
				age_jours,
				est_hors_periode,
				present_fin_mois,
				anciennete_mois,
				anciennete_annee_id,
				salarie_id
				)
				SELECT
					p_contrats.oid AS contrat_id,
					p_calendrier_mois.mois AS mois,
					GREATEST(p_calendrier_mois.date_debut, p_contrats.date_debut) AS date_debut,
					LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin) AS date_fin,
					min(w_profils.profil_id) AS profil_id,
					CASE WHEN p_contrats.date_debut BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_debut_contrat,
					CASE WHEN p_contrats.date_fin BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_fin_contrat,
					0, --w_profils.nbh_mens / 151.67 AS equivalent_temps_plein,
					base.cti_age(LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin), COALESCE(p_salaries.date_naissance, '1962-04-18'::date), 'ny')  AS age_id,
					LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin)::date - COALESCE(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
					'0' AS est_hors_periode,
					CASE WHEN p_contrats.date_fin >= p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS present_fin_mois,
					base.cti_age(date_trunc('month',p_calendrier_mois.date_fin::date)::date, date_trunc('month',p_contrats.date_debut)::date, 'nm')
							+ GREATEST(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) + 1 AS anciennete_mois,
					floor((base.cti_age(date_trunc('month',p_calendrier_mois.date_fin::date)::date, date_trunc('month',p_contrats.date_debut)::date, 'nm')
						+ GREATEST(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) + 1) / 12) AS anciennete_annee_id,
					p_salaries.oid
				FROM rh.p_contrats
					JOIN rh.p_salaries ON p_contrats.salarie_id = p_salaries.oid
					--JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
					--JOIN rh.t_entreprises ON t_etablissements.entreprise_id = t_entreprises.oid
					JOIN base.p_calendrier_mois ON (p_contrats.date_debut <= p_calendrier_mois.date_fin AND p_contrats.date_fin >= p_calendrier_mois.date_debut)
					JOIN w_profils ON w_profils.numero_contrat = p_contrats.numero_contrat
				GROUP BY 1,2,3,4,6,7,8,9,10,11,12,13,14,15
			;
			
			]]></sqlcmd>
		</NODE>
		<NODE label="Historique de la paie">
			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_hp
			;

			-- INFOS :
			-- La rubrique 440 "Prime Interessement" n'est pas comptée dans le brut => déplacée dans OD/Net
			CREATE TEMP TABLE w_hp AS
				(
				SELECT
					sa_matricule AS matricule,
					hb_date::date AS date,
					base.cti_first_day(hb_date::date) AS date_debut,
					base.cti_last_day(hb_date::date) AS date_fin,
					to_char(hb_date::date,'YYYYMM')::numeric as mois,
					t_rubriques.oid AS rub_id,
					t_rubriques.code_original AS rub_code,
					t_rubriques.texte AS rub_texte,
					hb_base::numeric AS base,
					(CASE WHEN ru_gain = 1 THEN 1 ELSE -1 END) * (CASE WHEN ru_rubrique::int != 440 AND ru_type = 1 AND ru_das_avnat != 1 THEN hb_montant::numeric ELSE 0 END) AS montant_brut,
					0, --(CASE WHEN ru_gain = 1 THEN 1 ELSE -1 END) * (CASE WHEN ru_rubrique = 9 OR ru_rubrique >= 7990 THEN 0 ELSE hb_montant::numeric END) AS montant_frais_imposables,
					hb_taux::numeric AS taux_sal,
					0 AS montant_sal,
					0 AS taux_pat,
					0 AS montant_pat,
					(CASE WHEN (ru_rubrique::int = 440 OR ru_rubrique::int > 1999) AND ru_das_avnat != 1 THEN hb_montant::numeric ELSE 0 END) AS od_net,
					(CASE WHEN ru_dasenplus2 = 2 THEN hb_montant::numeric ELSE 0 END) AS avt_nat,
					0 AS net_imposable,
					0 AS net_a_payer
				FROM prod_sage100.f_hbns
					JOIN prod_sage100.f_rub ON f_rub.ru_rubrique = f_hbns.hb_rubrique
					JOIN rh.t_rubriques ON t_rubriques.code_original = f_rub.ru_rubrique
				WHERE 1=1
					AND ru_imprimable = 2
					AND hb_montant != 0
					AND date_part('year', hb_date::date) >= 2008
					--AND sa_matricule = 1117
					--AND hb_date >= '2012-01-01'
				)
				UNION ALL
				(
				SELECT
					sa_matricule AS matricule,
					hc_date::date AS date,
					base.cti_first_day(hc_date::date) AS date_debut,
					base.cti_last_day(hc_date::date) AS date_fin,
					to_char(hc_date::date,'YYYYMM')::numeric AS mois,
					t_rubriques.oid AS rub_id,
					t_rubriques.code_original AS rub_code,
					t_rubriques.texte AS rub_texte,
					hc_base::numeric AS base,
					0 AS montant_brut,
					0 AS montant_frais_imposables,
					hc_taux_salarial::numeric AS taux_sal,
					(CASE WHEN ru_gain = 1 THEN -1 ELSE 1 END) * hc_montant_salarial::numeric AS montant_sal,
					hc_taux_patronal::numeric AS taux_pat,
					(CASE WHEN ru_gain = 1 THEN -1 ELSE 1 END) * hc_montant_patronal::numeric AS montant_pat,
					0 AS od_net,
					0 AS avt_nat,
					0 AS net_imposable,
					0 AS net_a_payer
				FROM prod_sage100.f_hcot
					JOIN prod_sage100.f_rub ON f_rub.ru_rubrique = f_hcot.hc_rubrique
					JOIN rh.t_rubriques ON t_rubriques.code_original = f_rub.ru_rubrique
				WHERE 1=1
					AND ru_imprimable = 2
					AND (hc_montant_salarial != 0 OR hc_montant_patronal != 0)
					AND date_part('year', hc_date::date) >= 2008
					--AND sa_matricule = 1117
					--AND hc_date >= '2012-01-01'
				)
				UNION ALL
				(
				SELECT
					sa_matricule AS matricule,
					hu_date::date AS date,
					base.cti_first_day(hu_date::date) AS date_debut,
					base.cti_last_day(hu_date::date) AS date_fin,
					to_char(hu_date::date,'YYYYMM')::numeric AS mois,
					t_rubriques.oid AS rub_id,
					t_rubriques.code_original AS rub_code,
					t_rubriques.texte AS rub_texte,
					CASE WHEN hu_constante = 86 THEN hu_valeurcumul::numeric ELSE 0 END AS base,
					0 AS montant_brut,
					0 AS montant_frais_imposables,
					0 AS taux_sal,
					0 AS montant_sal,
					0 AS taux_pat,
					0 AS montant_pat,
					0 AS od_net,
					0 AS avt_nat,
					CASE WHEN hu_constante = 4 THEN hu_valeurcumul::numeric ELSE 0 END AS net_imposable,
					CASE WHEN hu_constante = 3 THEN hu_valeurcumul::numeric ELSE 0 END AS net_a_payer
				FROM prod_sage100.f_hcum
					JOIN rh.t_rubriques ON t_rubriques.code_original = 'C' || lpad(hu_constante, 3, '0')
				WHERE 1=1
					AND hu_constante::int IN (3, 4, 86)
					AND date_part('year', hu_date::date) >= 2008
					--AND sa_matricule = 1117
					--AND hu_date >= '2012-01-01'
				)
			;
				
			CREATE INDEX i_w_hp_1 
			ON w_hp 
			USING btree (matricule)
			;
			
			CREATE INDEX i_w_hp_2 
			ON w_hp 
			USING btree (date)
			;
			
			CREATE INDEX i_w_hp_3 
			ON w_hp 
			USING btree (rub_code)
			;

			TRUNCATE rh.p_historique_paie
			;
			
			SELECT base.cti_stash_table_indexes('rh', 'p_historique_paie')
			;

			INSERT INTO rh.p_historique_paie
				(
				  age_id,
				  base,
				  contrat_id,
				  contrat_mois_id,
				  date_debut,
				  date_fin,
				  date_paie,
				  mois_activite,
				  mois_paie,
				  montant_avantage_nature,
				  montant_brut,
				  montant_cotisation_patronale,
				  montant_cotisation_salarie,
				  montant_frais_imposables,
				  montant_net_a_payer_salarie,
				  montant_net_imposable_salarie,
				  montant_od_net_salarie,
				  organisme_cotisation_id,
				  profil_id,
				  rubrique_id,
				  salarie_id,
				  taux_cotisation_patronale,
				  taux_cotisation_salarie
				)
				SELECT
					date_part('year', age(date, date_naissance)) AS age_id,
					base AS base,
					p_contrats_mois.contrat_id AS contrat_id,
					p_contrats_mois.oid AS contrat_mois_id,
					date_trunc('month', date)::date AS date_debut,
					date::date AS date_fin,
					date::date AS date_paie,
					w_hp.mois AS mois_activite,
					w_hp.mois AS mois_paie,
					avt_nat AS montant_avantage_nature,
					montant_brut AS montant_brut,
					montant_pat AS montant_cotisation_patronale,
					montant_sal AS montant_cotisation_salarie,
					0 AS montant_frais_imposables,
					net_a_payer AS montant_net_a_payer_salarie,
					net_imposable AS montant_net_imposable_salarie,
					od_net AS montant_od_net_salarie,
					0 AS organisme_cotisation_id,
					w_profils.profil_id AS profil_id,
					w_hp.rub_id AS rubrique_id,
					p_salaries.oid AS salarie_id,
					taux_pat AS taux_cotisation_patronale,
					taux_sal AS taux_cotisation_salarie
				FROM w_hp
					JOIN rh.p_salaries ON p_salaries.matricule = w_hp.matricule
					JOIN w_profils ON 1=1
						AND w_profils.matricule = w_hp.matricule
						AND base.cti_overlaps(aff_date_debut,aff_date_fin,w_hp.date_debut,w_hp.date_fin)
					LEFT JOIN rh.p_contrats_mois ON 1=1
						AND p_contrats_mois.salarie_id = p_salaries.oid
						AND p_contrats_mois.mois_activite = w_hp.mois
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23
			;

			SELECT base.cti_stash_pop_table_indexes('rh', 'p_historique_paie')
			;
			
			-- Associer le bulletin de paie au dernier contrat connu lorsque pas de contrat couvrant le mois de paie.
			UPDATE rh.p_historique_paie
			SET 	
				contrat_id = contrat,
				contrat_mois_id = contrat_mois,
				profil_id = profil
			FROM
				(
				SELECT
					p_historique_paie.salarie_id,
					p_historique_paie.date_paie,
					(max(ARRAY[EXTRACT(EPOCH FROM p_contrats.date_fin),p_contrats.oid]))[2] AS contrat,
					(max(ARRAY[EXTRACT(EPOCH FROM p_contrats.date_fin),p_contrats.profil_id]))[2] AS profil,
					(max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.oid]))[2] AS contrat_mois
				FROM rh.p_historique_paie
					JOIN rh.p_contrats ON p_contrats.salarie_id = p_historique_paie.salarie_id
					JOIN rh.p_contrats_mois ON p_contrats_mois.contrat_id = p_contrats.oid
				WHERE p_historique_paie.contrat_mois_id IS NULL
				GROUP BY 1,2
				) AS subq
			WHERE 1=1
				AND p_historique_paie.salarie_id = subq.salarie_id
				AND p_historique_paie.date_paie = subq.date_paie
			;

			-- Création d'une table temp qui regroupe tous les totaux à atteindre pour calculer l'écart
			DROP TABLE IF EXISTS w_totaux
			;

			CREATE TEMP TABLE w_totaux AS
                SELECT
					sa_matricule AS matricule,
					hu_date::date AS date,
					to_char(hu_date::date,'YYYYMM')::numeric AS mois,
					hu_constante as rub_code,
					hu_valeurcumul::numeric AS montant
				FROM prod_sage100.f_hcum
				WHERE 1=1
					AND date_part('year', hu_date::date) >= 2008
					AND hu_constante::int IN (3,4,5,6,7,8,86)
			;
			
			-- Inserer pour chaque bulletin une ligne qui va faire le compte avec le total (rubrique 'C000' nommée 'Ecart cumulé')
			INSERT INTO rh.p_historique_paie
				(
                age_id,
                contrat_id,
                contrat_mois_id,
                date_debut,
                date_fin,
                date_paie,
                mois_activite,
                mois_paie,
                base,
                montant_avantage_nature,
                montant_brut,
                montant_cotisation_patronale,
                montant_cotisation_salarie,
                montant_frais_imposables,
                montant_net_a_payer_salarie,
                montant_net_imposable_salarie,
                montant_od_net_salarie,
                organisme_cotisation_id,
                profil_id,
                rubrique_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie
				)
				SELECT
                    age_id,
                    contrat_id,
                    contrat_mois_id,
                    subq.date_debut,
                    subq.date_fin,
                    subq.date_paie,
                    subq.mois_activite,
                    subq.mois_paie,
                    0 AS base,
                    sum(CASE WHEN rub_code = 5 THEN montant - subq.montant_avantage_nature ELSE 0 END) AS montant_avantage_nature,
                    sum(CASE WHEN rub_code = 8 THEN montant - subq.montant_brut ELSE 0 END) AS montant_brut,
                    sum(CASE WHEN rub_code = 6 THEN montant - subq.montant_cotisation_patronale ELSE 0 END) AS montant_cotisation_patronale,
                    sum(CASE WHEN rub_code = 7 THEN montant - subq.montant_cotisation_salarie ELSE 0 END) AS montant_cotisation_salarie,
                    0 AS montant_frais_imposables,
                    sum(CASE WHEN rub_code = 3 THEN montant - subq.montant_net_a_payer_salarie ELSE 0 END) AS montant_net_a_payer_salarie,
                    sum(CASE WHEN rub_code = 4 THEN montant - subq.montant_net_imposable_salarie ELSE 0 END) AS montant_net_imposable_salarie,
                    0 AS montant_od_net_salarie,
                    subq.organisme_cotisation_id AS organisme_cotisation_id,
                    subq.profil_id AS profil_id,
                    (SELECT oid FROM rh.t_rubriques WHERE code = 'C000') AS rubrique_id,
                    subq.salarie_id AS salarie_id,
                    0 AS taux_cotisation_patronale,
                    0 AS taux_cotisation_salarie
				FROM 
					(
					SELECT
                        p_historique_paie.age_id,
                        p_historique_paie.contrat_id,
                        p_historique_paie.contrat_mois_id,
                        p_historique_paie.date_debut,
                        p_historique_paie.date_fin,
                        p_historique_paie.date_paie,
                        p_historique_paie.mois_activite,
                        p_historique_paie.mois_paie,
                        0 AS base,
                        sum(montant_avantage_nature) AS montant_avantage_nature,
                        sum(montant_brut) AS montant_brut,
                        sum(montant_cotisation_patronale) AS montant_cotisation_patronale,
                        sum(montant_cotisation_salarie) AS montant_cotisation_salarie,
                        0 AS montant_frais_imposables,
                        sum(montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
                        sum(montant_net_imposable_salarie) AS montant_net_imposable_salarie,
                        0 AS montant_od_net_salarie,
                        p_historique_paie.organisme_cotisation_id,
                        p_historique_paie.profil_id,
                        (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                        p_historique_paie.salarie_id,
                        0 AS taux_cotisation_patronale,
                        0 AS taux_cotisation_salarie
					FROM rh.p_historique_paie
                        JOIN rh.p_salaries ON p_salaries.oid = p_historique_paie.salarie_id
					GROUP BY 1,2,3,4,5,6,7,8,9, 18,19,20,21
					) AS subq
				JOIN rh.p_salaries ON p_salaries.oid = subq.salarie_id
				JOIN w_totaux ON
					w_totaux.matricule = p_salaries.matricule
					AND w_totaux.date = subq.date_paie
				GROUP BY 1,2,3,4,5,6,7,8,9, 18,19,20,21
				HAVING 1!=1
					OR sum(CASE WHEN rub_code = 8 THEN montant - subq.montant_brut ELSE 0 END) <> 0
					OR sum(CASE WHEN rub_code = 5 THEN montant - subq.montant_avantage_nature ELSE 0 END) <> 0
					OR sum(CASE WHEN rub_code = 6 THEN montant - subq.montant_cotisation_patronale ELSE 0 END) <> 0
					OR sum(CASE WHEN rub_code = 7 THEN montant - subq.montant_cotisation_salarie ELSE 0 END) <> 0
					OR sum(CASE WHEN rub_code = 3 THEN montant - subq.montant_net_a_payer_salarie ELSE 0 END) <> 0
					OR sum(CASE WHEN rub_code = 4 THEN montant - subq.montant_net_imposable_salarie ELSE 0 END) <> 0
			;

			/*
			
            Quels sont les écarts cumulés > 0 ? :
            
            SELECT  
                p_salaries.matricule, 
                p_historique_paie.*
            FROM rh.p_historique_paie 
                JOIN rh.p_salaries on p_salaries.oid = p_historique_paie.salarie_id
                JOIN rh.t_rubriques on t_rubriques.oid = p_historique_paie.rubrique_id
            WHERE 1=1
                AND t_rubriques.code_original = 'C000'
                AND 
                    (1!=1
                    OR p_historique_paie.base <> 0
                    OR p_historique_paie.montant_brut <> 0
					OR p_historique_paie.montant_cotisation_salarie <> 0
                    OR p_historique_paie.montant_cotisation_patronale <> 0
                    OR p_historique_paie.montant_net_a_payer_salarie <> 0
                    OR p_historique_paie.montant_net_imposable_salarie <> 0
                    OR p_historique_paie.montant_avantage_nature <> 0
                    )
            ORDER BY 1,4 DESC
            ;
            
			*/

			]]></sqlcmd>
		</NODE>
		<NODE label="Ventilation des profils">
			<sqlcmd><![CDATA[
			
			-- Alimentation des profils simultanés.
			TRUNCATE rh.p_profil_contrat_mois
			;
			
			INSERT INTO rh.p_profil_contrat_mois (
				profil_id,
				contrat_mois_id,
				salarie_id,
				ratio,
				mois
				)
				SELECT
					p_contrats_mois.profil_id AS profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					1 AS ratio,
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
				GROUP BY 1,2,3,4,5
			;
			
			]]></sqlcmd>
		</NODE>
		<NODE label="Arrêts de travail">
			<sqlcmd><![CDATA[

			-- SELECT * FROM w_arr
			
			DROP TABLE IF EXISTS w_arr
			;
			
			CREATE TEMP TABLE w_arr AS
				(
				SELECT
                    sa_matricule AS matricule,
                    ap_arret_01type AS motif,
					to_char(ap_arret_01debut::date,'YYYYMM')::numeric AS mois,
                    ap_arret_01debut::date AS date_debut,
                    ap_arret_01fin::date AS date_fin,
                    ap_arret_01fin::date - ap_arret_01debut::date + 1 AS nb_jours,
                    '' AS no_contrat
                FROM prod_sage100.f_hst_arret
                WHERE 1=1
                    AND ap_arret_01debut IS NOT NULL
                    AND ap_arret_01fin IS NOT NULL
                    AND ap_arret_01fin::date - ap_arret_01debut::date + 1 > 0 -- nb_jours > 0
                    AND date_part('year', ap_arret_01debut::date) >= '2008'
                GROUP BY 1,2,3,4,5,6,7
				)
				UNION
				(
				SELECT
                    sa_matricule AS matricule,
                    ap_arret_02type AS motif,
					to_char(ap_arret_02debut::date,'YYYYMM')::numeric AS mois,
                    ap_arret_02debut::date AS date_debut,
                    ap_arret_02fin::date AS date_fin,
                    ap_arret_02fin::date - ap_arret_02debut::date + 1 AS nb_jours,
                    '' AS no_contrat
                FROM prod_sage100.f_hst_arret
                WHERE 1=1
                    AND ap_arret_02debut IS NOT NULL
                    AND ap_arret_02fin IS NOT NULL
                    AND ap_arret_02fin::date - ap_arret_02debut::date + 1 > 0 -- nb_jours > 0
                    AND date_part('year', ap_arret_02debut::date) >= '2008'
                GROUP BY 1,2,3,4,5,6,7
				)
				UNION
				(
				SELECT
                    sa_matricule AS matricule,
                    ap_arret_03type AS motif,
					to_char(ap_arret_03debut::date,'YYYYMM')::numeric AS mois,
                    ap_arret_03debut::date AS date_debut,
                    ap_arret_03fin::date AS date_fin,
                    ap_arret_03fin::date - ap_arret_03debut::date + 1 AS nb_jours,
                    '' AS no_contrat
                FROM prod_sage100.f_hst_arret
                WHERE 1=1
                    AND ap_arret_03debut IS NOT NULL
                    AND ap_arret_03fin IS NOT NULL
                    AND ap_arret_03fin::date - ap_arret_03debut::date + 1 > 0 -- nb_jours > 0
                    AND date_part('year', ap_arret_03debut::date) >= '2008'
                GROUP BY 1,2,3,4,5,6,7
				)
			;
			
			UPDATE w_arr
			SET no_contrat = w_cnt.numero_contrat
			FROM w_cnt
			WHERE 1=1
				AND w_arr.matricule = w_cnt.matricule
				AND base.cti_overlaps(w_arr.date_debut,w_arr.date_fin,w_cnt.date_debut,w_cnt.date_fin)
			;

            -- Alimentation des arrêts de travail
			TRUNCATE rh.p_arrets_travail
			;

			ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
			;

			INSERT INTO rh.p_arrets_travail(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				date_reprise,
				motif_arret_id,
				precision_motif_arret_id,
				nb_jours
				)
				SELECT p_salaries.oid,
					   p_contrats.oid,
					   w_arr.mois,
					   w_arr.date_debut,
					   w_arr.date_fin,
					   (w_arr.date_fin + INTERVAL '1 day')::date AS date_reprise,
					   t_motifs_arret.oid AS motif_arret_id,
					   0 AS precision_motif_arret_id,
					   w_arr.nb_jours
				FROM w_arr
					JOIN rh.p_salaries ON p_salaries.matricule = w_arr.matricule
					JOIN rh.t_motifs_arret ON t_motifs_arret.code_original = w_arr.motif
					JOIN rh.p_contrats ON p_contrats.salarie_id = p_salaries.oid
			;

            -- Ventilation mensuelle des arrêts de travail
			TRUNCATE rh.p_arrets_travail_mois
			;

			INSERT INTO rh.p_arrets_travail_mois(
				arret_travail_id,
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				nb_debut_arret,
				nb_fin_arret,
				nb_reprise_apres_arret,
				date_debut,
				date_fin,
				nb_jours
				)
				SELECT
					p_arrets_travail.oid AS arret_travail_id,
					p_arrets_travail.salarie_id AS salarie_id,
					p_arrets_travail.contrat_id AS contrat_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.mois_activite,
					CASE WHEN p_arrets_travail.date_debut BETWEEN p_contrats_mois.date_debut AND p_contrats_mois.date_fin THEN 1 ELSE 0 END AS nombre_debut_arret,
					CASE WHEN p_arrets_travail.date_fin BETWEEN p_contrats_mois.date_debut AND p_contrats_mois.date_fin THEN 1 ELSE 0 END AS nombre_fin_arret,
					CASE WHEN p_arrets_travail.date_reprise BETWEEN p_contrats_mois.date_debut AND p_contrats_mois.date_fin THEN 1 ELSE 0 END AS nombre_reprise_apres_arret,
					GREATEST(p_contrats_mois.date_debut, p_arrets_travail.date_debut) AS date_debut,
					LEAST(p_contrats_mois.date_fin, p_arrets_travail.date_fin) AS date_fin,
					LEAST(p_contrats_mois.date_fin, p_arrets_travail.date_fin)::date - GREATEST(p_contrats_mois.date_debut, p_arrets_travail.date_debut)::date + 1 AS nb_jours
				FROM rh.p_contrats_mois
					JOIN rh.p_arrets_travail ON (p_contrats_mois.contrat_id = p_arrets_travail.contrat_id AND
						p_arrets_travail.date_debut <= p_contrats_mois.date_fin AND
						p_arrets_travail.date_reprise >= p_contrats_mois.date_debut
						)
				ORDER BY arret_travail_id, p_contrats_mois.mois_activite
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Visites Médicales">
			<sqlcmd><![CDATA[

			]]></sqlcmd>
		</NODE>
		<NODE label="Accidents du travail">
			<sqlcmd><![CDATA[

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

			-- Pré-traitement
			DROP TABLE IF EXISTS w_for
			;

			CREATE temp TABLE w_for AS
				SELECT 
					f_participant.sa_matricule AS matricule,
					'' AS no_contrat,
					f_formation.fo_code AS code,
					fds_datefin::date AS date_debut,
					fds_datefin::date AS date_fin,
					to_char(fds_datefin::date,'YYYYMM')::numeric AS mois_activite,
					fds_nbheures::numeric AS nb_heures,
					f_orgfor.of_nom AS organisateur
				FROM prod_sage100.f_formdatessessions
					JOIN prod_sage100.f_formation ON f_formation.fo_code = f_formdatessessions.fo_code
					JOIN prod_sage100.f_participant ON f_participant.fo_formation = f_formdatessessions.fo_code
					JOIN prod_sage100.f_orgfor ON f_orgfor.of_organisme = f_formation.of_organisme
				WHERE 1=1
					AND date_part('year', fds_datefin::date) >= '2008'
				GROUP BY 1,2,3,4,5,6,7,8
			;
			
			UPDATE w_for
			SET no_contrat = w_cnt.numero_contrat
			FROM w_cnt
			WHERE 1=1
				AND w_for.matricule = w_cnt.matricule
				AND base.cti_overlaps(w_for.date_debut, w_for.date_fin, w_cnt.date_debut, w_cnt.date_fin)
			;
			
			UPDATE w_for
			SET no_contrat = subq.numero_contrat
			FROM 
				(
				SELECT 
					matricule,
					(max(ARRAY[extract(EPOCH FROM w_cnt.date_fin), w_cnt.numero_contrat::numeric]))[2] AS numero_contrat
				FROM w_cnt
				GROUP BY 1
				) AS subq
			WHERE 1=1
				AND w_for.matricule = subq.matricule
				AND no_contrat = ''
			;

			-- Peuplement de rh.p_formations
			TRUNCATE rh.p_formations
			;

			ALTER SEQUENCE rh.s_formations RESTART WITH 1
			;

			INSERT INTO rh.p_formations
				(
				salarie_id,
				formation_id,
				contrat_id,
				contrat_mois_id,
				formation_date,
				mois_activite,
				nb_heures,
				organisateur
				)
				SELECT 	
					p_salaries.oid,
					t_liste_formations.oid,
					p_contrats_mois.contrat_id,
					p_contrats_mois.oid,
					w_for.date_fin,
					w_for.mois_activite,
					w_for.nb_heures,
					substr(w_for.organisateur, 1, 20)
				FROM
					w_for
					JOIN rh.p_salaries ON p_salaries.matricule = w_for.matricule
					JOIN rh.t_liste_formations ON w_for.code = t_liste_formations.code
					JOIN rh.p_contrats_mois ON 1=1
						AND p_contrats_mois.salarie_id = p_salaries.oid
						AND p_contrats_mois.mois_activite = w_for.mois_activite
				ORDER BY 1,2,3,4
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Handicap">
			<sqlcmd><![CDATA[
			
			]]></sqlcmd>
		</NODE>
	</NODE>
	<NODE name="POST" label="POST-TRAITEMENTS">
		<NODE name="DIVERS" type="common"/>
		<NODE name="POST" type="common"/>
	</NODE>
	<NODE name="VACUUM" label="REORGANISATION BASE DE DONNEES">
		<NODE name="VACUUM" type="common" />
	</NODE>
	<NODE name="RAZ" label="RAZ BASE">
		<NODE name="RAZ" type="common" />
	</NODE>
	<NODE name="RAZ_ALL" label="RAZ ALL">
		<NODE name="RAZ_ALL" type="common" />
	</NODE>
</ROOT>
