<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
		<NODE name="INIT" type="common" />
		<NODE label="Mise à jour des informations permanentes">
			<sqlcmd><![CDATA[

            -- Table du ou des entreprises/établissements à importer.
            DROP TABLE IF EXISTS w_ets
            ;

            CREATE TEMP TABLE w_ets AS
                SELECT
                    ste,
                    etbl,
                    nometab1,
                    siret
                FROM prod_sigems.etab
                WHERE
                    case
                        when (SELECT count(rhp_in) = 0 FROM (SELECT rhp_in('siren')) as subq) THEN true -- Pas de SIREN paramétré => on remonte toutes les entités.
                        when (SELECT max(length(rhp_in)) = 9 from (select rhp_in('siren')) as subq) THEN substr(siret, 1, 9) IN (SELECT rhp_in('siren')) -- Un ou des SIREN paramétrés => on remonte toutes les entreprises associées (sur 9 cars).
                        when (SELECT max(length(rhp_in)) = 2 from (select rhp_in('siren')) as subq) THEN ste IN (SELECT rhp_in('siren')) -- ste
						else siret IN (SELECT rhp_in('siren')) -- Un ou des SIRET paramétrés => on remonte tous les établissements associés (sur 14 cars).
                    end
            ;
			
			-- Màj des Depts.
			INSERT INTO rh.t_departements(code, texte, texte_court)
				SELECT code_departement, libelle, substr(libelle,1,50)
				FROM prod_sigems.departement
				WHERE code_departement NOT IN (SELECT code FROM rh.t_departements)
			;

			-- Màj des Entreprises
			INSERT INTO rh.t_entreprises(code, texte, texte_court, code_original, siren)
				SELECT 
					etab.ste, 
					max(etab.nometab1), 
					max(substr(etab.nometab1, 1, 50)), 
					etab.ste, 
					substr(etab.siret, 1, 9)
				FROM prod_sigems.etab
                    JOIN w_ets ON 1=1
                        AND w_ets.ste = etab.ste
                        AND w_ets.etbl = etab.etbl
				WHERE etab.ste NOT IN (SELECT code_original FROM rh.t_entreprises)
				GROUP BY 1,4,5
			;
			
			with ent as (
                SELECT
                    t_entreprises.oid,
                    substr(etab.siret, 1, 9) AS siren
                FROM rh.t_entreprises
					JOIN prod_sigems.etab on etab.ste = t_entreprises.code_original)
            UPDATE rh.t_entreprises
			SET siren = ent.siren
			FROM ent
            WHERE 1=1
                and t_entreprises.oid = ent.oid
                and t_entreprises.siren IS DISTINCT FROM ent.siren
			;

			-- Màj des Etablissements
			INSERT INTO rh.t_etablissements(code, texte, texte_court, code_original, entreprise_id, siret)
				SELECT 
					etab.etbl, 
					etab.nometab1, 
					substr(etab.nometab1, 1, 50), 
					etab.ste||etab.etbl, 
					t_entreprises.oid, 
					etab.siret
				FROM prod_sigems.etab
                    JOIN w_ets ON 1=1
                        AND w_ets.ste = etab.ste
                        AND w_ets.etbl = etab.etbl
					JOIN rh.t_entreprises ON t_entreprises.code_original = etab.ste
				WHERE etab.ste||etab.etbl NOT IN (SELECT code_original FROM rh.t_etablissements)
				GROUP BY 1,2,3,4,5,6
			;
			
			 with eta as (
				SELECT
                    t_etablissements.oid,
                    etab.siret as siret
                FROM rh.t_etablissements
                    JOIN prod_sigems.etab on etab.ste||etab.etbl = t_etablissements.code_original)
            UPDATE rh.t_etablissements
			SET siret = eta.siret
			FROM eta
            WHERE 1=1
                and t_etablissements.oid = eta.oid
                and t_etablissements.siret IS DISTINCT FROM eta.siret 
			;

			-- Màj des catégories socio-professionnelles
			INSERT INTO rh.t_categories_socio_professionnelle
						(code, texte, texte_court, code_original)
				SELECT lower(c_pcs), libelpcs, substr(libelpcs,1,50), lower(c_pcs)
				FROM prod_sigems.ipcs
				WHERE lower(c_pcs) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
					AND c_pcs != ''
				GROUP BY 1,2,3,4
			;

			-- KO Màj des groupes cotisants.
			INSERT INTO rh.t_groupes_cotisant(code, texte, texte_court, code_original)
				SELECT c_group,lib_group,substr(lib_group,1,50),c_group
				FROM prod_sigems.groupe_fiehp
				WHERE c_group 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
			DROP TABLE IF EXISTS w_tmp_mar_0
			;
			
			CREATE TEMP TABLE w_tmp_mar_0 AS
				SELECT 
					motif_abs AS libelle, 
					upper(translate(translate(motif_abs,'éèà','eea'),' -)(','')) AS libellecode
				FROM prod_sigems.REMPLACEMENT
				GROUP BY 1,2
			;

			DROP TABLE IF EXISTS w_tmp_mar_1
			;
			
			CREATE TEMP TABLE w_tmp_mar_1 AS
				SELECT 
					rpad(substr(libellecode,1,4) || substr(upper(md5(libelle)),1,2),6,'0') as code,
					libelle as code_original
				FROM w_tmp_mar_0
			;
			
			INSERT INTO rh.t_motifs_debut_contrat(code, code_original, texte, texte_court)
				SELECT
					motif_deb||CASE WHEN motif_abs IS NULL OR trim(motif_abs) = '' THEN '000000' ELSE w_tmp_mar_1.code END as code,
					motif_deb||CASE WHEN w_tmp_mar_1.code_original IS NULL THEN '' ELSE w_tmp_mar_1.code_original END as code_original,
					CASE WHEN motif_abs IS NULL OR trim(motif_abs) = '' THEN DADSU_TABLES.libelle ELSE substr(DADSU_TABLES.libelle,1,10)||' '||motif_abs END as texte,
					substr(CASE WHEN motif_abs IS NULL OR trim(motif_abs) = '' THEN DADSU_TABLES.libelle ELSE substr(DADSU_TABLES.libelle,1,10)||' '||motif_abs END,1,50) as texte_court
				FROM prod_sigems.CONTRATS_PB
					LEFT JOIN prod_sigems.DADSU_TABLES ON DADSU_TABLES.code = CONTRATS_PB.motif_deb
					LEFT JOIN prod_sigems.REMPLACEMENT ON REMPLACEMENT.id_cont = CONTRATS_PB.id_cont
					LEFT JOIN w_tmp_mar_1 ON w_tmp_mar_1.code_original = REMPLACEMENT.motif_abs
				WHERE 1=1
					AND DADSU_TABLES.code_structure = 'S41.G01.00.002.001'
					AND (motif_deb||CASE WHEN w_tmp_mar_1.code_original IS NULL THEN '' ELSE w_tmp_mar_1.code_original END) NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
					AND motif_deb IS NOT NULL 
					AND trim(motif_deb) <> '' 
				GROUP BY 1,2,3,4
				ORDER BY 1,2
			;

			-- Màj des motifs de fin de contrat
			INSERT INTO rh.t_motifs_fin_contrat(code, texte, texte_court, code_original)
				SELECT code, libelle, substr(libelle,1,50), code
				FROM prod_sigems.dadsu_tables
				WHERE code NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
					AND code_structure = 'S41.G01.00.004.001'
				GROUP BY 1,2,3,4
			;

			/*SELECT c_motf, libelmotf, substr(libelmotf,1,50), c_motf
				FROM prod_sigems.motf
				WHERE c_motf 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(code, texte, texte_court, code_original)
				SELECT c_nati, libelnati, substr(libelnati,1,50), c_nati
				FROM prod_sigems.nati
				WHERE c_nati 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(code, texte, texte_court, code_original)
				SELECT code, libelle, substr(libelle,1,50), code
				FROM prod_sigems.dadsu_typcont
				WHERE code NOT IN (SELECT code_original FROM rh.t_organismes_cotisation)
				GROUP BY 1,2,3,4
			;

			-- Màj des codes emplois
			INSERT INTO rh.t_codes_emploi(code, texte, texte_court, code_original)
				SELECT c_empl, libelempl, substr(libelempl, 1, 50), c_empl
				FROM prod_sigems.empl
				WHERE c_empl NOT IN (SELECT code_original FROM rh.t_codes_emploi)
				GROUP BY 1,2,3,4
			;

			-- Màj des qualifications
			INSERT INTO rh.t_qualifications(code, texte, texte_court, code_original)
				SELECT c_qual, nomqual, substr(nomred,1,50), c_qual
				FROM prod_sigems.qual
				WHERE 1=1
					AND trim(c_qual) != ''
					AND c_qual NOT IN (SELECT code_original FROM rh.t_qualifications)
				GROUP BY 1,2,3,4
			;

			UPDATE rh.t_qualifications
			SET texte_court = substr(texte,1,50)
			WHERE char_length(trim(texte_court)) = 0
			;

			-- Màj des rubriques
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT reduitr, libel, substr(libel,1,50), reduitr, ordre
				FROM prod_sigems.rub
				WHERE reduitr 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 'C007', 'Heures payées', 'Heures payées', 'C007', -1
				WHERE 'C007' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

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

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

            INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
                SELECT 'C003', 'Cotisations salariales', 'Cotisations salariales', '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 'C881', 'Heures payées cadre', 'Heures payées cadre', 'C881', -1
                WHERE 'C881' NOT IN (SELECT code_original FROM rh.t_rubriques)
            ;
            
            INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
                SELECT 'C998', 'Cotisations patronales', 'Cotisations patronales', 'C998', -1
                WHERE 'C998' NOT IN (SELECT code_original FROM rh.t_rubriques)
            ;

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

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

			-- Ajout de la rubrique si elle n'existe pas déjà.
			INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
				SELECT 'C714', 'C714', 'Taxe sur les salaires', 'Taxe sur les salaires', -1
				WHERE 1=1
					AND (SELECT valeur = '1' FROM rh.t_divers WHERE code = 'SIGEMS_TS') -- Taxe sur les salaires que si l'option a été définie à 1.
					AND 'C714' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

            -- Mà des Comptes.
			INSERT INTO rh.t_compte(code_original, code, texte, texte_court)
				SELECT n_cpt, n_cpt, n_cpt, n_cpt
				FROM prod_sigems.rub
				WHERE 1=1
                    and n_cpt NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
                    and length(trim(n_cpt)) > 0
				GROUP BY 1,2,3,4
			;

			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
				SELECT cod_sit, lib_sit, substr(lib_sit,1,50), cod_sit
				FROM prod_sigems.situation
				WHERE cod_sit NOT IN (SELECT code_original FROM rh.t_situations_famille)
				GROUP BY 1,2,3,4
			;
			
			INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
				SELECT c_sfa, c_sfa, c_sfa, c_sfa
				FROM prod_sigems.pers
                    JOIN w_ets ON w_ets.ste||w_ets.etbl = pers.ste||pers.etb
				WHERE 
					c_sfa IS NOT NULL
					AND trim(c_sfa) <> ''
					AND c_sfa NOT IN (SELECT code_original FROM rh.t_situations_famille)
				GROUP BY 1,2,3,4
			;
	
			-- Màj des types de contrat
			INSERT INTO rh.t_types_contrat(code, texte, texte_court, code_original)
				SELECT typecont, typecont, substr(typecont,1,50), typecont
				FROM prod_sigems.contrats_pb
				WHERE
					typecont NOT IN (SELECT code_original FROM rh.t_types_contrat)
					AND typecont <> ''
				GROUP BY 1,2,3,4
			;

			/*
			SELECT cod_nat, lib_nat, substr(lib_nat,1,50), cod_nat
				FROM prod_sigems.nature_contrat
				WHERE cod_nat 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(code, texte, texte_court, code_original)
				SELECT c_stat, libelstat, substr(libelstat,1,50), c_stat
				FROM prod_sigems.stat
				WHERE c_stat 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(code_original, code, texte, texte_court)
				SELECT caract, caract, caract, caract
				FROM prod_sigems.contrats_pb
				WHERE caract NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
				GROUP BY 1,2,3,4
			;

			/*SELECT code, code, libelle, substr(libelle,1,50)
				FROM prod_sigems.dadsu_tables
				WHERE code NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
					AND code_structure ilike 'S41.G01.00.013%'
				GROUP BY 1,2,3,4*/

			-- Màj des services
			INSERT INTO rh.t_services(code_original, code, texte, texte_court)
				SELECT c_serv, c_serv, nomserv, substr(nomserv,1,50)
				FROM prod_sigems.serv
				WHERE c_serv NOT IN (SELECT code_original FROM rh.t_services)
				GROUP BY 1,2,3,4
			;

			-- Màj des spécialités
			INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
				SELECT cod_spe, cod_spe, lib_spe, substr(lib_spe,1,50)
				FROM prod_sigems.specialite
				WHERE cod_spe NOT IN (SELECT code_original FROM rh.t_specialites)
				GROUP BY 1,2,3,4
			;

			-- Màj des types d'horaire
			INSERT INTO rh.t_types_horaire(code_original, code, texte, texte_court)
				-- SELECT cod_hor, cod_hor, lib_hor, substr(lib_hor,1,50)
				-- FROM prod_sigems.horaire
				-- WHERE cod_hor NOT IN (SELECT code_original FROM rh.t_types_horaire)
				-- GROUP BY 1,2,3,4
                SELECT c_ssec, c_ssec, c_ssec, substr(c_ssec, 1, 50)
				FROM prod_sigems.contrats_pb
				WHERE c_ssec NOT IN (SELECT code_original FROM rh.t_types_horaire)
				GROUP BY 1,2,3,4
			;

			-- Màj des sociétés d'interim

			-- Màj des grilles
			
			-- Suppression doublons suite à bug (à enlever en mars 2023)
			DELETE FROM rh.t_grilles
			USING
			(
			SELECT code_original, count(*),
				MAX(CASE WHEN oid IN (SELECT grille_id FROM rh.p_profils) THEN oid ELSE 0 END) AS last_use,
				MIN(oid) AS first_create
			FROM rh.t_grilles
			WHERE oid <> 0
			GROUP BY 1
			HAVING count(*) > 1
			) subview
			WHERE t_grilles.code_original = subview.code_original AND
				(
				t_grilles.oid <> last_use AND last_use > 0 OR
				t_grilles.oid <> first_create AND last_use = 0
				)
			;
			
			-- Ajout des nouvelles
			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)
				GROUP BY 1,2,3,4
			;

			-- Màj des groupes de grilles
			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(code_original, code, texte, texte_court)
				SELECT code, code, lib, substr(lib,1,50)
				FROM prod_sigems.motif_arret
				WHERE 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

			-- Màj des motifs de visite médicale
			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
			;

			-- Màj des circonstances d'accident du travail
			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
			;

			-- Màj des lieux d'accident du travail
			DROP TABLE IF EXISTS w_tmp_lieu_0
			;

			CREATE TEMP TABLE w_tmp_lieu_0 AS
				SELECT 
					lieu as libelle, 
					upper(translate(translate(lieu,'éèà','eea'),' ,-)(+/''','')) AS libellecode
				FROM prod_sigems.acctravail
				WHERE 
					lieu <> ''
					AND lieu IS DISTINCT FROM NULL
			;

			DROP TABLE IF EXISTS w_tmp_lieu_1
			;

			CREATE TEMP TABLE w_tmp_lieu_1 AS
				SELECT 
					rpad(substr(libellecode,1,4) || substr(upper(md5(libelle)),1,2),6,'0') as code,
					libelle as code_original
				FROM w_tmp_lieu_0
			;
			
			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
			;

			-- Màj de la nature de l'accident du travail
			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
			;

			-- Màj des sièges d'accident du travail
			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(code_original, code, texte, texte_court)
				SELECT id_formation, id_formation, libelfrma, substr(libelfrma,1,50)
				FROM prod_sigems.frma
				WHERE id_formation NOT IN (SELECT code_original FROM rh.t_liste_formations)
				GROUP BY 1,2,3,4
			;

			]]></sqlcmd>
		</NODE>
        <NODE label="Auto-détection du paramétrage des rubriques selon le compte (stratégie n°1).">
            <condition><![CDATA[
                
            -- Historique de paie classique.
            select valeur = '1'
            from rh.t_divers
            where code = 'SIGEMS_AUTO'
            ;

                ]]></condition>
            <sqlcmd><![CDATA[

            -- reset
            update rh.t_rubriques set
                p_detail = false,
                p_base = false,
                p_brut = false,
                p_masse_salariale = false,
                p_cotisation_salarie = false,
                p_cotisation_patronale = false,
                p_od_net_salarie = false,
                p_net_imposable = false,
                p_net_a_payer = false
            where not user_modified
            ;

            -- brut
            with toto as (
                select
                    reduitr,
                    n_cpt
                from prod_sigems.rub
                where substr(n_cpt, 1, 1) = '1'
            )
            update rh.t_rubriques set 
                p_detail = true,
                p_base = true,
                c_base = 1,
                s_base = 0,
                p_brut = true,
                c_brut = 1,
                s_brut = 3,
                p_masse_salariale = true,
                c_masse_salariale = 1,
                s_masse_salariale = 3,
                p_net_imposable = case when substr(n_cpt, 1, 2) = '12' then false else true end,
                c_net_imposable = 1,
                s_net_imposable = 3,
                p_net_a_payer = true,
                c_net_a_payer = 1,
                s_net_a_payer = 3
            from toto
            where true
                and t_rubriques.code_original = toto.reduitr
                and not user_modified
            ;
            -- cot sal/pat
            with toto as (
                select
                    reduitr,
                    n_cpt
                from prod_sigems.rub
                where substr(n_cpt, 1, 1) IN ('5', '6', '7', '8') AND substr(n_cpt, 1, 2) not in ('87', '89')
            )
            update rh.t_rubriques set 
                p_detail = true,
                p_base = true,
                c_base = 1,
                s_base = 0,
                p_cotisation_salarie = true,
                c_cotisation_salarie = 1,
                s_cotisation_salarie = 3,
                p_cotisation_patronale = true,
                c_cotisation_patronale = 1,
                s_cotisation_patronale = 5,
                p_masse_salariale = true,
                c_masse_salariale = 1,
                s_masse_salariale = 5,
                p_net_imposable = case when substr(n_cpt, 1, 2) = '50' then false else true end, -- csg/crds
                c_net_imposable = 1,
                s_net_imposable = case when substr(n_cpt, 1, 2) = '70' then 6 else 3 end, -- mutuelles
                p_net_a_payer = true,
                c_net_a_payer = 1,
                s_net_a_payer = 3
            from toto
            where true
                and t_rubriques.code_original = toto.reduitr
                and not user_modified
            ;

            -- OD/Net
            -- cot sal/pat
            with toto as (
                select
                    reduitr
                from prod_sigems.rub
                where substr(n_cpt, 1, 2) in ('87', '89', '90', '99')
            )
            update rh.t_rubriques set 
                p_detail = true,
                p_base = true,
                c_base = 1,
                s_base = 0,
                p_od_net_salarie = true,
                c_od_net_salarie = 1,
                s_od_net_salarie = 3,
                p_net_a_payer = true,
                c_net_a_payer = 1,
                s_net_a_payer = 3
            from toto
            where true
                and t_rubriques.code_original = toto.reduitr
                and not user_modified
            ;

            ]]></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
					t_entreprises.oid,
					t_etablissements.oid,
					(annee||lpad(mois, 2, '0'))::numeric,
					count(DISTINCT mat),
					sum(brut),
					sum(hpay)
				FROM prod_sigems.stat_paie
                    JOIN w_ets ON w_ets.ste||w_ets.etbl = stat_paie.ste||stat_paie.etb
					JOIN rh.t_entreprises ON t_entreprises.code_original = stat_paie.ste
					JOIN rh.t_etablissements ON t_etablissements.code_original = stat_paie.ste||stat_paie.etb
				WHERE annee >= 2014
				GROUP BY 1,2,3
			;

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

            -- Pointage des salaries sans contrats à exclure.
			DROP TABLE IF EXISTS w_exc_mat
			;

			CREATE TEMP TABLE w_exc_mat AS
				SELECT pers.mat
					FROM prod_sigems.pers
                        JOIN w_ets ON w_ets.ste||w_ets.etbl = pers.ste||pers.etb
						LEFT JOIN prod_sigems.contrats_pb ON contrats_pb.mat = pers.mat
					WHERE 1!=1
						OR pers.mat = ''
						OR pers.c_anu = 'O'
						OR contrats_pb.mat IS null
				GROUP BY 1
				ORDER BY 1
			;
			
			-- Création d'une table propre de contrats.
			DROP TABLE IF EXISTS w_cnt
			;
			
			CREATE TEMP TABLE w_cnt AS
				with discarded_cnt as (
					select  mat as dc_mat, dtdebu as dc_dtdebu, min(id_cont) as dc_id_cont
					from prod_sigems.contrats_pb
					group by 1,2
					having count(id_cont) > 1
				)
				SELECT
					(CASE WHEN dtdebu IS DISTINCT FROM NULL AND char_length(dtdebu) > 0 THEN dtdebu ELSE '1900-01-01' END)::date AS date_debut,
					(CASE WHEN dtsort IS DISTINCT FROM NULL AND char_length(dtsort) > 0 THEN dtsort ELSE '2099-12-31' END)::date AS date_fin,
					mat||'-'||id_cont AS u_id_cont, -- Attention : u_id_cont n'est pas forcément chronologique, d'où rang_contrat.
					rank() OVER (PARTITION BY mat ORDER BY (CASE WHEN dtdebu IS DISTINCT FROM NULL AND char_length(dtdebu) > 0 THEN dtdebu ELSE '1900-01-01' END)::date) rang_contrat,
					contrats_pb.*
				FROM prod_sigems.contrats_pb
                    JOIN w_ets ON 1=1
                        AND w_ets.ste = contrats_pb.soc
                        AND w_ets.etbl = contrats_pb.etb
					left join discarded_cnt on discarded_cnt.dc_id_cont = contrats_pb.id_cont
				WHERE 1=1
					AND dtdebu IS NOT NULL
					AND mat IS DISTINCT FROM NULL
					AND mat != ''
					AND mat NOT IN (SELECT mat FROM w_exc_mat)
					and discarded_cnt.dc_mat is null
			;

			-- #correction Lorsque le statut n'est pas alimenté une seule fois pour un matricule,
			-- utiliser le statut de la fiche salarié
			UPDATE w_cnt
			SET c_stat = pers.c_stat
			FROM prod_sigems.pers, w_ets
			WHERE 1=1
                AND pers.mat = w_cnt.mat
                AND w_ets.ste||w_ets.etbl = pers.ste||pers.etb
				AND w_cnt.mat IN (
					SELECT mat
					FROM w_cnt
					WHERE 1!=1
						OR c_stat IS NULL
						OR char_length(c_stat) = 0
					GROUP BY 1)
			;


			-- Création d'un table propre des remplacements
			DROP TABLE IF EXISTS w_rmp
			;
			
			CREATE TEMP TABLE w_rmp AS
				SELECT
					id_cont,
					max(motif_abs) AS motif_abs
				FROM prod_sigems.remplacement
				GROUP BY 1
			;

			-- Création d'un table temp de profils
			DROP TABLE IF EXISTS w_profils
			;
			
			CREATE TEMP TABLE w_profils AS
				SELECT
					0 as profil_id,
					w_cnt.soc as ste,
					w_cnt.etb,
					w_cnt.mat,
					w_cnt.date_debut as grh_dtdu,
					w_cnt.date_fin as grh_dtau,
					w_cnt.id_cont,
					w_cnt.u_id_cont,
					w_cnt.rang_contrat,
					w_cnt.nbh_mens,
					w_cnt.date_debut as contrat_dtdu,
					w_cnt.date_fin as contrat_dtau,
					-- Champs dédiés au privé.
					COALESCE(lower(pers.c_pcs),chr(1)||'*') AS categorie_socio_professionnelle_code_original,
					COALESCE(pers.c_emp, chr(1)||'*') AS code_emploi_code_original,
					COALESCE(lpad(groupe_fiehp.c_group, 2, '0')||lpad(groupe_fiehp.qualif, 4, '0'), chr(1)||'*') AS grille_code_original,
					COALESCE(groupe_fiehp.c_group, chr(1)||'*') AS grille_groupe_code_original,
					chr(1)||'*' AS groupe_cotisant_code_original,
					COALESCE(w_cnt.motif_deb||CASE WHEN w_rmp.motif_abs IS NULL THEN '' ELSE w_rmp.motif_abs END, chr(1)||'*') AS motif_debut_code_original,
					COALESCE(w_cnt.motif_fin,chr(1)||'*') AS motif_fin_code_original,
					COALESCE(pers.c_qual, chr(1)||'*') AS qualification_code_original,
					chr(1)||'*' AS section_analytique_code_original,
					chr(1)||'*' AS section_analytique_paie_code_original,
					COALESCE(nullif(trim(w_cnt.serv), ''), nullif(trim(pers.c_serv), ''), chr(1)||'*') AS service_code_original,
					chr(1)||'*' AS societe_interim_code_original,
					chr(1)||'*' AS specialite_code_original,
					COALESCE(w_cnt.c_stat,chr(1)||'*') AS statut_code_original,
					COALESCE(w_cnt.typecont,chr(1)||'*') AS type_contrat_code_original, --GREATEST(w_cnt.nature,chr(1)||'*') AS type_contrat_code_original,
					COALESCE(nullif(trim(w_cnt.c_ssec), ''), chr(1)||'*') AS type_horaire_code_original,
					COALESCE(w_cnt.caract,chr(1)||'*') AS type_temps_travail_code_original,
					-- Champs dédiés au public.
					chr(1)||'*' AS unite_fonctionnelle_code_original,
					chr(1)||'*' AS categorie_conge_code_original,
					chr(1)||'*' AS compte_salarie_code_original,
					chr(1)||'*' AS commission_paritaire_code_original,
					chr(1)||'*' AS lettre_budgetaire_code_original,
					chr(1)||'*' AS cadre_emploi_code_original,
					chr(1)||'*' AS filiere_code_original,
					chr(1)||'*' AS categorie_statutaire_code_original
				FROM w_cnt
					LEFT JOIN prod_sigems.pers on 1=1
                        AND pers.mat = w_cnt.mat
                        AND pers.ste = w_cnt.soc
                        AND pers.etb = w_cnt.etb
					LEFT JOIN prod_sigems.groupe_fiehp on 1=1
						AND groupe_fiehp.qualif = pers.c_qual
						AND groupe_fiehp.qualif <> ''
						AND groupe_fiehp.qualif IS DISTINCT FROM NULL
					LEFT JOIN w_rmp ON w_rmp.id_cont = w_cnt.id_cont
				WHERE w_cnt.mat NOT IN (SELECT mat FROM w_exc_mat)
				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,28,29
			;

			]]></sqlcmd>
		</NODE>
		<NODE name="PROFIL" type="common" />
		<NODE label="Salariés">
			<sqlcmd><![CDATA[

			-- Création d'une table temporaire contenant le profil le + récent pour un matricule
			DROP TABLE IF EXISTS w_last_profils
			;
			
			CREATE TEMP TABLE w_last_profils AS
				SELECT 
					mat, 
					(max(ARRAY[extract(EPOCH FROM greatest(contrat_dtdu, grh_dtdu)), profil_id]))[2] AS profil_id
				FROM w_profils
				GROUP BY 1
			;
						
			DROP TABLE IF EXISTS w_salaries
			;
			
			CREATE TEMP TABLE w_salaries AS
				SELECT 
					rhp('finess')                        AS finess,
					pers.nom                             AS nom,
					pers.prn                             AS prenom,
					pers.datna::date                     AS date_naissance,
					pers.sexe                            AS sexe,
					pers.mat                             AS matricule,
					pers.mat                             AS code,
					pers.mat                             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,
					numero ||''||bister||' '||rue||' '||adr||' '||cpo||' '||bur AS adresse1,
					'' AS adresse2,
					pers.jnf                             AS nom_naissance,
					coalesce(t_situations_famille.oid,0) AS situation_famille_id,
					coalesce(w_last_profils.profil_id,0) AS profil_id,
					min(dtdebu)::date                    AS date_debut,
					(CASE
						WHEN count(dtdebu) = count(dtsort)
						THEN max(dtsort)
						ELSE '2099-12-31'
					END)::date                           AS date_fin,
					null::date                           AS date_entree_ets,
					null::date                           AS date_sortie_ets,
					-- Champs dédiés au public.          
					null::date                           AS date_entree_fp,
					null::date                           AS date_entree_fph,
					0                                    AS no_adeli,
					0                                    AS code_cotisation_id,
					0                                    AS matricule_retraite,
					pers.secu                            AS nir
				FROM prod_sigems.pers
                    JOIN w_ets ON w_ets.ste||w_ets.etbl = pers.ste||pers.etb
					LEFT JOIN w_cnt                   ON w_cnt.mat = pers.mat
					LEFT JOIN rh.t_codes_postaux      ON t_codes_postaux.code = cpo
					LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = c_sfa
					LEFT JOIN rh.t_entreprises        ON t_entreprises.code_original = pers.ste
					LEFT JOIN rh.t_nationalites       ON t_nationalites.code_original = pers.c_nat
					LEFT JOIN w_last_profils          ON w_last_profils.mat = pers.mat
				WHERE 1=1
					AND pers.c_anu <> 'O'
					AND trim(pers.mat) != ''
					AND pers.ste != 'XX'
					AND pers.etb != 'XX'
					AND pers.mat NOT IN (SELECT mat FROM w_exc_mat)
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,19,20,21,22,23,24,25,26
			;

			-- Les dates d'entrée et de sortie établissement sont calculées à partir des contrats.
			UPDATE w_salaries
			SET date_entree_ets = date_debut,
				date_sortie_ets = date_fin
			;

			]]></sqlcmd>
		</NODE>
		<NODE name="SALARIE" type="common" />
		<NODE label="Contrats">
			<sqlcmd><![CDATA[

			-- Création d'une table temporaire contenant le profil le + récent pour chaque contrat
			DROP TABLE IF EXISTS w_last_contrats
			;
			
			CREATE TEMP TABLE w_last_contrats AS
				SELECT 
					u_id_cont, 
					(max(ARRAY[extract(EPOCH FROM greatest(grh_dtdu)), profil_id]))[2] AS profil_id
				FROM w_profils
				GROUP BY 1
			;
			
			DROP TABLE IF EXISTS w_contrats
			;
			
			CREATE TEMP TABLE w_contrats AS
				SELECT
					w_profils.profil_id,
					w_profils.ste,
					w_profils.etb,
					w_profils.mat,
					w_profils.id_cont,
					w_profils.u_id_cont,
					w_profils.rang_contrat,
					w_profils.nbh_mens,
					w_profils.contrat_dtdu,
					w_profils.contrat_dtau,
					w_profils.contrat_dtdu AS date_debut,
					w_profils.contrat_dtau AS date_fin,
					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_last_contrats
					JOIN w_profils ON 1=1
						AND w_profils.u_id_cont = w_last_contrats.u_id_cont
						AND w_profils.profil_id = w_last_contrats.profil_id
				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,28,29
			;
			
			-- Peuplement des contrats
			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,
				etablissement_id,
				code_original,
				profil_id
				)
				SELECT
					coalesce(p_salaries.oid,0)       AS salarie_id,
					contrat_dtdu::date               AS date_debut,
					contrat_dtau::date               AS date_fin,
					u_id_cont                          AS numero_contrat,
					coalesce(t_etablissements.oid,0) AS etablissement_id,
					u_id_cont                          AS code_original,
					w_contrats.profil_id             AS profil_id
				FROM w_contrats
					JOIN rh.p_salaries       ON p_salaries.matricule = w_contrats.mat
					JOIN rh.t_etablissements ON t_etablissements.code_original = w_contrats.ste||w_contrats.etb
				WHERE 1=1
					AND mat IS NOT NULL
					AND mat <> ''
				GROUP BY 1,2,3,4,5,6,7
			;
			
			-- Ajout des salariés remplacés
			UPDATE rh.p_contrats
			SET salarie_remplace_id = subq.salarie_remplace_id
			FROM (
				SELECT
					mat||'-'||id_cont AS u_id_cont,
					max(p_salaries.oid) AS salarie_remplace_id
				FROM prod_sigems.remplacement
					JOIN rh.p_salaries on p_salaries.matricule = remplacement.mat_abs
				WHERE 1=1
					AND id_cont <> 0 
					AND mat_abs IS NOT NULL
					AND mat_abs <> ''
				GROUP BY 1
				) AS subq
			WHERE numero_contrat = subq.u_id_cont
			;

			-- Calcul ancienneté au début de contrat
			UPDATE rh.p_contrats
			SET
				anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
				anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_calculee_mois
			FROM (
				SELECT
					t1.u_id_cont AS numero_contrat,
					sum(coalesce(t2.contrat_dtau::date, '20991231'::date) - t2.contrat_dtdu::date + 1) AS anciennete_anterieure_jours,
					sum(coalesce(t2.contrat_dtau::date, '20991231'::date) - t2.contrat_dtdu::date + 1) / 30 AS anciennete_anterieure_calculee_mois
				FROM w_contrats AS t1
					JOIN w_contrats AS t2 ON 1=1
						AND t2.mat = t1.mat
						AND t2.rang_contrat < t1.rang_contrat
				group by 1
				) AS subq
			WHERE 1=1
				AND p_contrats.numero_contrat = subq.numero_contrat
			;
			
			-- Ventilation des contrats par mois
			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				nombre_entrees,
				nombre_departs,
				nombre_debut_contrat,
				nombre_fin_contrat,
                est_hors_periode,
                present_debut_mois,
                present_fin_mois,
                nombre_heures,
                ratio_temps_travail,
                equivalent_temps_plein,
				age_id,
				age_jours,
				anciennete_jours,
				anciennete_mois,
				anciennete_annee_id)
				SELECT
					p_contrats.salarie_id AS salarie_id,
					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,
					CASE WHEN p_salaries.date_entree_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_entrees,
					CASE WHEN p_salaries.date_sortie_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_departs,
					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' AS est_hors_periode,
					CASE WHEN p_calendrier_mois.date_debut BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_debut_mois,
					CASE WHEN p_calendrier_mois.date_fin BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_fin_mois,
                    w_contrats.nbh_mens::numeric AS nombre_heures, -- /!\ Nombre d'heures a priori non proratisé : correspond au temps de travail.
                    w_contrats.nbh_mens::numeric / t_etablissements.base_calcul_etp::numeric as ratio_temps_travail, -- Correspond au type de temps de travail : temps complet = 1; mi-temps = 0.5; etc.
					(w_contrats.nbh_mens::numeric / t_etablissements.base_calcul_etp::numeric)
					  * (
							(LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin) - GREATEST(p_calendrier_mois.date_debut, p_contrats.date_debut) + 1)::numeric
							/
							(p_calendrier_mois.date_fin - p_calendrier_mois.date_debut + 1)::numeric
						) 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,
					-- Ancienneté en jours
					p_contrats.anciennete_anterieure_jours
						+ (p_calendrier_mois.date_fin - p_contrats.date_debut)
						+ 1
						AS anciennete_jours,
					-- Ancienneté en 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,
					-- Ancienneté en années
					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
				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_contrats ON w_contrats.u_id_cont = p_contrats.numero_contrat
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
			;
			
			-- Màj des âges négatifs (plage autorisée : 0 -> 110 ans)
			UPDATE rh.p_contrats_mois
			SET age_id = 0
			WHERE age_id < 0
			;
			
			UPDATE rh.p_contrats_mois
			SET age_id = (SELECT max(oid) FROM rh.t_ages)
			WHERE age_id > (SELECT max(oid) FROM rh.t_ages)
			;
			
			-- Màj des anciennetés trop grandes (plage autorisée : 0 -> 50 ans)
			UPDATE rh.p_contrats_mois
			SET anciennete_annee_id = 0
			WHERE anciennete_annee_id < 0
			;
			
			UPDATE rh.p_contrats_mois
			SET anciennete_annee_id = (SELECT max(oid) FROM rh.t_anciennetes_annee)
			WHERE anciennete_annee_id > (SELECT max(oid) FROM rh.t_anciennetes_annee)
			;
										
			]]></sqlcmd>
		</NODE>
		<NODE label="Historique de la paie">
			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_hp_sq
			;

			-- Alimentation de la colonne "base".
			CREATE TEMP TABLE w_hp_sq AS
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::numeric AS mois,
					reduitr::text AS rub_code,
					ordre,
					n_cpt,
					sum(v_cst::numeric) AS base,
					0::numeric AS taux_sal,
					0::numeric AS montant_sal,
					0::numeric AS taux_pat,
					0::numeric AS montant_pat
				FROM prod_sigems.phst
					JOIN prod_sigems.rub ON rub.c_bas = phst.num
                    JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
				WHERE 1=1
					-- AND typdoc = 'B'
				 	AND v_cst != 0
				 	AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
				 	AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;
			
			-- Alimentation de la colonne "Taux salarial".
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::numeric AS mois,
					reduitr AS rub_code,
					ordre,
					n_cpt,
					0,
					sum(CASE WHEN typtas = 'G' THEN v_csg ELSE v_cst END),
					0,
					0,
					0
				FROM prod_sigems.phst
					JOIN prod_sigems.rub ON rub.c_tas = phst.num
					JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
                    JOIN (select valeur = 0 as opt_std_hp from rh.t_divers where code = 'OPT_STD_HP') as t_divers ON true
				WHERE 1=1
					AND CASE WHEN t_divers.opt_std_hp THEN typdoc = 'B' ELSE true END
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND CASE WHEN typtas = 'G' THEN v_csg ELSE v_cst END != 0
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;
			
			-- Alimentation de la colonne "Montant salarial".
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::numeric AS mois,
					reduitr AS rub_code,
					ordre,
					n_cpt,
					0,
					0,
					sum(v_rub),
					0,
					0
				FROM prod_sigems.phst
				   JOIN prod_sigems.rub ON rub.c_rub = phst.num
				   JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
				WHERE 1=1
					-- AND (1!=1
					-- 	OR typdoc = 'B' AND n_cpt::text||c_rub::text != '128' -- @specifique Ste Félicité : on retire la R128 qui n'a pas de comtpe défini.
					-- 	OR typdoc = 'D' AND c_rub = 3034 -- @specifique Ste Félicité : on intégre la 3034 "Réintégration du net imposable".
					-- 	OR typdoc = 'X' AND c_rub IN (129, 130) AND substr(n_cpt, 1, 1) = '1') -- @specifique Ste Félicité : on n'a pas pris la R128 mais prend sa décomposition en R129 + R130.
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND v_rub != 0
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;
			
			-- Alimentation de la colonne "Taux patronal".
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::numeric AS mois,
					reduitr AS rub_code,
					ordre,
					n_cpt,
					0,
					0,
					0,
					sum(CASE WHEN typtap = 'G' THEN v_csg ELSE v_cst END),
					0
				FROM prod_sigems.phst
					JOIN prod_sigems.rub ON rub.c_tap = phst.num
					JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
                    JOIN (select valeur = 0 as opt_std_hp from rh.t_divers where code = 'OPT_STD_HP') as t_divers ON true
				WHERE 1=1
					AND CASE WHEN t_divers.opt_std_hp THEN typdoc = 'B' ELSE true END
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND CASE WHEN typtap = 'G' THEN v_csg ELSE v_cst END != 0
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;
			
			-- Alimentation de la colonne "Montant patronal".
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::numeric AS mois,
					reduitr AS rub_code,
					ordre,
					n_cpt,
					0,
					0,
					0,
					0,
					sum(v_cst)
				FROM prod_sigems.phst
					JOIN prod_sigems.rub ON rub.c_mtp = phst.num
					JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
                    JOIN (select valeur = 0 as opt_std_hp from rh.t_divers where code = 'OPT_STD_HP') as t_divers ON true
				WHERE 1=1
					AND CASE WHEN t_divers.opt_std_hp THEN typdoc = 'B' ELSE true END
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND v_cst != 0
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;

			-- Alimentation de la rubrique C714 "Taxe sur les salaires".
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year',d_hst)::text||lpad (date_part('month',d_hst),2,'0'))::NUMERIC AS mois,
					'C714'::text AS rub_code,
					-1,
					'99999999',
					sum(v_cst),
					0,
					0,
					0,
					sum(v_cst)
				FROM prod_sigems.phst
					JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
				WHERE 1=1
					AND (SELECT valeur = '1' FROM rh.t_divers WHERE code = 'SIGEMS_TS') -- Taxe sur les salaires que si l'option a été définie à 1.
					AND num = 714
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;
			
			-- Alimentation des rubriques de cumul.
			INSERT INTO w_hp_sq
				SELECT 
					phst.ste AS societe,
					phst.etb AS etablissement,
					mat AS matricule,
					mat||'-'||id_contrat AS u_id_cont,
					d_hst AS "date",
					(date_part('year',d_hst)::text||lpad (date_part('month',d_hst),2,'0'))::NUMERIC AS mois,
					'C'::text||lpad(num,3,'0') AS rub_code,
					-1,
					'99999999',
					sum(v_cst), -- base
					0,
					sum(case when num IN (7, 507) then 0 else v_cst end), -- sal; pas de montant pour les heures payées et travaillées.
					0,
					sum(case when num IN (7, 507) then 0 else v_rub end) -- pat; pas de montant pour les heures payées et travaillées.
				FROM prod_sigems.phst
					JOIN w_ets ON 1=1
                        AND w_ets.ste = phst.ste
                        AND w_ets.etbl = phst.etb
				WHERE 1=1
					AND num IN (1, 3, 5, 7, 11, 507, 881, 998)
					AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					AND d_hst >= '2014-01-01'::date
				GROUP BY 1,2,3,4,5,6,7,8,9
			;

			DROP TABLE IF EXISTS w_hp
			;
			-- Aggrégation des rubriques de paie.
			CREATE TEMP TABLE w_hp AS
				SELECT *
				FROM
					(
					SELECT 
						societe,
						etablissement,
						matricule,
						u_id_cont,
						"date"::date,
						mois,
						rub_code,
						ordre,
						n_cpt,
						sum(base) AS base,
						sum(taux_sal) AS taux_sal,
						sum(montant_sal) AS montant_sal,
						sum(taux_pat) AS taux_pat,
						sum(montant_pat) AS montant_pat
					FROM w_hp_sq
					GROUP BY 1,2,3,4,5,6,7,8,9
					) AS phst2
				WHERE 1!=1
					OR montant_sal != 0
					OR montant_pat != 0
					OR rub_code IN ('C001','C003','C005','C007','C011', 'C507','C998', 'C714')
			;

            -- #specifique Spécifiques Brétéché Forfait (on renseigne dans base le nombre d'heures à inscrire dans le champ d'HP base).
            UPDATE w_hp SET
                base = round(base * 151.67 / 206.0, 2)
            WHERE 1=1
                AND current_database() = 'icti_171'
                AND rub_code = '3017'
            ;
			
			 -- #specifique Spécifiques St Louis Forfait (on renseigne dans base le nombre d'heures à inscrire dans le champ d'HP base).
            with fj_sal as (
                select
                    u_id_cont,
                    date
                from w_hp
                where true
                    and rub_code = 'R001'
                    and to_char(date, 'YYYY') >= 2019
                    and base = 0 
                    and montant_sal != 0
                    AND current_database() = 'icti_320'
                )
            , new_data_fj as (
                select
                    w_hp.u_id_cont,
                    w_hp.date,
                    w_hp.base
                from w_hp
                    join fj_sal on true
                        and fj_sal.u_id_cont = w_hp.u_id_cont
                        and fj_sal.date = w_hp.date
                where 1=1
                    and w_hp.rub_code = 'C507'
                    AND current_database() = 'icti_320')
            update w_hp set
                base = new_data_fj.base
            from new_data_fj
            where 1=1
                and new_data_fj.u_id_cont = w_hp.u_id_cont
                and new_data_fj.date = w_hp.date
                and w_hp.rub_code = 'R001'
                AND current_database() = 'icti_320'
            ;

            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
			;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Historique de la paie (mode classique)">
            <condition><![CDATA[
                
            -- Historique de paie classique.
            select valeur = 0
            from rh.t_divers
            where code = 'OPT_STD_HP'
            ;

                ]]></condition>
            <sqlcmd><![CDATA[

			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,
				  montant_od_net_patronale,
				  organisme_cotisation_id,
				  profil_id,
				  rubrique_id,
                  compte_id,
				  salarie_id,
				  taux_cotisation_patronale,
				  taux_cotisation_salarie
				)
				SELECT
					date_part('year', age(date, date_naissance)) AS age_id,
					base AS base,
					(max(array[p_contrats_mois.oid, p_contrats_mois.contrat_id]))[2],
					max(p_contrats_mois.oid),
					date_trunc('month', date)::date,
					date::date,
					date::date,
					w_hp.mois,
					w_hp.mois,
					CASE WHEN t_rubriques.code_calcul = '4' THEN montant_sal ELSE 0 END AS montant_avantage_nature,
					-- @specifique Compléter le brut standard avec le brut exceptionnel (intéressement).
					-- Spécifique Brétéché de juillet 2014 avec comme condition : n_cpt = 'ANNEXE04' and reduitr = '3057'.
					-- En espérant que cette condition ne soit jamais rencontré chez un autre client.
					CASE WHEN substr(n_cpt, 1, 1) = '1' OR substr(n_cpt, 1, 2) = '87' OR (n_cpt = 'ANNEXE04' and rub_code = '3057') THEN montant_sal ELSE 0 END AS montant_brut,
					montant_pat AS montant_cotisation_patronale,
					CASE WHEN substr(n_cpt, 1, 1) IN ('5', '6', '7', '8') AND substr(n_cpt, 1, 2) != '89' AND substr(n_cpt, 1, 2) != '87' THEN -montant_sal ELSE 0 END AS montant_cotisation_salarie,
					CASE WHEN t_rubriques.code_calcul = '3' THEN montant_sal ELSE 0 END AS montant_frais_imposables,
					CASE WHEN substr(n_cpt, 1, 1) IN ('1', '5', '6', '7', '8', '9') AND substr(n_cpt, 1, 3) != '899' THEN montant_sal ELSE 0 END AS montant_net_a_payer_salarie,
					CASE WHEN substr(n_cpt, 1, 1) IN ('1', '5', '6', '7', '8') AND substr(n_cpt, 1, 2) != '50' THEN montant_sal ELSE 0 END AS montant_net_imposable_salarie,
					CASE WHEN substr(n_cpt, 1, 1) = '9' THEN montant_sal ELSE 0 END AS montant_od_net_salarie, -- Ajouté pour Ste Félicité
					CASE WHEN t_rubriques.code_calcul = '6' THEN montant_sal * t_rubriques.coefficient ELSE 0 END AS montant_od_net_patronale, -- Ajouté pour Ste Félicité
					0 AS organisme_cotisation_id, --	p_profils.organisme_cotisation_id AS organisme_cotisation_id, -- KO
					max(w_contrats.profil_id) AS profil_id,
					t_rubriques.oid AS rubrique_id,
                    t_compte.oid as compte_id,
					p_salaries.oid AS salarie_id,
					taux_pat AS taux_cotisation_patronale,
					taux_sal AS taux_cotisation_salarie
				FROM w_hp
					JOIN rh.t_rubriques ON t_rubriques.code_original = w_hp.rub_code
					JOIN rh.p_salaries ON p_salaries.matricule = w_hp.matricule
                    LEFT JOIN rh.t_compte ON t_compte.code_original = w_hp.n_cpt
					LEFT JOIN w_contrats ON 1=1
						AND w_contrats.mat = w_hp.matricule
						AND base.cti_overlaps(w_contrats.contrat_dtdu, w_contrats.contrat_dtau, (date_part('year',w_hp.date)::text||lpad(date_part('month',w_hp.date),2,'0')||'01')::date, w_hp.date)
					LEFT JOIN rh.p_contrats on p_contrats.numero_contrat = w_contrats.u_id_cont
					LEFT JOIN rh.p_contrats_mois on p_contrats_mois.contrat_id = p_contrats.oid
						AND p_contrats_mois.mois_activite = date_part('year', date)::text||lpad(date_part('month', date), 2, '0')
                WHERE rub_code NOT IN ('C001','C003','C005','C011', 'C998', 'C714') -- Exclusion des rubriques de cumul autre que les heures payées et travaillées.
				GROUP BY 1,2,  5,6,7,8,9,10,11,12,13,14,15,16,17,18,  21,22,23,24,25
			;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Historique de la paie (mode paramétré)">
            <condition><![CDATA[
                
            -- Historique de paie paramétré.
            select valeur = 1
            from rh.t_divers
            where code = 'OPT_STD_HP'
            ;

            ]]></condition>
        <sqlcmd><![CDATA[

            INSERT INTO rh.p_historique_paie (
                  age_id,
                  contrat_id,
                  contrat_mois_id,
                  date_debut,
                  date_fin,
                  date_paie,
                  mois_activite,
                  mois_paie,
                  base,
                  nombre,
				  heure_contrat,
                  heure_payee,
                  heure_travaillee,
                  montant_masse_salariale,
                  montant_brut,
                  montant_avantage_nature,
                  montant_frais_imposables,
                  taux_cotisation_salarie,
                  montant_cotisation_salarie,
                  taux_cotisation_patronale,
                  montant_cotisation_patronale,
                  montant_od_net_salarie,
                  montant_od_net_patronale,
                  montant_net_imposable_salarie,
                  montant_net_a_payer_salarie,
                  organisme_cotisation_id,
                  profil_id,
                  rubrique_id,
                  compte_id,
                  salarie_id)
                SELECT
                    date_part('year', age(date, date_naissance)) AS age_id,
					(max(array[p_contrats_mois.oid, p_contrats_mois.contrat_id]))[2],
                    max(p_contrats_mois.oid),
                    date_trunc('month', date)::date,
                    date::date,
                    date::date,
                    w_hp.mois,
                    w_hp.mois,
                    CASE WHEN p_base THEN (CASE s_base
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_base AS base,
                    CASE WHEN p_nombre THEN (CASE s_nombre
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_nombre AS nombre,
					CASE WHEN p_heures_contrat THEN (CASE s_heures_contrat
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_heures_contrat AS heures_contrat,
                    CASE WHEN p_heures_payees THEN (CASE s_heures_payees
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_heures_payees AS heures_payees,
                    CASE WHEN p_heures_travaillees THEN (CASE s_heures_travaillees
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_heures_travaillees AS heures_travaillees,
                    CASE WHEN p_masse_salariale THEN (CASE s_masse_salariale
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_masse_salariale AS montant_masse_salariale,
                    CASE WHEN p_brut THEN (CASE s_brut
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_brut AS montant_brut,
                    CASE WHEN p_avantage_nature THEN (CASE s_avantage_nature
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_avantage_nature AS montant_avantage_nature,
                    CASE WHEN p_frais_imposables THEN (CASE s_frais_imposables
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_frais_imposables AS montant_frais_imposables,
                    taux_sal * coefficient_txs AS taux_cotisation_salarie,
                    CASE WHEN p_cotisation_salarie THEN (CASE s_cotisation_salarie
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_cotisation_salarie AS montant_cotisation_salarie,
                    taux_pat * coefficient_txp AS taux_cotisation_patronale,
                    CASE WHEN p_cotisation_patronale THEN (CASE s_cotisation_patronale
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_cotisation_patronale AS montant_cotisation_patronale,
                    CASE WHEN p_od_net_salarie THEN (CASE s_od_net_salarie
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_od_net_salarie AS montant_od_net_salarie,
                    CASE WHEN p_od_net_patronale THEN (CASE s_od_net_patronale
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_od_net_patronale AS montant_od_net_patronale,
                    CASE WHEN p_net_imposable THEN (CASE s_net_imposable
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_net_imposable AS montant_net_imposable_salarie,
                    CASE WHEN p_net_a_payer THEN (CASE s_net_a_payer
                            WHEN 0 THEN base
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_pat
                            WHEN 5 THEN montant_pat
                            WHEN 6 THEN montant_sal + montant_pat
                            WHEN 7 THEN montant_sal - montant_pat
                            WHEN 8 THEN -montant_sal + montant_pat
                        END) ELSE 0 END * c_net_a_payer AS montant_net_a_payer_salarie,
                    0 AS organisme_cotisation_id, --    p_profils.organisme_cotisation_id AS organisme_cotisation_id, -- KO
                    max(w_contrats.profil_id) AS profil_id,
                    t_rubriques.oid AS rubrique_id,
                    t_compte.oid as compte_id,
                    p_salaries.oid AS salarie_id
                FROM w_hp
                    JOIN rh.t_rubriques ON t_rubriques.code_original = w_hp.rub_code
                    JOIN rh.p_salaries ON p_salaries.matricule = w_hp.matricule
                    LEFT JOIN rh.t_compte ON t_compte.code_original = w_hp.n_cpt
                    LEFT JOIN w_contrats ON 1=1
                        AND w_contrats.mat = w_hp.matricule
                        AND base.cti_overlaps(w_contrats.contrat_dtdu, w_contrats.contrat_dtau, (date_part('year',w_hp.date)::text||lpad(date_part('month',w_hp.date),2,'0')||'01')::date, w_hp.date)
                    LEFT JOIN rh.p_contrats on p_contrats.numero_contrat = w_contrats.u_id_cont
                    LEFT JOIN rh.p_contrats_mois on p_contrats_mois.contrat_id = p_contrats.oid
                        AND p_contrats_mois.mois_activite = date_part('year', date)::text||lpad(date_part('month', date), 2, '0')
                WHERE t_rubriques.p_detail
                GROUP BY 1, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,  28,29,30, w_hp.ctid
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Historique de la paie (suite)">
            <sqlcmd><![CDATA[


			-- Associer le bulletin de paie au dernier contrat connu lorsque pas de contrat couvrant le mois de paie.
			-- @todo : un tuple dans p_contrats_mois devrait être créé avec est_hors_periode à 1 (au lieu de l'update qui suit)...
			-- MAIS comme v_historique_paie est interrogée sur date_paie, les requêtes fonctionnent...
			UPDATE rh.p_historique_paie SET
				contrat_id = contrat[2],
				contrat_mois_id = contrat_mois[2],
				profil_id = profil[2]
			FROM
				(
				select
					p_historique_paie.salarie_id,
					p_historique_paie.date_paie,
					max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.contrat_id]) as contrat,
					max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.profil_id]) as profil,
					max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.oid]) as contrat_mois
				from rh.p_historique_paie
				JOIN rh.p_contrats_mois ON p_contrats_mois.salarie_id = p_historique_paie.salarie_id
				where p_historique_paie.contrat_mois_id is null
				group by 1,2
				) as subq
			WHERE
				p_historique_paie.salarie_id = subq.salarie_id
				AND p_historique_paie.date_paie = subq.date_paie
			;

            -- Application du ratio temps de travail pour les temps partiels.
            update rh.p_historique_paie set
                base = base * ratio_temps_travail
            from rh.p_contrats_mois
            where 1=1
                and p_historique_paie.contrat_mois_id = p_contrats_mois.oid
                and rubrique_id in (select oid from rh.t_rubriques where @c_base != 1)
                and ratio_temps_travail != 1
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Historique de la paie (mode classique)">
            <condition><![CDATA[
                
            -- Historique de paie classique.
            select valeur = 0
            from rh.t_divers
            where code = 'OPT_STD_HP'
            ;

            ]]></condition>
            <sqlcmd><![CDATA[

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

			CREATE TEMP TABLE w_tmp_totaux AS
				SELECT *
				FROM (
					SELECT 	
						societe,
						etablissement,
						matricule,
						"date",
						mois,
						rub_code,
						sum(base) AS base,
						sum(taux_sal) AS taux_sal,
						sum(montant_sal) AS montant_sal,
						sum(taux_pat) AS taux_pat,
						sum(montant_pat) AS montant_pat,
						max(ordre) AS ordre
					FROM (
							 SELECT
							 	phst.ste AS societe,
								phst.etb AS etablissement,
								mat AS matricule,
								d_hst AS "date",
								(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::NUMERIC AS mois,
								'C'::text||lpad(num,3,'0') AS rub_code,
								v_cst AS base,
								v_cst AS taux_sal,
								v_cst AS montant_sal,
								v_cst AS taux_pat,
								v_cst AS montant_pat,
								-1 as ordre
							FROM prod_sigems.phst
                                JOIN w_ets ON 1=1
                                    AND w_ets.ste = phst.ste
                                    AND w_ets.etbl = phst.etb
							WHERE 1=1
								AND num BETWEEN 1 AND 11
								AND num <> 7
								AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
						UNION ALL
							SELECT 
								phst.ste AS societe,
								phst.etb AS etablissement,
								mat AS matricule,
								d_hst AS "date",
								(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::NUMERIC AS mois,
								'C012'::text AS rub_code,
								v_cst,
								v_cst,
								v_cst,
								v_cst,
								v_cst,
								-1
							FROM prod_sigems.phst
								JOIN w_ets ON 1=1
                                    AND w_ets.ste = phst.ste
                                    AND w_ets.etbl = phst.etb
							WHERE 1=1
							AND num = 173
							AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
						UNION ALL
							-- Taxe sur les salaires que si l'option a été définie à 1.
							SELECT 
								phst.ste AS societe,
								phst.etb AS etablissement,
								mat AS matricule,
								d_hst AS "date",
								(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::NUMERIC AS mois,
								'C714'::text AS rub_code,
								v_cst,
								0,
								0,
								0,
								v_cst,
								-1
							FROM prod_sigems.phst
								JOIN w_ets ON 1=1
                                    AND w_ets.ste = phst.ste
                                    AND w_ets.etbl = phst.etb
							WHERE 1=1
								AND (SELECT valeur = '1' FROM rh.t_divers WHERE code = 'SIGEMS_TS') -- Taxe sur les salaires que si l'option a été définie à 1.
								AND num = 714
								AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
						UNION ALL
							-- @specifique Compléter le brut standard avec le brut exceptionnel (intéressement).
							-- Spécifique Brétéché de juillet 2014 avec comme condition : n_cpt = 'ANNEXE04' and reduitr = '3057'.
							-- En espérant que cette condition ne soit jamais rencontré chez un autre client.
							SELECT 
								phst.ste AS societe,
								phst.etb AS etablissement,
								mat AS matricule,
								d_hst AS "date",
								(date_part('year', d_hst)::text||lpad(date_part('month', d_hst), 2, '0'))::NUMERIC AS mois,
								'C001' AS rub_code,
								v_rub AS base,
								v_rub AS taux_sal,
								v_rub AS montant_sal,
								v_rub AS taux_pat,
								v_rub AS montant_pat,
								-1 as ordre
							FROM prod_sigems.phst
								JOIN prod_sigems.rub ON rub.c_rub = phst.num
								JOIN w_ets ON 1=1
                                    AND w_ets.ste = phst.ste
                                    AND w_ets.etbl = phst.etb
							WHERE 1=1
								AND (1!=1
									OR substr(n_cpt, 1, 2) = '87'
									OR (n_cpt = 'ANNEXE04' and reduitr = '3057'))
								AND phst.mat NOT IN (SELECT mat FROM w_exc_mat)
					) as subq
					GROUP BY 1,2,3,4,5,6) AS phst2
					WHERE (montant_sal <> 0 OR montant_pat <> 0)
					AND   "date" >= '2014-01-01'
			;

			DROP TABLE IF EXISTS w_cumul
			;

            CREATE TEMP TABLE w_cumul AS
                SELECT
                    true as total_heures_contrat,
                    true as total_heures_payees,
                    true as total_heures_travaillees,
                    true as total_masse_salariale,
                    true as total_brut,
                    true as total_avantage_nature,
                    true as total_frais_imposables,
                    true as total_cotisation_salarie,
                    true as total_cotisation_patronale,
                    true as total_od_net_salarie,
                    true as total_od_net_patronale,
                    true as total_net_imposable,
                    true as total_net_a_payer
            ;

			DROP TABLE IF EXISTS w_totaux
			;

			CREATE TEMP TABLE w_totaux AS
				SELECT
					societe,
					etablissement,
					matricule,
					"date",
					mois,
                    sum(CASE WHEN rub_code = 'C007' THEN montant_sal ELSE 0 END) AS mnt_hp,
                    sum(CASE WHEN rub_code = 'C507' THEN montant_sal ELSE 0 END) AS mnt_hw,
					sum(CASE WHEN rub_code = 'C001' THEN montant_sal ELSE 0 END) AS mnt_brut,
					sum(CASE WHEN rub_code = 'C003' THEN -montant_sal ELSE 0 END) AS mnt_cotisation_salariale,
                    sum(CASE WHEN rub_code IN ('C012', 'C714') THEN montant_pat ELSE 0 END) AS mnt_cotisation_patronale,
					sum(CASE WHEN rub_code = 'C005' THEN montant_sal ELSE 0 END) as mnt_net_imposable_salarie,
                    sum(CASE WHEN rub_code = 'C011' THEN montant_sal ELSE 0 END) AS mnt_net_a_payer_salarie
				FROM w_tmp_totaux
				GROUP BY 1,2,3,4,5
			;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Historique de la paie (mode paramétré)">
            <condition><![CDATA[
                
            -- Historique de paie paramétré.
            select valeur = 1
            from rh.t_divers
            where code = 'OPT_STD_HP'
            ;

            ]]></condition>
        <sqlcmd><![CDATA[

			-- Création d'une table récapitulative des écarts à calculer par indicateur de paie (1 seule ligne).
            DROP TABLE IF EXISTS w_cumul
			;

            CREATE TEMP TABLE w_cumul AS
                SELECT
                    bool_or(p_cumul and p_heures_contrat) as total_heures_contrat,
                    bool_or(p_cumul and p_heures_payees) as total_heures_payees,
                    bool_or(p_cumul and p_heures_travaillees) as total_heures_travaillees,
                    bool_or(p_cumul and p_masse_salariale) as total_masse_salariale,
                    bool_or(p_cumul and p_brut) as total_brut,
                    bool_or(p_cumul and p_avantage_nature) as total_avantage_nature,
                    bool_or(p_cumul and p_frais_imposables) as total_frais_imposables,
                    bool_or(p_cumul and p_cotisation_salarie) as total_cotisation_salarie,
                    bool_or(p_cumul and p_cotisation_patronale) as total_cotisation_patronale,
                    bool_or(p_cumul and p_od_net_salarie) as total_od_net_salarie,
                    bool_or(p_cumul and p_od_net_patronale) as total_od_net_patronale,
                    bool_or(p_cumul and p_net_imposable) as total_net_imposable,
                    bool_or(p_cumul and p_net_a_payer) as total_net_a_payer
                FROM rh.t_rubriques
            ;

            DROP TABLE IF EXISTS w_totaux
            ;

            CREATE TEMP TABLE w_totaux AS
                SELECT
                    societe,
                    etablissement,
                    matricule,
                    "date",
                    mois,
                    sum(CASE WHEN p_cumul AND p_heures_payees        THEN base        * c_heures_payees        ELSE 0 END) AS mnt_hp,
                    sum(CASE WHEN p_cumul AND p_heures_travaillees   THEN base        * c_heures_travaillees   ELSE 0 END) AS mnt_hw,
                    sum(CASE WHEN p_cumul AND p_brut                 THEN montant_sal * c_brut                 ELSE 0 END) AS mnt_brut,
                    sum(CASE WHEN p_cumul AND p_cotisation_salarie   THEN montant_sal * c_cotisation_salarie   ELSE 0 END) AS mnt_cotisation_salariale,
                    sum(CASE WHEN p_cumul AND p_cotisation_patronale THEN montant_pat * c_cotisation_patronale ELSE 0 END) AS mnt_cotisation_patronale,
                    sum(CASE WHEN p_cumul AND p_net_imposable        THEN montant_sal * c_net_imposable        ELSE 0 END) as mnt_net_imposable_salarie,
                    sum(CASE WHEN p_cumul AND p_net_a_payer          THEN montant_sal * c_net_a_payer          ELSE 0 END) AS mnt_net_a_payer_salarie
                FROM w_hp
                    JOIN rh.t_rubriques on t_rubriques.code_original = w_hp.rub_code
                WHERE p_cumul
                -- rub_code IN ('C001','C003','C005','C007','C011', 'C507','C998', 'C714')
                GROUP BY 1,2,3,4,5
            ;

			]]></sqlcmd>
		</NODE>
        <NODE label="Historique de la paie">
            <sqlcmd><![CDATA[

            -- Inserer pour chaque bulletin une ligne qui va faire le compte avec le total
            INSERT INTO rh.p_historique_paie(
                contrat_id,
                contrat_mois_id,
                mois_activite,
                date_debut,
                date_fin,
                mois_paie,
                date_paie,
                base,
                nombre,
                heure_payee,
                heure_travaillee,
                montant_masse_salariale,
                montant_brut,
                montant_avantage_nature,
                montant_frais_imposables,
                taux_cotisation_salarie,
                montant_cotisation_salarie,
                taux_cotisation_patronale,
                montant_cotisation_patronale,
                montant_od_net_salarie,
                montant_od_net_patronale,
                montant_net_imposable_salarie,
                montant_net_a_payer_salarie,
                organisme_cotisation_id,
                rubrique_id,
                salarie_id)
                SELECT
                  contrat_id,
                  contrat_mois_id,
                  subq.mois_activite,
                  subq.date_debut,
                  subq.date_fin,
                  subq.mois_paie,
                  subq.date_paie,
                  0,
                  0,
                  sum(case when total_heures_payees 		then mnt_hp - heure_payee 										else 0 end),
                  sum(case when total_heures_travaillees 	then mnt_hw - heure_travaillee 									else 0 end),
                  0,
                  sum(case when total_brut 					then mnt_brut - montant_brut 									else 0 end),
                  0,
                  0,
                  0,
                  sum(case when total_cotisation_salarie 	then mnt_cotisation_salariale - montant_cotisation_salarie 		else 0 end),
                  0,
                  sum(case when total_cotisation_patronale 	then mnt_cotisation_patronale - montant_cotisation_patronale 	else 0 end),
                  0,
                  0,
                  sum(case when total_net_imposable 		then mnt_net_imposable_salarie - montant_net_imposable_salarie 	else 0 end),
                  sum(case when total_net_a_payer 			then mnt_net_a_payer_salarie - montant_net_a_payer_salarie 		else 0 end),
                  subq.organisme_cotisation_id,
                  (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                  subq.salarie_id
                FROM (
                    SELECT
                      p_historique_paie.contrat_id,
                      p_historique_paie.contrat_mois_id,
                      p_historique_paie.date_debut,
                      p_historique_paie.mois_activite,
                      p_historique_paie.date_fin,
                      p_historique_paie.mois_paie,
                      p_historique_paie.date_paie,
                      0,
                      0,
                      sum(heure_payee) as heure_payee,
                      sum(heure_travaillee) as heure_travaillee,
                      0,
                      sum(montant_brut) as montant_brut,
                      0,
                      0,
                      0,
                      sum(montant_cotisation_salarie) as montant_cotisation_salarie,
                      0,
                      sum(montant_cotisation_patronale) as montant_cotisation_patronale,
                      0,
                      0,
                      sum(montant_net_imposable_salarie) as montant_net_imposable_salarie,
                      sum(montant_net_a_payer_salarie) as montant_net_a_payer_salarie,
                      p_historique_paie.organisme_cotisation_id,
                      p_historique_paie.salarie_id
                    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, 24,25) as subq
                JOIN rh.p_salaries ON p_salaries.oid = subq.salarie_id
                JOIN w_totaux ON 1=1
                    AND w_totaux.matricule = p_salaries.matricule
                    AND w_totaux.date = subq.date_paie
				JOIN w_cumul ON true
                GROUP BY 1,2,3,4,5,6,7,8,9, 24,25,26
                HAVING 1!=1
                    OR sum(mnt_hp - heure_payee) != 0
                    OR sum(mnt_hw - heure_travaillee) != 0
                    OR sum(mnt_brut - montant_brut) != 0
                    OR sum(mnt_cotisation_salariale - montant_cotisation_salarie) != 0
                    OR sum(mnt_cotisation_patronale - montant_cotisation_patronale) != 0
                    OR sum(mnt_net_imposable_salarie - montant_net_imposable_salarie) != 0
                    OR sum(mnt_net_a_payer_salarie - montant_net_a_payer_salarie) != 0
            ;

            UPDATE rh.p_historique_paie
            SET date_debut = date_fin
            WHERE date_debut > date_fin
            ;

            -- Renseigner les heures contrats à partir de la rubriques d'heures salaire de base conventionnel lorsque le nombre d'heures contrat n'est pas renseigné.
            UPDATE rh.p_contrats_mois SET
                nombre_heures = 0
            WHERE (select count(*) > 0 from rh.t_listes join rh.t_listes_contenu on t_listes_contenu.liste_id = t_listes.oid where code = 'CTI_HCNT')
            ;

            UPDATE rh.p_contrats_mois SET
                nombre_heures = subq.nombre_heures
            FROM (
                SELECT
                    contrat_mois_id,
                    mois_paie,
                    sum(base) as nombre_heures
                FROM rh.p_historique_paie
                WHERE rubrique_id IN (select to_id from rh.t_listes join rh.t_listes_contenu on t_listes_contenu.liste_id = t_listes.oid where code = 'CTI_HCNT')
                GROUP BY 1,2) as subq
            WHERE 1=1
                AND p_contrats_mois.oid = subq.contrat_mois_id
                AND p_contrats_mois.mois_activite = subq.mois_paie
                AND nullif(p_contrats_mois.nombre_heures, 0) is null
            ;

            ]]></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
					w_profils.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
					JOIN rh.p_contrats ON p_contrats.oid = p_contrats_mois.contrat_id
					--JOIN w_contrats ON w_contrats.u_id_cont = p_contrats.numero_contrat
					JOIN w_profils ON 1=1
						AND w_profils.u_id_cont = p_contrats.numero_contrat
						AND base.cti_overlaps(w_profils.grh_dtdu, w_profils.grh_dtau, p_contrats_mois.date_debut, p_contrats_mois.date_fin)
				GROUP BY 1,2,3,4,5
			;

			-- @todo le faire 2 fois avec d'abord l'historique des affectations puis l'historique des contrats
			
			]]></sqlcmd>
		</NODE>
		<NODE label="Arrêts de travail">
			<sqlcmd><![CDATA[

			-- Création d'une table temporaire contenant 1 contrat pour 1 arret
			DROP TABLE IF EXISTS w_arrets
			;
			CREATE TEMP TABLE w_arrets AS
				SELECT
					ij_arret.ident,
					ij_arret.ste,
					ij_arret.etb,
					ij_arret.mat,
					ij_arret.motif,
					(date_part('year', ij_arret.dt_arret::date)::text||lpad(date_part('month',ij_arret.dt_arret::date), 2, '0'))::numeric AS mois_activite,
					ij_arret.dtdu::date as date_debut,
                    coalesce(ij_arret.dt_prolong, ij_arret.dtau, maladie.dtrepris - '1 day'::interval, acctravail.dtrep - '1 day'::interval, '2099-12-31'::date)::date as date_fin,
					coalesce(ij_arret.dt_prolong, ij_arret.dtau, maladie.dtrepris - '1 day'::interval, acctravail.dtrep - '1 day'::interval, '2099-12-31'::date)::date - dtdu::date as nbj,
					max(w_cnt.id_cont) as id_cont,
					(max(ARRAY[w_cnt.rang_contrat::text, w_cnt.u_id_cont::text]))[2] as u_id_cont
				FROM prod_sigems.ij_arret
                    left join prod_sigems.maladie on maladie.num_ij_arret = ij_arret.ident
                    left join prod_sigems.acctravail on acctravail.num_ij_arret = ij_arret.ident
					JOIN w_cnt on 1=1
						AND w_cnt.mat = ij_arret.mat
						AND base.cti_overlaps(ij_arret.dtdu::date, coalesce(ij_arret.dt_prolong, ij_arret.dtau, maladie.dtrepris - '1 day'::interval, acctravail.dtrep - '1 day'::interval, '2099-12-31'::date)::date, w_cnt.date_debut, w_cnt.date_fin)
                    JOIN w_ets ON 1=1
                        AND w_ets.ste = ij_arret.ste
                        AND w_ets.etbl = ij_arret.etb
				WHERE 1=1
					-- AND dtdu >= '2014-01-01'
					AND dtdu <= now()
					AND ij_arret.mat NOT IN (SELECT mat FROM w_exc_mat)
                    and ij_arret.id_liencontrat > 0
				GROUP BY 1,2,3,4,5,6,7,8,9
			;

			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_arrets.mois_activite,
					   w_arrets.date_debut,
					   w_arrets.date_fin,
					   (w_arrets.date_fin + INTERVAL '1 day')::date AS date_reprise,
					   t_motifs_arret.oid AS motif_arret_id,
					   0 AS precision_motif_arret_id,
					   w_arrets.nbj AS nb_jours
				FROM w_arrets
					JOIN prod_sigems.contrats_pb on contrats_pb.mat||'-'||contrats_pb.id_cont = w_arrets.u_id_cont
					JOIN rh.p_salaries ON p_salaries.matricule = w_arrets.mat
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_arrets.u_id_cont
					JOIN rh.t_motifs_arret ON t_motifs_arret.code_original = w_arrets.motif
			;

			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,
				nb_arret
				)
				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,
					1
				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[

			-- Création d'une table temporaire
			DROP TABLE IF EXISTS w_visites
			;
			CREATE TEMP TABLE w_visites AS
				SELECT
					vis_med.ste,
					vis_med.etb,
					vis_med.mat,
					vis_med.reclass as motif,
					(date_part('year', vis_med.dt_visite::date)::text||lpad(date_part('month', vis_med.dt_visite::DATE), 2, '0'))::NUMERIC AS mois_activite,
					vis_med.dt_visite::date as date,
					max(id_cont) as id_cont,
					(max(ARRAY[w_cnt.rang_contrat::text, w_cnt.u_id_cont::text]))[2] as u_id_cont
				FROM prod_sigems.vis_med
					JOIN w_cnt ON w_cnt.mat = vis_med.mat
						AND vis_med.dt_visite between dtdebu AND CASE WHEN dtsort IS DISTINCT FROM NULL THEN dtsort ELSE '2099-12-31' END
					JOIN prod_sigems.pers ON 1=1
                        AND pers.mat = vis_med.mat
                        AND pers.ste = vis_med.ste
                        AND pers.etb = vis_med.etb
				WHERE 1=1
					-- AND dt_visite >= '2014-01-01'
					AND c_anu <> 'S'
					AND vis_med.mat NOT IN (SELECT mat FROM w_exc_mat)
				GROUP BY 1,2,3,4,5,6
			;

			-- Peuplement de rh.p_visites_medicales
			TRUNCATE rh.p_visites_medicales
			;

			ALTER SEQUENCE rh.s_visites_medicales RESTART WITH 1
			;

			INSERT INTO rh.p_visites_medicales(
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				date,
				motif_visite_id
			)
				SELECT p_salaries.oid,
					   p_contrats.oid,
					   p_contrats_mois.oid,
					   w_visites.mois_activite,
					   w_visites.date,
					   t_motifs_visite.oid
				FROM w_visites
					JOIN rh.p_salaries ON p_salaries.matricule = w_visites.mat
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_visites.u_id_cont
					JOIN rh.p_contrats_mois ON p_contrats_mois.contrat_id = p_contrats.oid 
						AND	w_visites.date >= p_contrats_mois.date_debut
						AND	w_visites.date <= p_contrats_mois.date_fin
					JOIN rh.t_motifs_visite ON t_motifs_visite.code_original = w_visites.motif
			;

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

			-- Création d'une table temporaire
			DROP TABLE IF EXISTS w_accident
			;
			CREATE TEMP TABLE w_accident AS
				SELECT
					acctravail.soc,
					acctravail.etb,
					acctravail.mat,
					(date_part('year', acctravail.dtacc::date)::text||lpad(date_part('month', acctravail.dtacc::DATE), 2, '0'))::NUMERIC AS mois_activite,
					acctravail.dtacc::date as date,
					max(id_cont) as id_cont,
					acctravail.circst_stat as circonstance,
					acctravail.lieu as lieu,
					acctravail.nature_stat as nature,
					acctravail.siege_stat as siege,
					(max(ARRAY[w_cnt.rang_contrat::text, w_cnt.u_id_cont::text]))[2] as u_id_cont
				FROM prod_sigems.acctravail
					JOIN w_cnt ON w_cnt.mat = acctravail.mat
						AND acctravail.dtacc between dtdebu AND CASE WHEN dtsort IS DISTINCT FROM NULL THEN dtsort ELSE '2099-12-31' END
					JOIN prod_sigems.pers ON 1=1
                        AND pers.mat = acctravail.mat
                        AND pers.ste = acctravail.soc
                        AND pers.etb = acctravail.etb
				WHERE 1=1
					-- AND dtacc >= '2014-01-01'
					AND c_anu <> 'S'
					AND acctravail.mat NOT IN (SELECT mat FROM w_exc_mat)
				GROUP BY 1,2,3,4,5,7,8,9,10
			;

			-- Peuplement de rh.p_accident_travail
			TRUNCATE rh.p_accident_travail
			;

			ALTER SEQUENCE rh.s_accident_travail RESTART WITH 1
			;

			INSERT INTO rh.p_accident_travail(
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				date,
				accident_circonstance_id,
				accident_lieu_id,
				accident_nature_id,
				accident_siege_id
			)
				SELECT p_salaries.oid,
					   p_contrats.oid,
					   p_contrats_mois.oid,
					   w_accident.mois_activite,
					   w_accident.date,
					   t_accident_circonstance.oid,
					   t_accident_lieu.oid,
					   t_accident_nature.oid,
					   t_accident_siege.oid
				FROM w_accident
					JOIN rh.p_salaries ON p_salaries.matricule = w_accident.mat
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_accident.u_id_cont
					JOIN rh.p_contrats_mois ON p_contrats_mois.contrat_id = p_contrats.oid 
						AND	w_accident.date >= p_contrats_mois.date_debut
						AND	w_accident.date <= p_contrats_mois.date_fin
					JOIN rh.t_accident_circonstance ON t_accident_circonstance.code_original = w_accident.circonstance
					JOIN rh.t_accident_lieu ON t_accident_lieu.code_original = w_accident.lieu
					JOIN rh.t_accident_nature ON t_accident_nature.code_original = w_accident.nature
					JOIN rh.t_accident_siege ON t_accident_siege.code_original = w_accident.siege
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Formations">
			<sqlcmd><![CDATA[
			
			DROP TABLE IF EXISTS w_formation;

			CREATE temp TABLE w_formation (
				id serial,
				matricule CHARACTER VARYING(8),
				ste CHARACTER VARYING(2),
				etb CHARACTER VARYING(2),
				code_formation CHARACTER VARYING(4),
				date_formation TIMESTAMP,
				mois_activite NUMERIC,
				nbre_heures NUMERIC(6,2),
				n_org CHARACTER VARYING(20),
				id_cont INTEGER,
				date_debut TIMESTAMP,
				CONSTRAINT w_formation_pkey PRIMARY KEY (id)
			) WITHOUT OIDS
			;
			
			
			----------------------------------------------------------------------------------------------------
			-- * Insère les données
			-- * Zappe les employés suspendus sauf ceux dont le contrat est en cours (date de sortie
			--   nulle ou supérieure à date actuelle)
			-- * Zappe les entrées dont le code de formation n'est pas renseigné
			-- * Ne prend que les dates de formation > 01 Janvier 2014 et < date actuelle + 2 ans
			-- * Si une entrée a un code de formation et une date mais a un nombre d'heures à zéro,
			--   force le nombre d'heures à 1.00

			INSERT INTO w_formation (matricule, ste, etb, code_formation, date_formation, mois_activite, nbre_heures, n_org)
				(
					SELECT
						pform_pb.mat,
						pform_pb.ste,
						pform_pb.etb,
						pform_pb.id_formation,
						pform_pb.d_for,
						(date_part('year',pform_pb.d_for::date)::text||lpad(date_part('month', pform_pb.d_for::DATE), 2, '0'))::NUMERIC,
						CASE WHEN pform_pb.nb_hr > 0 THEN pform_pb.nb_hr ELSE 1.00 END,
						pform_pb.n_org
					FROM prod_sigems.pform_pb
						JOIN prod_sigems.pers ON 1=1
                            AND pers.mat = pform_pb.mat
                            AND pers.ste = pform_pb.ste
                            AND pers.etb = pform_pb.etb
						JOIN w_cnt ON w_cnt.mat = pform_pb.mat
					WHERE 1=1
						AND d_for < (CURRENT_DATE + INTEGER '731')
						AND (1!=1
							OR pers.c_anu <> 'S'
							OR (1=1
								AND pers.c_anu = 'S'
								AND w_cnt.date_fin > CURRENT_DATE))
						AND pform_pb.mat NOT IN (SELECT mat FROM w_exc_mat)
					GROUP BY 1,2,3,4,5,6,7,8
				UNION
					-- * Insère les données dont la date de formation n'est pas encore renseignée
					-- * Force à 0.00 le nombre d'heures de formation
					-- * Zappe les employés suspendus sauf ceux dont le contrat est en cours (date de sortie
					--   nulle ou supérieure à date actuelle)
					-- * Zappe les entrées dont le code de formation n'est pas renseigné
					SELECT 
						pform_pb.mat,
						pform_pb.ste,
						pform_pb.etb,
						pform_pb.id_formation,
						pform_pb.d_for,
						(date_part('year',pform_pb.d_for::date)::text||lpad(date_part('month',pform_pb.d_for::DATE),2,'0'))::NUMERIC,
						0.00 AS nb_hr,
						n_org
					FROM prod_sigems.pform_pb
						JOIN prod_sigems.pers ON 1=1
                            AND pers.mat = pform_pb.mat
                            AND pers.ste = pform_pb.ste
                            AND pers.etb = pform_pb.etb
						JOIN w_cnt ON w_cnt.mat = pform_pb.mat
					WHERE 1=1
						AND pform_pb.d_for IS NULL
						AND (1!=1
							OR pers.c_anu <> 'S'
							OR (1=1
								AND pers.c_anu = 'S'
								AND w_cnt.date_fin > CURRENT_DATE))
						AND pform_pb.mat NOT IN (SELECT mat FROM w_exc_mat)
					GROUP BY 1,2,3,4,5,6,7,8
				)
			;
			
			
			----------------------------------------------------------------------------------------------------
			-- * Insère la date de début de contrat la plus proche de la date de formation
			--   Servira si la date de formation ne rentre dans aucun contrat

			UPDATE w_formation
			SET date_debut = 
				(
				SELECT MAX(dtdebu) 
				FROM w_cnt
				WHERE 1=1
					AND w_cnt.mat = matricule
					AND date_formation IS DISTINCT FROM NULL
					AND dtdebu < date_formation
				)
			;
			
			
			--    select * from w_formation order by 2
			----------------------------------------------------------------------------------------------------
			-- * Cherche les lignes qui ont en commun le matricule, le code, la date et les heures
			-- * Supprime celle qui a le plus petit id (normalement qui a été saisie en premier)

			DELETE 
			FROM w_formation
			WHERE id NOT IN
				(
				SELECT	MIN(dup.id)
				FROM	w_formation AS dup
				GROUP BY dup.matricule, dup.code_formation, dup.date_formation, dup.nbre_heures
				)
			;
			
			
			--    select * from w_formation order by 2
			----------------------------------------------------------------------------------------------------
			-- * Cherche les lignes qui ont en commun le matricule, le code et la date
			-- * Supprime celle qui a le plus petit id (normalement qui a été saisie en premier)

			DELETE
			FROM w_formation
			WHERE id IN
				(
				SELECT	MIN(id)
				FROM	w_formation
				GROUP BY matricule, code_formation, date_formation
				HAVING COUNT(date_formation) > 1
				ORDER BY 1
				)
			;
			
			
			--    select * from w_formation order by 2
			----------------------------------------------------------------------------------------------------
			-- * Cherche les entrées où la date de formation n'est comprise dans aucun intervalle de contrat
			-- * Remplace la date de formation par la plus récente date de début de contrat antérieure
			--   à la date de formation
			-- * Recalcule le champ mois_activite avec la nouvelle date

			UPDATE w_formation
			SET date_formation = date_debut, mois_activite = (date_part('year',date_formation::date)::text||lpad(date_part('month', date_formation::DATE), 2, '0'))::NUMERIC
			WHERE id IN
				(
				SELECT id
				FROM w_formation
					JOIN w_cnt ON w_cnt.mat = w_formation.matricule
					JOIN prod_sigems.pers ON 1=1
                            AND pers.mat = w_cnt.mat
                            AND pers.ste = w_cnt.soc
                            AND pers.etb = w_cnt.etb
				WHERE 
					id NOT IN (
						SELECT id
						FROM w_formation
							JOIN w_cnt ON w_cnt.mat = w_formation.matricule
						GROUP BY w_formation.id, w_formation.date_formation, w_cnt.date_debut, w_cnt.date_fin
						HAVING w_formation.date_formation BETWEEN w_cnt.date_debut AND w_cnt.date_fin
						ORDER BY 1
					)
				GROUP BY 1
				ORDER BY 1
				)
			AND date_formation IS DISTINCT FROM NULL
			;
			
			
			--    select * from w_formation order by 2
			----------------------------------------------------------------------------------------------------
			-- * Cherche les cas où un salarié fait au moins deux formations le même jour pour un 
			--   total d'heures supérieur à 9. On considère alors qu'on est dans le cas d'une
			--   formation 'marathon' et on force tous les nombres d'heures de ces formations à 1.00
			
			UPDATE w_formation
			SET nbre_heures = 1.00
			WHERE id in (
				SELECT id 
				FROM w_formation 
				WHERE ARRAY[matricule::text, date_formation::text] in (
					SELECT ARRAY[matricule::text,date_formation::text]
					FROM w_formation
					WHERE date_formation IS NOT NULL
					GROUP BY 1
					HAVING sum (nbre_heures) > 9 AND COUNT (DISTINCT code_formation) > 1
				)
			)
			;
			
			
			--    select * from w_formation order by 2
			----------------------------------------------------------------------------------------------------
			-- 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,
							formation_date,
							mois_activite,
							nb_heures,
							organisateur
						)
				SELECT 	
					p_salaries.oid AS "salarie_oid",
					t_liste_formations.oid AS "formation_oid",
					w_formation.date_formation,
					w_formation.mois_activite,
					w_formation.nbre_heures,
					w_formation.n_org
				FROM w_formation
					JOIN rh.p_salaries ON p_salaries.matricule = w_formation.matricule
					JOIN rh.t_liste_formations ON w_formation.code_formation = t_liste_formations.code
				ORDER BY 1,2,3,4
			;

			
			--   select * from rh.p_formations order by 2
			----------------------------------------------------------------------------------------------------
			-- Rattache une formation qui n'a pas de date au contrat le plus récent du
			-- salarié concerné par la formation
			-- Met la date de la formation à 2099-12-31 et le mois_activite à 209912

			UPDATE rh.p_formations toto
			SET contrat_id =
				(
					SELECT
					(MAX(ARRAY[date_debut::text,oid::text]))[2]::bigint
					FROM rh.p_contrats cont
					WHERE cont.salarie_id = toto.salarie_id
				),
				formation_date = '2099-12-31'::DATE, mois_activite = 209912
			WHERE formation_date IS NULL
			;
			
			
			--   SELECT * FROM rh.p_formations order by 2
			----------------------------------------------------------------------------------------------------
			-- Rattache le numéro de contrat à la formation dont la date est comprise
			-- entre les dates de début et de fin dudit contrat
			-- Concerne les formations dont la date a été renseignée

			UPDATE rh.p_formations toto
			SET contrat_id =
				(
					SELECT	(MAX(ARRAY[date_debut::text,oid::text]))[2]::bigint
					FROM	rh.p_contrats cont
					WHERE	cont.salarie_id = toto.salarie_id
					AND		toto.formation_date <= cont.date_fin
					AND		toto.formation_date >= cont.date_debut
				)
			WHERE formation_date < '2099-12-31'
			;
			
			
			--    SELECT * FROM rh.p_formations order by 2
			----------------------------------------------------------------------------------------------------
			-- Rattache le contrat_mois_id de la formation pour les formations dont la date a été
			-- renseignée

			UPDATE rh.p_formations toto
			SET contrat_mois_id = 
				(
				SELECT 	oid
				FROM 	rh.p_contrats_mois cont
				WHERE 	cont.contrat_id = toto.contrat_id 
				AND 	cont.mois_activite = toto.mois_activite
				)
			WHERE	toto.formation_date < '2099-12-31'
			;

			
			--    SELECT * FROM rh.p_formations order by 2
			----------------------------------------------------------------------------------------------------
			-- Rattache le contrat_mois_id de la formation pour les formations dont la date n'a  pas été
			-- renseignée. On prendra dans ce cas le contrat_mois_id le plus élevé

			UPDATE	rh.p_formations toto
			SET 	contrat_mois_id = 
				(
				SELECT 	(MAX(ARRAY[date_debut::text,oid::text]))[2]::bigint
				FROM 	rh.p_contrats_mois cont
				WHERE 	cont.contrat_id = toto.contrat_id 
				)
			WHERE	toto.formation_date = '2099-12-31'
			;

			--   select * from rh.p_formations order by 2;
			-- BRET00 (1046)


			]]></sqlcmd>
		</NODE>
		<!--<NODE label="Handicap">
			<sqlcmd><![CDATA[
			
			DROP TABLE IF EXISTS w_handicap
			;
			
			CREATE TEMP TABLE w_handicap AS
				SELECT
					vis_med.mat,
					vis_med.handicap,
					vis_med.tx_invalid,
					vis_med.dtdeb_cotorep,
					vis_med.dtfin_cotorep,
					vis_med.categorie
				FROM
					prod_sigems.vis_med
					JOIN prod_sigems.pers ON 1=1
                            AND pers.mat = vis_med.mat
                            AND pers.ste = vis_med.ste
                            AND pers.etb = vis_med.etb
				WHERE 1=1
					AND vis_med.handicap <> ''
					AND pers.c_anu <> 'S'
					AND vis_med.mat NOT IN (SELECT mat FROM w_exc_mat)
				GROUP BY 1,2,3,4,5,6
			;
			
			TRUNCATE rh.p_handicap
			;
			
			ALTER SEQUENCE rh.s_handicap RESTART WITH 1
			;
			
			INSERT INTO rh.p_handicap (
				salarie_id,
				taux_incapacite,
				date_effet,
				date_echeance,
				categorie_cotorep)
				SELECT
					p_salaries.oid,
					w_handicap.tx_invalid::text,
					w_handicap.dtdeb_cotorep,
					w_handicap.dtfin_cotorep,
					w_handicap.categorie
				FROM w_handicap
					JOIN rh.p_salaries ON p_salaries.matricule = w_handicap.mat
			;	

			]]></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>
