<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
		<NODE label="Pre-traitements des tables prestataire">
			<sqlcmd><![CDATA[

            -- Création d'une table établissement pour filtrer les données.
            DROP TABLE IF EXISTS w_ets
            ;
            
            CREATE TEMP TABLE w_ets AS
                SELECT *
                FROM prod_rhplace.etablt
                WHERE eta_id IN (SELECT rhp_in('siren'))
            ;

			-- Utilisation de vues pour les tables ayant des dates sous forme d'entiers.
            DROP TABLE IF EXISTS w_salarie
            ;
            
            CREATE TEMP TABLE w_salarie AS
			 	SELECT
			 		to_timestamp((sal_dnaiss - 25567) * 86400)::date AS v_sal_dnaiss,
			 		to_timestamp((sal_dat_cemp - 25567) * 86400)::date AS v_sal_dat_cemp,
			 		salarie.*
		   		FROM prod_rhplace.salarie
                    JOIN w_ets ON w_ets.ent_id = salarie.ent_id
			;

			DROP VIEW IF EXISTS prod_rhplace.v_h_cnt_trav
			;

			CREATE OR REPLACE VIEW prod_rhplace.v_h_cnt_trav AS 
                select
                    ent_id,
                    sal_matr,
                    to_timestamp((con_du - 25567) * 86400)::date AS date_debut,
                    CASE WHEN con_au = 0 THEN '2099-12-31'::date ELSE to_timestamp((con_au - 25567) * 86400)::date END AS date_fin
                from prod_rhplace.h_contrat
			;

			DROP TABLE IF EXISTS w_cnt
			;
			
			CREATE TEMP TABLE w_cnt AS
				SELECT
					sal_matr||'-'||rank() OVER (PARTITION BY sal_matr order by date_debut) AS numero_contrat,
					date_fin - date_debut + 1 AS duree,
					v_h_cnt_trav.*
				FROM prod_rhplace.v_h_cnt_trav
                    JOIN w_ets ON w_ets.ent_id = v_h_cnt_trav.ent_id
			;

			-- #correction : si date_fin < date_debut alors date_fin = '2099-12-31'
			UPDATE w_cnt
			SET
				date_fin = '2099-12-31'::date,
				duree = '2099-12-31'::date - date_debut + 1
			WHERE date_fin < date_debut
			;


            DROP TABLE IF EXISTS w_h_contrat
            ;
            
            CREATE TEMP TABLE w_h_contrat AS
			 	SELECT
			 		to_timestamp((con_du - 25567) * 86400)::date AS date_debut,
			 		CASE WHEN con_au = 0 THEN '2099-12-31'::date ELSE to_timestamp((con_au - 25567) * 86400)::date END AS date_fin,
			 		h_contrat.*
		   		FROM prod_rhplace.h_contrat
                    JOIN w_ets ON w_ets.ent_id = h_contrat.ent_id
			;

			DROP TABLE IF EXISTS w_ligne
            ;
            
            CREATE TEMP TABLE w_ligne AS
				SELECT *
				FROM prod_rhplace.ligne
			;

            DROP TABLE IF EXISTS w_bulletin
            ;
            
            CREATE TEMP TABLE w_bulletin AS
                WITH ligne as (
                    select
                        bul_id,
                        bool_or(pla_id = 1350) as forfait_jour,
                        -- POP et STC fonctionnent avec 3162; FIEF avec 1363 pour les CDD et 1365 pour les CDI.
                        sum(case when pla_id in (1363, 1365, 3162) then lig_bas1 else 0 end) as lig_bas1
                    from w_ligne as ligne
                        JOIN w_ets ON w_ets.ent_id = ligne.ent_id
                    group by 1)
			 	SELECT
			 		to_timestamp((bul_deb - 25567) * 86400)::date AS date_debut,
			 		to_timestamp((bul_fin - 25567) * 86400)::date AS date_fin,
			 		to_timestamp((bul_pai - 25567) * 86400)::date AS date_paie,
                    forfait_jour, -- Vrai lorsqu'il s'agit d'un bulletin forfait jour (présence de la rubrique 1350).
                    case when forfait_jour then bul_horf / 20.67 else lig_bas1 / 151.67 end as etp,
                    case when forfait_jour then  (bul_horf / 20.67) * 151.67
                        else lig_bas1
                        end as bul_heure_payees,
			 		bulletin.*
		   		FROM prod_rhplace.bulletin
                    JOIN w_ets ON w_ets.ent_id = bulletin.ent_id
                    JOIN ligne on ligne.bul_id = bulletin.bul_id
		   		WHERE 1=1
                    AND bul_type = 'V' -- on ne conserve que les bulletins corrects.
                    AND bul_pai > 41637 -- 2013-12-31
			;

            -- Table des lignes de paies forfait jour (création d'une rubrique 4540 qui n'existe pas dans ces bulletins).
            DROP TABLE IF EXISTS w_ligne_fj
            ;
            
            CREATE TEMP TABLE w_ligne_fj AS
                select
                    ent_id,
                    bul_id,
                    '4540'::text as code,
                    bul_horf::numeric as nombre,
                    bul_heure_payees::numeric as base
                from w_bulletin
                where forfait_jour
            ;

			-- Alimentation de la base de la rubrique forfait 1350 avec la valeur de 1363, 1365 ou 3162.
			UPDATE w_ligne SET
				lig_bas1 = w_ligne_fj.base
			FROM w_ligne_fj
			WHERE 1=1
				AND w_ligne.bul_id = w_ligne_fj.bul_id
				AND w_ligne.pla_id = 1350
			;

			-- Conversion en heures de la base de la rubrique d'absence E/S 2250 lorsqu'il s'agit de forfaits jours car exprimée en jours.
			UPDATE w_ligne SET
				lig_bas1 = (lig_bas1 / 20.67) * 151.67
			FROM w_ligne_fj
			WHERE 1=1
				AND w_ligne.bul_id = w_ligne_fj.bul_id
				AND w_ligne.pla_id = 2250
			;

            CREATE INDEX w_bulletin_1 ON w_bulletin USING btree (ent_id)
            ;
            CREATE INDEX w_bulletin_2 ON w_bulletin USING btree (bul_id)
            ;

            DROP TABLE IF EXISTS w_h_coeff
            ;
            
            CREATE TEMP TABLE w_h_coeff AS
			 	SELECT
			 		to_timestamp((coe_du - 25567) * 86400)::date AS date_debut,
                    CASE WHEN lead(coe_du) over w is null THEN '2099-12-31'::date ELSE to_timestamp((coalesce(lead(coe_du) over w - 1, 99999) - 25567) * 86400)::date END as date_fin,
			 		h_coeff.*
		   		FROM prod_rhplace.h_coeff
                    JOIN w_ets ON w_ets.ent_id = h_coeff.ent_id
                window w as (partition by sal_matr order by coe_du)
			;

            DROP TABLE IF EXISTS w_h_es
            ;
            
            CREATE TEMP TABLE w_h_es AS
			 	SELECT
			 		to_timestamp((e_s_date - 25567) * 86400)::date AS date_debut,
			 		CASE WHEN e_s_dates = 0 THEN '2099-12-31'::date ELSE to_timestamp((e_s_dates - 25567) * 86400)::date END AS date_fin,
			 		h_es.*
		   		FROM prod_rhplace.h_es
                    JOIN w_ets ON w_ets.ent_id = h_es.ent_id
			;

            -- Statuts
            DROP TABLE IF EXISTS w_h_stprof
            ;

            CREATE TEMP TABLE w_h_stprof AS 
                SELECT
                    to_timestamp((stp_date - 25567) * 86400)::date AS date_debut,
                    CASE WHEN lead(stp_date) over w is null THEN '2099-12-31'::date ELSE to_timestamp((coalesce(lead(stp_date) over w - 1, 99999) - 25567) * 86400)::date END as date_fin,
                    h_stprof.*
                FROM prod_rhplace.h_stprof
                    JOIN w_ets ON w_ets.ent_id = h_stprof.ent_id
                window w as (partition by sal_matr order by stp_date)
            ;

            DROP TABLE IF EXISTS w_rub
            ;
            
            CREATE TEMP TABLE w_rub AS
                with rub_per as (
                    select 
                        pla_id,
                        pla_type,
                        pla_int,
                        pla_dval,
                        coalesce(nullif(pla_tot, ''), 'N') as pla_tot, -- par défaut on met 'N'.
                        coalesce(lead(pla_dval) over (partition by pla_id order by pla_dval) - 1, 99999) as pla_fval
                    from prod_rhplace.plap)
                ,rub_filter as (
                    select *
                    from rub_per
                    where false
                        OR 41638 between  pla_dval and pla_fval -- 41638 = 2014-01-01
                        OR pla_dval >= 41638)
                ,clustering as (
                    select
                        pla_id,
                        pla_type,
                        pla_int,
                        pla_dval,
                        pla_fval,
                        pla_tot,
                        case when pla_tot != coalesce(lag(pla_tot) over w, 'C') then true else null end as new_cluster
                    from rub_filter
                    window w as (partition by pla_id order by pla_dval))
                ,assigned_clustering as (
                    select
                        *
                        , count(new_cluster) over (
                        partition by pla_id
                          order by  pla_dval
                          rows unbounded preceding
                        ) as cluster_id
                    from clustering)
                ,tmp_rubs as (
                    select 
                        pla_id,
                        pla_type,
                        pla_int,
                        pla_tot,
                        min(pla_dval) as pla_dval,
                        max(pla_fval) as pla_fval
                    from assigned_clustering
                    group by 1,2,3,4,cluster_id)
                select
                    pla_id,
                    pla_type,
                    pla_int,
                    pla_tot,
                    case when count(*) over (partition by pla_id) > 1 
                        then
                            case when row_number() over (partition by pla_id order by pla_dval desc) = 1
                                then pla_id
                                else pla_id||'_'||to_char(to_timestamp((pla_dval - 25567) * 86400)::date, 'DD/MM/YYYY')
                            end
                        else pla_id end as pla_code,
                    pla_id||'_'||to_char(to_timestamp((pla_dval - 25567) * 86400)::date, 'YYYYMMDD') as pla_code_original,
                    pla_dval,
                    pla_fval
                from tmp_rubs
            ;

			]]></sqlcmd>
		</NODE>
		<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_etab
            ;

            CREATE TEMP TABLE w_etab AS
                SELECT
					ent_siren,
					eta_nic,
					societe.ent_id as codeetab
				FROM prod_rhplace.societe
					JOIN prod_rhplace.etablt ON societe.ent_id = etablt.ent_id
				WHERE 1!=1
                    OR ent_siren      IN (SELECT rhp_in('siren')) -- Soit un ou plusieurs SIREN ont été défini,
                    OR ent_siren||eta_nic IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs SIRET,
                    OR societe.ent_id   IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs codes établissement.
				GROUP BY 1,2,3
            ;
			
			-- Màj des Entreprises
			INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court, siren)
				SELECT 
					ent_id, 
					ent_id, 
					ent_rais, 
					substr(ent_rais, 1, 50),
					societe.ent_siren
				FROM prod_rhplace.societe
					JOIN w_etab ON w_etab.codeetab = societe.ent_id
				WHERE ent_id NOT IN (SELECT code_original FROM rh.t_entreprises)
				GROUP BY 1,2,3,4,5
			;
			
			with ent as (
                SELECT
                    t_entreprises.oid,
                    societe.ent_siren as siren
                FROM rh.t_entreprises
                    JOIN prod_rhplace.societe on societe.ent_id = 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_original, code, texte, texte_court, entreprise_id, siret)
				SELECT 
					eta_id, 
					eta_id, 
					eta_rais, 
					substr(eta_rais, 1, 50), 
					t_entreprises.oid,
					societe.ent_siren||etablt.eta_nic
				FROM prod_rhplace.etablt
					JOIN rh.t_entreprises ON t_entreprises.code_original = ent_id
					JOIN prod_rhplace.societe ON societe.ent_id = etablt.ent_id
				WHERE eta_id NOT IN (SELECT code_original FROM rh.t_etablissements)
				GROUP BY 1,2,3,4,5,6
			;
			
			with eta as (
                SELECT
                    t_etablissements.oid,
                    ent_siren||etablt.eta_nic as siret
                FROM rh.t_etablissements
                    JOIN prod_rhplace.societe ON societe.ent_id = t_etablissements.code_original
					JOIN prod_rhplace.etablt on eta_id = 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_original, code, texte, texte_court)
				SELECT lower(ins_id), lower(ins_id), lower(ins_id), substr(lower(ins_id), 1, 50)
				FROM prod_rhplace.h_insee_emp
                    JOIN w_ets ON w_ets.ent_id = h_insee_emp.ent_id
				WHERE lower(ins_id) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
				GROUP BY 1,2,3,4
			;

			-- [NON] Màj des groupes cotisants.
			
			-- Màj des motifs de début de contrat.
			INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
				SELECT mes_id||'|'||moe_id, mes_id||'-'||moe_id, mes_lib||' - '||moe_lib, substr(mes_lib||' - '||moe_lib, 1, 50)
                FROM prod_rhplace.ar_motif_e_s, prod_rhplace.ar_mot_emb 
                WHERE 1=1
                    AND mes_es = 'E'
                    AND mes_id||'|'||moe_id NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
                GROUP BY 1,2,3,4
			;

			-- Màj des motifs de fin de contrat
			INSERT INTO rh.t_motifs_fin_contrat(code_original, code, texte, texte_court)
				SELECT mes_id, mes_id, mes_lib, substr(mes_lib, 1, 50)
                FROM prod_rhplace.ar_motif_e_s
                WHERE 1=1
                    AND mes_es = 'S'
                    AND mes_id 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_original, code, texte, texte_court)
				SELECT pay_id, pay_id, pay_nat, substr(pay_nat, 1, 50)
				FROM prod_rhplace.ar_nation
				WHERE pay_id NOT IN (SELECT code_original FROM rh.t_nationalites)
				GROUP BY 1,2,3,4
			;
			
			-- [NON] Màj des organismes de cotisation.
			
			-- Màj des qualifications.
            INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
                SELECT emp_id, emp_id, emp_lib, substr(emp_lib, 1, 50)
                FROM prod_rhplace.ar_emploi
                    JOIN w_ets ON w_ets.ent_id = ar_emploi.ent_id
                WHERE emp_id NOT IN (SELECT code_original FROM rh.t_qualifications)
                GROUP BY 1,2,3,4
            ;
			
			-- Màj des rubriques
			INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
				SELECT 
					pla_code_original,
                    pla_code,
                    pla_int,
                    substr(pla_int, 1, 50),
					-1
				FROM w_rub
				WHERE pla_code_original NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

            -- On met à jour le code affiché de toutes les rubriques.
            update rh.t_rubriques set
                code = rub.pla_code
            from w_rub as rub
            where 1=1
                AND t_rubriques.code_original = rub.pla_code_original
                AND t_rubriques.code != rub.pla_code
            ;
			
			-- 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)
			;

			-- Màj des situations de famille (non profil)
			INSERT INTO rh.t_situations_famille(code_original, code, texte, texte_court)
				SELECT fam_id, fam_id, fam_lib, substr(fam_lib, 1, 50)
				FROM prod_rhplace.ar_sit_fam
				WHERE fam_id 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_original, code, texte, texte_court)
				SELECT ctr_id, ctr_id, ctr_lib, substr(ctr_lib,1,50)
				FROM prod_rhplace.ar_contrat
				WHERE ctr_id 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_original, code, texte, texte_court)
                SELECT stp_id, stp_id, stp_lib, substr(stp_lib, 1, 50)
                FROM prod_rhplace.ar_stprof
                WHERE stp_id NOT IN (SELECT code_original FROM rh.t_statuts)
            ;

			-- Màj des types de temps de travail
			INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
					SELECT cem_id, cem_id, cem_id, substr(cem_id, 1, 50)
					FROM prod_rhplace.h_cemploi
                        JOIN w_ets ON w_ets.ent_id = h_cemploi.ent_id
					WHERE cem_id NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
					GROUP BY 1,2,3,4
				UNION
					SELECT
						cem_id::text||coalesce(tem_taux::text, ''),
						cem_id::text||coalesce(tem_taux::text, ''),
						cem_id::text||coalesce(tem_taux::text, ''),
						substr(cem_id::text||coalesce(tem_taux::text, ''), 1, 50)
					FROM prod_rhplace.h_cemploi
                        JOIN w_ets ON w_ets.ent_id = h_cemploi.ent_id
						left join prod_rhplace.h_tempart ON 1=1
					WHERE cem_id::text||coalesce(tem_taux::text, '') NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
					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 h_typ_hor.hth_id, h_typ_hor.hth_id, h_typ_hor.hth_id, substr(h_typ_hor.hth_id, 1, 50)
				FROM prod_rhplace.h_typ_hor
                    JOIN w_ets ON w_ets.ent_id = h_typ_hor.ent_id
				WHERE h_typ_hor.hth_id NOT IN (SELECT code_original FROM rh.t_types_horaire)
				GROUP BY 1,2,3,4
			;

			-- Màj des services
            INSERT INTO rh.t_services(code_original, code, texte, texte_court)
                SELECT zl1_id, zl1_id, zl1_lib, substr(zl1_lib, 1, 50)
                FROM prod_rhplace.ar_z1local
                    JOIN w_ets ON w_ets.ent_id = ar_z1local.ent_id
                WHERE zl1_id NOT IN (SELECT code_original FROM rh.t_services)
                GROUP BY 1,2,3,4
            ;

			-- [NON] Màj des spécialités.
			
			-- Màj des codes emploi
			INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
				SELECT mod_id, mod_id, mod_lib, substr(mod_lib, 1, 50)
				FROM prod_rhplace.ar_modele
                    JOIN w_ets ON w_ets.ent_id = ar_modele.ent_id
				WHERE mod_id NOT IN (SELECT code_original FROM rh.t_codes_emploi)
				GROUP BY 1,2,3,4
			;

			-- Màj des comptes.
			INSERT INTO rh.t_compte(code_original, code, texte, texte_court)
				SELECT cpt_cle, substr(cpt_cpt1, 2, 6), cpt_lib, substr(cpt_lib, 1, 50)
				FROM prod_rhplace.ar_compte
				WHERE 1=1
					AND length(trim(cpt_lib)) > 0
					AND cpt_cle NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;
			
			-- [NON] Màj des sociétés d'interim

			-- Màj des grilles
			INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
				SELECT cat_id, cat_id, cat_lib, substr(cat_lib, 1, 50)
                FROM prod_rhplace.ar_categ
                    JOIN w_ets ON w_ets.ent_id = ar_categ.ent_id
                WHERE cat_id 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 coe_val, coe_val, coe_val, coe_val
                FROM w_h_coeff
                WHERE coe_val NOT IN (SELECT code_original FROM rh.t_grilles_groupes)
                GROUP BY 1
            ;

			-- [NON] Màj des motifs d'arret
			
			-- [NON] Màj des précisions du motif d'arrêt
			
			-- [NON] Màj des motifs de visite médicale

			-- [NON] Màj des circonstances d'accident du travail

			-- [NON] Màj des lieux d'accident du travail

			-- [NON] Màj de la nature de l'accident du travail

			-- [NON] Màj des sièges d'accident du travail

			-- [NON] Màj des listes de formations
			
			-- [NON] Màj des sections analytiques compta
			
			-- [NON] Màj des sections analytiques paie

			]]></sqlcmd>
		</NODE>
        <NODE label="Paramétrage des rubriques">
            <sqlcmd><![CDATA[

            -- Pré-paramétrage automatique des rubriques (au mieux).
            -- Cette requête n'intervient pas sur les rubriques paramétrées à la main.
            -- s_* (source_) :
            --   - 0 = nombre
            --   - 1 = base
            --   - 2 = taux salarial
            --   - 3 = montant salarial
            --   - 4 = taux patronal
            --   - 5 = montant patronal
            --   - 6 = montant salarial + montant patronal


            DROP TABLE IF EXISTS w_rub_affectation
            ;
            
            CREATE TEMP TABLE w_rub_affectation AS
                select
                    pla_id,
                    pla_type,
                    pla_int,
                    pla_dval,
                    pla_fval,
                    pla_tot,
                    pla_code,
                    pla_code_original,
                    pla_type::int in (15, 55, 65, 80) as p_cumul,
                    -- Rubrique de détail
                    pla_type::int in (5, 10, 50, 60, 70, 75, 85) as p_detail,
                    -- Nombre
                    pla_type::int in (5, 10, 50, 60, 70, 75, 85) p_nombre,
                    0 as s_nombre,
                    1 as c_nombre,
                    -- Base
                    pla_type::int in (5, 10, 50, 60, 70, 75, 85) as p_base,
                    1 as s_base,
                    1 as c_base,
                    -- Heures payées
                    false as p_heures_payees,
                    0 as s_heures_payees,
                    1 as c_heures_payees,
                    -- Heures travaillées
                    false as p_heures_travaillees,
                    0 as s_heures_travaillees,
                    1 as c_heures_travaillees,
                    -- Masse salariale
                    pla_type::int in (5, 10, 15, 50, 55) as p_masse_salariale,
                    case
                        when pla_type::int in (5, 10, 15) then 3
                        when pla_type::int in (50, 55) then 5
                        else 3
                    end as s_masse_salariale,
                    case
                        when pla_type::int in (5, 10, 15) then 1
                        when pla_type::int in (50, 55) then -1  -- tous les montants patronaux sont déjà signés négativement donc -1 pour ce coeff.
                        else 1
                    end as c_masse_salariale,
                    -- Brut
                    pla_type::int in (5, 10, 15) as p_brut,
                    3 as s_brut,
                    1 as c_brut,
                    -- Avantages en nature
                    false as p_avantage_nature,
                    3 as s_avantage_nature,
                    1 as c_avantage_nature,
                    -- Frais imposable
                    false as p_frais_imposables,
                    3 as s_frais_imposables,
                    1 as c_frais_imposables,
                    -- Cotisations salariales
                    pla_type::int in (50, 55) as p_cotisation_salarie,
                    3 as s_cotisation_salarie,
                    1 as c_cotisation_salarie,
                    -- Cotisations patronales
                    pla_type::int in (50, 55) as p_cotisation_patronale,
                    5 as s_cotisation_patronale,
                    -1 as c_cotisation_patronale, -- tous les montants patronaux sont déjà signés négativement donc -1 pour ce coeff.
                    -- OD/Net salariales
                    pla_type::int in (15, 55, 60, 70, 75, 80, 85) as p_od_net_salarie,
                    3 as s_od_net_salarie,
                    case when pla_type::int = 80 then -1 else 1 end as c_od_net_salarie,
                    -- OD/Net patronales
                    false as p_od_net_patronale,
                    5 as s_od_net_patronale,
                    1 as c_od_net_patronale,
                    -- Net imposable
                    pla_type::int in (5, 10, 50, 60, 65) as p_net_imposable,
                    3 as s_net_imposable,
                    1 as c_net_imposable,
                    -- Net à payer
                    pla_type::int in (5, 10, 50, 60, 70, 75, 80, 85) p_net_a_payer,
                    3 as s_net_a_payer,
                    1 as c_net_a_payer
                from w_rub
                where pla_tot = 'O' -- que les rubriques qui servent à calculer les totaux.
            ;

            update rh.t_rubriques set
                p_cumul = rub.p_cumul,
                p_detail = rub.p_detail,
                p_nombre = rub.p_nombre,
                s_nombre = rub.s_nombre,
                c_nombre = rub.c_nombre,
                p_base = rub.p_base,
                s_base = rub.s_base,
                c_base = rub.c_base,
                p_heures_payees = rub.p_heures_payees,
                s_heures_payees = rub.s_heures_payees,
                c_heures_payees = rub.c_heures_payees,
                p_heures_travaillees = rub.p_heures_travaillees,
                s_heures_travaillees = rub.s_heures_travaillees,
                c_heures_travaillees = rub.c_heures_travaillees,
                p_masse_salariale = rub.p_masse_salariale,
                s_masse_salariale = rub.s_masse_salariale,
                c_masse_salariale = rub.c_masse_salariale,
                p_brut = rub.p_brut,
                s_brut = rub.s_brut,
                c_brut = rub.c_brut,
                p_avantage_nature = rub.p_avantage_nature,
                s_avantage_nature = rub.s_avantage_nature,
                c_avantage_nature = rub.c_avantage_nature,
                p_frais_imposables = rub.p_frais_imposables,
                s_frais_imposables = rub.s_frais_imposables,
                c_frais_imposables = rub.c_frais_imposables,
                p_cotisation_salarie = rub.p_cotisation_salarie,
                s_cotisation_salarie = rub.s_cotisation_salarie,
                c_cotisation_salarie = rub.c_cotisation_salarie,
                p_cotisation_patronale = rub.p_cotisation_patronale,
                s_cotisation_patronale = rub.s_cotisation_patronale,
                c_cotisation_patronale = rub.c_cotisation_patronale,
                p_od_net_salarie = rub.p_od_net_salarie,
                s_od_net_salarie = rub.s_od_net_salarie,
                c_od_net_salarie = rub.c_od_net_salarie,
                p_od_net_patronale = rub.p_od_net_patronale,
                s_od_net_patronale = rub.s_od_net_patronale,
                c_od_net_patronale = rub.c_od_net_patronale,
                p_net_imposable = rub.p_net_imposable,
                s_net_imposable = rub.s_net_imposable,
                c_net_imposable = rub.c_net_imposable,
                p_net_a_payer = rub.p_net_a_payer,
                s_net_a_payer = rub.s_net_a_payer,
                c_net_a_payer = rub.c_net_a_payer
            from w_rub_affectation as rub
            where 1=1
                AND t_rubriques.code_original = rub.pla_code_original
                AND NOT t_rubriques.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)
                with ligne as (
                        select
                            bul_id,
                            ligne.ent_id,
                            pla_id,
                            lig_bas1,
                            lig_bas2,
                            lig_mont1,
                            lig_mont2
                        from w_ligne as ligne
                            JOIN w_ets ON w_ets.ent_id = ligne.ent_id
                    union all
                        select
                            bul_id,
                            ent_id,
                            code as pla_id,
                            base as lig_bas1,
                            nombre as lig_bas2,
                            0 as lig_mont1,
                            0 as lig_mont2
                        from w_ligne_fj)
				select 
					t_etablissements.entreprise_id AS entreprise_id,
					t_etablissements.oid as etablissement_id,
					substr(bulletin.bul_id, 1, 6)::numeric AS mois,
					count(distinct bulletin.sal_matr) AS nombre_salaries,
					sum(ligne.lig_mont1) AS montant_brut,
					sum(ligne.lig_bas1) AS nombre_heures
				from w_bulletin AS bulletin
                    JOIN w_ets ON w_ets.ent_id = bulletin.ent_id
					join ligne ON 1=1
                        AND ligne.bul_id = bulletin.bul_id
                        AND ligne.ent_id = bulletin.ent_id
                        AND ligne.pla_id IN ('BRUT', '4540', '1365')
                    join rh.t_etablissements ON t_etablissements.code_original = bulletin.eta_id
				group by 1,2,3
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Pre-traitement des Profils">
			<sqlcmd><![CDATA[
			
			-- Ventilation des statuts.
			DROP TABLE IF EXISTS w_h_categ
			;
			
			CREATE TEMP TABLE w_h_categ AS
				select
					max(t1.cat_id) AS cat_id,
					t1.sal_matr,
					t1.hca_date,
					max(to_timestamp((t1.hca_date - 25567) * 86400)::date) AS date_debut,
					min(coalesce(to_timestamp((t2.hca_date - 25567) * 86400)::date - '1 day'::interval, '2099-12-31')) AS date_fin
				from prod_rhplace.h_categ as t1
                    JOIN w_ets ON w_ets.ent_id = t1.ent_id
					left join prod_rhplace.h_categ AS t2 ON 1=1
						and t1.sal_matr = t2.sal_matr
                        and t1.ent_id = t2.ent_id
						and t1.hca_date < t2.hca_date
				group by 2,3
			;

			CREATE INDEX w_h_categ_1 ON w_h_categ USING btree (sal_matr)
			;
			CREATE INDEX w_h_categ_2 ON w_h_categ USING btree (cat_id)
			;
			CREATE INDEX w_h_categ_3 ON w_h_categ USING btree (date_debut)
			;
			CREATE INDEX w_h_categ_4 ON w_h_categ USING btree (date_fin)
			;

			-- Ventilation des categorie_socio_professionnelle.
			DROP TABLE IF EXISTS w_h_insee_emp
			;
			
			CREATE TEMP TABLE w_h_insee_emp AS
				select
					max (t1.ins_id) AS ins_id,
					t1.sal_matr,
					t1.hie_date,
					max(to_timestamp((t1.hie_date - 25567) * 86400)::date) AS date_debut,
					min(coalesce(to_timestamp((t2.hie_date - 25567) * 86400)::date - '1 day'::interval, '2099-12-31')) AS date_fin
				from prod_rhplace.h_insee_emp as t1
                    JOIN w_ets ON w_ets.ent_id = t1.ent_id
					left join prod_rhplace.h_insee_emp AS t2 ON 1=1
						and t1.sal_matr = t2.sal_matr
                        and t1.ent_id = t2.ent_id
						and t1.hie_date < t2.hie_date
				group by 2,3
			;

			CREATE INDEX w_h_insee_emp_1 ON w_h_insee_emp USING btree (sal_matr)
			;
			CREATE INDEX w_h_insee_emp_2 ON w_h_insee_emp USING btree (ins_id)
			;
			CREATE INDEX w_h_insee_emp_3 ON w_h_insee_emp USING btree (date_debut)
			;
			CREATE INDEX w_h_insee_emp_4 ON w_h_insee_emp USING btree (date_fin)
			;

			-- Ventilation des code_emploi.
			DROP TABLE IF EXISTS w_h_emploi
			;
			
			CREATE TEMP TABLE w_h_emploi AS
				select
					max(t1.emp_id) AS emp_id,
					t1.sal_matr,
					t1.hem_date,
					max(to_timestamp((t1.hem_date - 25567) * 86400)::date) AS date_debut,
					min(coalesce(to_timestamp((t2.hem_date - 25567) * 86400)::date - '1 day'::interval, '2099-12-31')) AS date_fin
				from prod_rhplace.h_emploi as t1
                    JOIN w_ets ON w_ets.ent_id = t1.ent_id
					left join prod_rhplace.h_emploi AS t2 ON 1=1
						and t1.sal_matr = t2.sal_matr
                        and t1.ent_id = t2.ent_id
						and t1.hem_date < t2.hem_date
				group by 2,3
			;

			CREATE INDEX w_h_emploi_1 ON w_h_emploi USING btree (sal_matr)
			;
			CREATE INDEX w_h_emploi_2 ON w_h_emploi USING btree (emp_id)
			;
			CREATE INDEX w_h_emploi_3 ON w_h_emploi USING btree (date_debut)
			;
			CREATE INDEX w_h_emploi_4 ON w_h_emploi USING btree (date_fin)
			;

			-- Ventilation des types de temps de travail.
			DROP TABLE IF EXISTS w_h_cemploi
			;
			
			CREATE TEMP TABLE w_h_cemploi AS
				select
					max(t1.cem_id) AS cem_id,
					t1.sal_matr,
					t1.hce_date,
					max(to_timestamp((t1.hce_date - 25567) * 86400)::date) AS date_debut,
					min(coalesce(to_timestamp((t2.hce_date - 25567) * 86400)::date - '1 day'::interval, '2099-12-31')) AS date_fin
				from prod_rhplace.h_cemploi as t1
                    JOIN w_ets ON w_ets.ent_id = t1.ent_id
					left join prod_rhplace.h_cemploi AS t2 ON 1=1
						and t1.sal_matr = t2.sal_matr
                        and t1.ent_id = t2.ent_id
						and t1.hce_date < t2.hce_date
				group by 2,3
			;

			CREATE INDEX w_h_cemploi_1 ON w_h_cemploi USING btree (sal_matr)
			;
			CREATE INDEX w_h_cemploi_2 ON w_h_cemploi USING btree (cem_id)
			;
			CREATE INDEX w_h_cemploi_3 ON w_h_cemploi USING btree (date_debut)
			;
			CREATE INDEX w_h_cemploi_4 ON w_h_cemploi USING btree (date_fin)
			;

			-- Ventilation des % des types de temps de travail partiel.
			DROP TABLE IF EXISTS w_h_tempart
			;
			
			CREATE TEMP TABLE w_h_tempart AS
				select
					max(t1.tem_taux) AS tem_taux,
					t1.sal_matr,
					t1.tem_date,
					max(to_timestamp((t1.tem_date - 25567) * 86400)::date) AS date_debut,
					min(coalesce(to_timestamp((t2.tem_date - 25567) * 86400)::date - '1 day'::interval, '2099-12-31')) AS date_fin
				from prod_rhplace.h_tempart as t1
                    JOIN w_ets ON w_ets.ent_id = t1.ent_id
					left join prod_rhplace.h_tempart AS t2 ON 1=1
						and t1.sal_matr = t2.sal_matr
                        and t1.ent_id = t2.ent_id
						and t1.tem_date < t2.tem_date
				group by 2,3
			;

			CREATE INDEX w_h_tempart_1 ON w_h_tempart USING btree (sal_matr)
			;
			CREATE INDEX w_h_tempart_2 ON w_h_tempart USING btree (tem_taux)
			;
			CREATE INDEX w_h_tempart_3 ON w_h_tempart USING btree (date_debut)
			;
			CREATE INDEX w_h_tempart_4 ON w_h_tempart USING btree (date_fin)
			;

            -- Ventilation des services.
            DROP TABLE IF EXISTS w_h_services
            ;
            
            CREATE TEMP TABLE w_h_services AS
                select
                    sal_matr,
                    zl1_id,
                    (to_timestamp((hz1_date - 25567) * 86400))::date as date_debut,
                    case when lead(hz1_date) over w is null then '2099-12-31'::date else ((to_timestamp((lead(hz1_date) over w - 25567) * 86400))::date - '1 day'::interval)::date end as date_fin
                from prod_rhplace.h_z1_loc
                    JOIN w_ets ON w_ets.ent_id = h_z1_loc.ent_id
                window w as (partition by sal_matr order by hz1_date)
            ;

            CREATE INDEX w_h_services_1 ON w_h_services USING btree (sal_matr)
            ;
            CREATE INDEX w_h_services_2 ON w_h_services USING btree (zl1_id)
            ;
            CREATE INDEX w_h_services_3 ON w_h_services USING btree (date_debut)
            ;
            CREATE INDEX w_h_services_4 ON w_h_services USING btree (date_fin)
            ;

            DROP TABLE IF EXISTS w_lmt
            ;

            CREATE TEMP TABLE w_lmt AS
                WITH w_lmt_cnt AS (
                    SELECT
                        sal_matr,
                        min(date_debut) as date_debut,
                        max(date_fin) as date_fin
                    FROM w_cnt
                    GROUP BY 1),
                w_lmt_bul as (
                    select
                        sal_matr,
                        min(date_debut) as date_debut,
                        max(date_fin) as date_fin
                    from w_bulletin
                    group by 1)
                SELECT
                    coalesce(salarie.sal_matr, w_lmt_cnt.sal_matr, w_lmt_bul.sal_matr) as sal_matr,
                    ins_id,
                    emp_id,
                    cal_id,
                    min(least(w_lmt_cnt.date_debut, w_lmt_bul.date_debut)) as min_date,
                    greatest(least(max(w_lmt_cnt.date_fin), current_date), max(w_lmt_bul.date_fin)) as max_date
                FROM prod_rhplace.salarie
                    left JOIN w_lmt_cnt ON w_lmt_cnt.sal_matr = salarie.sal_matr
                    left join w_lmt_bul on w_lmt_bul.sal_matr = salarie.sal_matr
                where coalesce(w_lmt_cnt.sal_matr, w_lmt_bul.sal_matr) is not null
                group by 1,2,3,4
            ;

			-- Croisement de tous les historiques salariés jour par jour.
			DROP TABLE IF EXISTS w_tmp_1
			;
			
			CREATE TEMP TABLE w_tmp_1 AS
                with cal as (
                    select
                        mois,
                        date,
                        count(*) over (partition by mois) as duree_mois
                    from base.p_calendrier)
				SELECT
					mat,
					mois,
					min(date_debut) AS date_debut,
					max(date_fin) AS date_fin,
					numero_contrat,
					bul_id,
					est_hors_periode,
					type_contrat_code_original,
					categorie_socio_professionnelle_code_original,
					qualification_code_original,
					statut_code_original,
                    grille_code_original,
					grille_groupe_code_original,
					type_temps_travail_code_original,
					motif_debut_code_original,
					motif_fin_code_original,
                    code_emploi_code_original,
                    service_code_original,
                    sum(etp_contrat) as etp_contrat,
                    sum(heures_contrat) as heures_contrat
				FROM (
					SELECT
						salarie.sal_matr as mat,
						cal.mois,
						cal.date as date_debut,
						cal.date as date_fin,
						cnt.numero_contrat,
						bul.bul_id,
                        case when tcnt.ctr_id = 'I' then (case when cem_id = 'C' THEN 100 else tem_taux end)::numeric / duree_mois / count(cal.date) over (partition by salarie.sal_matr, cal.date) / 100.0
                            else bul_heure_payees / (1820.0 / 12.0) / count(cal.date) over (partition by salarie.sal_matr, bul.bul_id) / count(cal.date) over (partition by salarie.sal_matr, cal.date)
                            end as etp_contrat,
                        case when tcnt.ctr_id = 'I' then (case when cem_id = 'C' THEN 100 else tem_taux end)::numeric / duree_mois / count(cal.date) over (partition by salarie.sal_matr, cal.date) / 100.0 * (1820.0 / 12.0)
                            else bul_heure_payees / count(cal.date) over (partition by salarie.sal_matr, bul.bul_id) / count(cal.date) over (partition by salarie.sal_matr, cal.date)
                            end as heures_contrat,
						CASE WHEN cnt.numero_contrat IS NULL THEN 1 ELSE 0 END est_hors_periode, -- paie hors période de contrat
						coalesce(tcnt.ctr_id, chr(1)||'*') AS type_contrat_code_original,
						coalesce(lower(ins.ins_id), chr(1)||'*') AS categorie_socio_professionnelle_code_original,
						coalesce(emp.emp_id, chr(1)||'*') AS qualification_code_original,
						coalesce(statut.stp_id, chr(1)||'*') AS statut_code_original,
                        coalesce(grille.cat_id, chr(1)||'*') AS grille_code_original,
						coalesce(grille_groupe.coe_val, chr(1)||'*') AS grille_groupe_code_original,
						coalesce(ttt.cem_id::text||coalesce(ptt.tem_taux::text, ''), chr(1)||'*') AS type_temps_travail_code_original,
						coalesce(mes.mes_id||'|'||tcnt.moe_id, chr(1)||'*') AS motif_debut_code_original,
						coalesce(mes.mes_ids, chr(1)||'*') AS motif_fin_code_original,
                        coalesce(salarie.cal_id, chr(1)||'*') AS code_emploi_code_original,
                        coalesce(service.zl1_id, chr(1)||'*') AS service_code_original
					from cal
						join w_lmt as salarie on date between salarie.min_date and salarie.max_date
						left join w_cnt AS cnt ON 1=1
							AND cnt.sal_matr = salarie.sal_matr
							AND date between cnt.date_debut and cnt.date_fin
						left join w_bulletin AS bul ON 1=1
							AND bul.sal_matr = salarie.sal_matr
							AND date between bul.date_debut and bul.date_fin
						left join w_h_contrat AS tcnt ON 1=1 -- type de contrat
							AND tcnt.sal_matr = salarie.sal_matr
							AND date between tcnt.date_debut and tcnt.date_fin
						left join w_h_insee_emp as ins on 1=1 -- categorie_socio_professionnelle
							AND ins.sal_matr = salarie.sal_matr
							AND date between ins.date_debut and ins.date_fin
						left join w_h_emploi as emp on 1=1 -- qualification
							AND emp.sal_matr = salarie.sal_matr
							AND date between emp.date_debut and emp.date_fin
						left join w_h_categ as grille on 1=1 -- grille
							AND grille.sal_matr = salarie.sal_matr
							AND date between grille.date_debut and grille.date_fin
						left join w_h_coeff as grille_groupe on 1=1 -- grille_groupe
							AND grille_groupe.sal_matr = salarie.sal_matr
							AND date between grille_groupe.date_debut and grille_groupe.date_fin
						left join w_h_es as mes on 1=1 -- modes d'entrée/sortie
							AND mes.sal_matr = salarie.sal_matr
							AND date between mes.date_debut and mes.date_fin
						left join w_h_cemploi as ttt on 1=1 -- type temps de travail
							AND ttt.sal_matr = salarie.sal_matr
							AND date between ttt.date_debut and ttt.date_fin
						left join w_h_tempart as ptt on 1=1 -- type temps de travail : pourcentage pour les partiels
							AND ptt.sal_matr = salarie.sal_matr
							AND date between ptt.date_debut and ptt.date_fin
                        left join w_h_stprof as statut on 1=1
                            AND statut.sal_matr = salarie.sal_matr
                            AND date between statut.date_debut and statut.date_fin
                        left join w_h_services as service on 1=1
                            AND service.sal_matr = salarie.sal_matr
                            AND date between service.date_debut and service.date_fin
					GROUP BY 1,2,3,4,5,6, 9,10,11,12,13,14,15,16,17,18,19,20,
                        mes.sal_matr, salarie.ins_id, salarie.emp_id, ins.ins_id, emp.emp_id, ptt.tem_taux,
                        ttt.cem_id, cnt.sal_matr, tcnt.sal_matr, statut.sal_matr, bul.sal_matr, grille.sal_matr,
                        service.sal_matr, cal.duree_mois, tcnt.ctr_id, ttt.cem_id, ptt.tem_taux, bul_heure_payees
					having 1!=1
						OR cnt.sal_matr is not null
						OR bul.sal_matr is not null) AS subq
				GROUP BY 1,2,5,6,7,8,9,10,11,12,13,14,15,16,17,18
			;

			-- Association des bulletins de paie au dernier/futur contrat connu lorsque hors période.
			UPDATE w_tmp_1
			SET numero_contrat = subq.numero_contrat
			FROM (
				select
					bul_id,
					mat,
					coalesce(numero_contrat, -- si la valeur est renseignée sur la ligne courante, on la prend.
                        (max(case when numero_contrat is null then null else ARRAY[extract(epoch from date_debut)::text, numero_contrat] end) over wb)[2], -- sinon on prend la valeur renseignée la plus proche dans le passé
                        (min(case when numero_contrat is null then null else ARRAY[extract(epoch from date_debut)::text, numero_contrat] end) over wf)[2], -- sinon on prend la valeur renseignée la plus proche dans le futur
                        null -- sinon on prend null
                    ) as numero_contrat
				from w_tmp_1
				 window
                    wb as (PARTITION BY mat ORDER BY date_debut rows unbounded preceding), -- sélectionne les lignes précédentes
                    wf as (PARTITION BY mat ORDER BY date_debut rows between current row and unbounded following) -- sélectionne les lignes suivantes
				) AS subq
			WHERE 1=1
				AND w_tmp_1.mat = subq.mat
				AND w_tmp_1.bul_id = subq.bul_id
			;

			DROP TABLE IF EXISTS w_profils
			;
			
			CREATE TEMP TABLE w_profils AS
				SELECT
					0 AS profil_id, -- Identifiant CTI du profil CTI
                    row_number() over (order by mat, bul_id, numero_contrat) as code_original, -- identifiant unique de profil
					-- Cléfs naturelles permettant le matching du profil CTI au données Cegid
					bul_id,
					numero_contrat,
                    etp_contrat,
                    heures_contrat,
					mat AS matricule,
					min(date_debut) AS date_debut,
					max(date_fin) AS date_fin,
					est_hors_periode,

					-- Données du Profil CTI
					categorie_socio_professionnelle_code_original,
					code_emploi_code_original,
					grille_code_original,
					grille_groupe_code_original,
					chr(1)||'*' AS groupe_cotisant_code_original,
					motif_debut_code_original,
					motif_fin_code_original,
					qualification_code_original,
					chr(1)||'*' AS section_analytique_code_original,
					chr(1)||'*' AS section_analytique_paie_code_original,
					service_code_original,
					chr(1)||'*' AS societe_interim_code_original,
					chr(1)||'*' AS specialite_code_original,
					statut_code_original,--greatest(hst.phs_dadscat, chr(1)||'*') AS statut_code_original,
					type_contrat_code_original,
					chr(1)||'*' AS type_horaire_code_original,
					type_temps_travail_code_original,--greatest(hst.phs_condemploi||phs_ttauxpartiel::float, 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_tmp_1
				GROUP BY 1 ,3,4,5,6,7, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35
			;
			
			]]></sqlcmd>
		</NODE>
		<NODE name="PROFIL" type="common" />
		<NODE label="Salariés">
			<sqlcmd><![CDATA[
			
			DROP TABLE IF EXISTS w_salaries
			;
			
			CREATE TEMP TABLE w_salaries AS
				SELECT 
					rhp('finess') AS finess,
					CASE WHEN length(trim(sal_val_nom)) > 0 THEN sal_val_nom ELSE sal_naiss END AS nom,
					sal_prenom AS prenom,
					v_sal_dnaiss AS date_naissance,
					CASE WHEN substr(sal_noss, 1, 1) = 1 THEN 'M' ELSE 'F' END AS sexe,
					salarie.sal_matr AS matricule,
					salarie.sal_matr AS code,
					salarie.sal_matr AS code_original,
					max(coalesce(t_entreprises.oid, 0)) AS entreprise_id,
					max(coalesce(t_nationalites.oid, 0)) AS nationalite_id,
					max(coalesce(t_codes_postaux.oid, 0)) AS code_postal_id,
					sal_naiss AS nom_naissance,
					max(coalesce(t_situations_famille.oid, 0)) AS situation_famille_id,
					((max(ARRAY[w_profils.date_fin::text, w_profils.profil_id::text]))[2])::bigint AS profil_id, -- dernier profil salarié.
					max(h_cnt_trav.date_debut) AS date_debut, -- date de début du dernier contrat.
					max(h_cnt_trav.date_fin) AS date_fin, -- date de fin du dernier contrat.
					salarie.v_sal_dat_cemp AS date_entree_ets,
					max(h_cnt_trav.date_fin) AS date_sortie_ets,
					-- Champs dédiés au public.
					'1900-01-01'::date AS date_entree_fp,
					'1900-01-01'::date  AS date_entree_fph,
					0 AS no_adeli,
					0 AS code_cotisation_id,
					0 AS matricule_retraite,
					salarie.sal_noss||salarie.sal_cless AS nir
				FROM w_salarie AS salarie
                    JOIN w_ets ON w_ets.eta_id = salarie.eta_id
					JOIN w_cnt AS h_cnt_trav ON 1=1
						AND h_cnt_trav.ent_id = salarie.ent_id
						AND h_cnt_trav.sal_matr = salarie.sal_matr
                    JOIN w_profils on w_profils.numero_contrat = h_cnt_trav.numero_contrat
					LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = salarie.sal_cp
					LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = salarie.fam_id
					LEFT JOIN rh.t_entreprises ON t_entreprises.code_original = salarie.ent_id
					LEFT JOIN rh.t_nationalites ON t_nationalites.code_original = salarie.sal_cod_pays
				GROUP BY 1,2,3,4,5,6,7,8, 12, 17,19,20,21,22,23,24
			;
			
			]]></sqlcmd>
		</NODE>
		<NODE name="SALARIE" type="common" />
		<NODE label="Contrats">
			<sqlcmd><![CDATA[
			
			TRUNCATE rh.p_contrats
			;
			
			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

			INSERT INTO rh.p_contrats(
				salarie_id,
				date_debut,
				date_fin,
				numero_contrat,
				code_original,
				etablissement_id,
				profil_id)
				SELECT
					coalesce(p_salaries.oid,0) AS salarie_id,
					w_cnt.date_debut,
					w_cnt.date_fin,
					w_cnt.numero_contrat, 
					w_cnt.numero_contrat AS code_original,
					coalesce(t_etablissements.oid,0) AS etablissement_id,
					(max(ARRAY[extract(EPOCH from w_profils.date_fin), w_profils.profil_id]))[2] AS profil_id -- Il se peut que pour un même contrat, il y est plusieurs profils. Dans ce cas on prend le profil le plus récent.
				FROM w_cnt
					JOIN rh.p_salaries ON p_salaries.matricule = sal_matr
					-- JOIN rh.t_etablissements ON t_etablissements.code_original = 'STC' -- @TODO faire quelque chose pour les contrats qui sont ratachés directement à l'entreprise...
                    join rh.t_etablissements ON t_etablissements.code_original = w_cnt.ent_id -- FIXME
					JOIN w_profils ON 1=1
						AND w_profils.matricule = sal_matr
						AND w_profils.numero_contrat = w_cnt.numero_contrat
				GROUP BY 1,2,3,4,5,6
			;
			
			-- #correction
			-- Si les dates d'entrée/sortie d'établissement semblent incohérentes par rapports aux dates des contrats, les corriger.
			UPDATE rh.p_salaries
			SET date_entree_ets = date_debut_contrat
			FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND	date_entree_ets > date_debut_contrat
			;

			UPDATE rh.p_salaries
			SET date_entree_ets = date_debut_contrat
			FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND to_char(date_entree_ets, 'YYYY')::numeric >= 2009
				AND	date_entree_ets < date_debut_contrat
			;
				
			UPDATE rh.p_salaries
			SET date_sortie_ets = date_fin_contrat
			FROM (SELECT salarie_id, max(date_fin) AS date_fin_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND date_fin_contrat > date_sortie_ets
			;
			
			-- 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.numero_contrat,
					sum(t2.duree) AS anciennete_anterieure_jours,
					sum(t2.duree) / 30 AS anciennete_anterieure_calculee_mois
				FROM w_cnt AS t1
					JOIN w_cnt AS t2 ON 1=1
						AND t2.sal_matr = t1.sal_matr
						AND t2.date_debut < t1.date_debut
				group by 1
				) AS subq
			WHERE 1=1
				AND p_contrats.numero_contrat = subq.numero_contrat
			;

			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
                code_original,
				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,
				equivalent_temps_plein,
                nombre_heures,
				age_id,
				age_jours,
				anciennete_jours,
				anciennete_mois,
				anciennete_annee_id)
				SELECT
                    w_profils.code_original,
					p_salaries.oid AS salarie_id,
					p_contrats.oid AS contrat_id,
					p_calendrier_mois.mois AS mois,
					GREATEST(p_calendrier_mois.date_debut, w_profils.date_debut) AS date_debut,
					LEAST(p_calendrier_mois.date_fin, w_profils.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,
					w_profils.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,
					etp_contrat,
                    heures_contrat,
					base.cti_age(LEAST(p_calendrier_mois.date_fin, w_profils.date_fin), COALESCE(p_salaries.date_naissance, '1962-04-18'::date), 'ny')  AS age_id,
					LEAST(p_calendrier_mois.date_fin, w_profils.date_fin)::date - COALESCE(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
					p_contrats.anciennete_anterieure_jours
						+ (LEAST(p_calendrier_mois.date_fin, w_profils.date_fin) - p_contrats.date_debut)
						+ 1
					AS anciennete_jours,
					base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
						+ p_contrats.anciennete_anterieure_calculee_mois
					AS anciennete_mois,
					floor(
						(
							base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
							+ p_contrats.anciennete_anterieure_calculee_mois
						) / 12
					) AS anciennete_annee_id
				FROM w_profils
					JOIN base.p_calendrier_mois ON base.cti_overlaps(w_profils.date_debut, w_profils.date_fin, p_calendrier_mois.date_debut, p_calendrier_mois.date_fin)
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_profils.numero_contrat
					JOIN rh.p_salaries ON p_salaries.matricule = w_profils.matricule
				WHERE 1=1
					AND p_calendrier_mois.mois < to_char(now() + '1 month'::interval, 'YYYYMM')
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
			;
						
			]]></sqlcmd>
		</NODE>
		<NODE label="Historique de la paie">
			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_hp
			;

			CREATE TEMP TABLE w_hp AS
                with ligne as (
                        select
                            bul_id,
                            ligne.ent_id,
                            pla_id,
                            lig_bas1,
                            lig_bas2,
                            lig_taux1,
                            lig_mont1,
                            lig_taux2,
                            lig_mont2
                        from w_ligne as ligne
                            JOIN w_ets ON w_ets.ent_id = ligne.ent_id
                    union all
                        select
                            bul_id,
                            ent_id,
                            code as pla_id,
                            base as lig_bas1,
                            nombre as lig_bas2,
                            0 as lig_taux1,
                            0 as lig_mont1,
                            0 as lig_taux2,
                            0 as lig_mont2
                        from w_ligne_fj)
				SELECT
					bulletin.eta_id,
					bulletin.sal_matr AS matricule,
					-- Dates d'activité
					date_debut,
					date_fin,
					to_char(date_fin, 'YYYYMM')::numeric AS mois_activite,
					-- Dates de paie
					date_paie,
					substr(bulletin.bul_id, 1, 6)::numeric AS mois_paie,
					pla_code_original AS rubrique,
                    p_detail,
                    p_cumul,
                    -- Les forfaits jours voient leur base multiplié par le coeff paramétré dans base (jours => heures).
                    -- En revanche, les autres salariés voient leur base multiplié par le coeff paramétré dans nombre (représente toujours des jours).
                    -- Cela permet d'appliquer le signe négatif sur la base de toute la population de salariés.
					case when p_base then lig_bas1 else 0 end * case when forfait_jour then c_base * bulletin.etp else c_nombre end AS base,
                    case when p_nombre then lig_bas2 else 0 end * c_nombre AS nombre,
                    case
					 	when p_heures_contrat and s_heures_contrat = 0 then lig_bas2
                        when p_heures_contrat and s_heures_contrat = 1 then lig_bas1
                        else 0
                    end * c_heures_contrat as heure_contrat,
                    case
                        when p_heures_payees and s_heures_payees = 0 then lig_bas2
                        when p_heures_payees and s_heures_payees = 1 then lig_bas1
                        else 0
                    end * c_heures_payees as heure_payee,
                    case
                        when p_heures_travaillees and s_heures_travaillees = 0 then lig_bas2
                        when p_heures_travaillees and s_heures_travaillees = 1 then lig_bas1
                        else 0
                    end * c_heures_travaillees as heure_travaillee,
                    case
                        when p_masse_salariale and s_masse_salariale = 3 then lig_mont1
                        when p_masse_salariale and s_masse_salariale = 5 then lig_mont2
                        else 0
                    end * c_masse_salariale as montant_masse_salariale,
					CASE WHEN p_brut THEN lig_mont1 ELSE 0 END * c_brut AS montant_brut,
                    CASE WHEN p_avantage_nature THEN lig_mont1 ELSE 0 END * c_avantage_nature AS montant_avantage_nature,
                    case when p_frais_imposables then lig_mont1 else 0 end * c_frais_imposables as montant_frais_imposables,
                    case when p_cotisation_salarie then lig_mont1 else 0 end * c_cotisation_salarie as montant_cotisation_salarie,
                    case when p_cotisation_patronale then lig_mont2 else 0 end * c_cotisation_patronale as montant_cotisation_patronale,
                    case when p_od_net_salarie then lig_mont1 else 0 end * c_od_net_salarie as montant_od_net_salarie,
                    case when p_od_net_patronale then lig_taux2 else 0 end * c_od_net_patronale as montant_od_net_patronale,
					lig_taux1 AS tx_sal,
					lig_taux2 AS tx_pat,
					CASE WHEN p_net_imposable THEN lig_mont1 ELSE 0 END * c_net_imposable AS montant_net_imposable_salarie,
					CASE WHEN p_net_a_payer THEN lig_mont1 ELSE 0 END * c_net_a_payer AS montant_net_a_payer_salarie
				FROM w_bulletin AS bulletin
                    JOIN w_ets ON w_ets.eta_id = bulletin.eta_id
                    join ligne ON 1=1
                        AND ligne.bul_id = bulletin.bul_id
                        AND ligne.ent_id = bulletin.ent_id
                    join w_rub ON 1=1
                        AND w_rub.pla_id = ligne.pla_id
                        AND bulletin.bul_fin between w_rub.pla_dval and w_rub.pla_fval
                    join rh.t_rubriques on t_rubriques.code_original = w_rub.pla_code_original
				WHERE 1!=1
                    OR p_detail
                    OR p_cumul
			;

			-- #correction
			UPDATE w_hp
			SET date_paie = (mois_paie||'01')::date + '1 month - 1 day'::interval
			WHERE to_char(date_paie, 'YYYYMM')::numeric != mois_paie
			;
				
			CREATE INDEX i_w_hp_1 
			ON w_hp 
			USING btree (matricule)
			;
			
			CREATE INDEX i_w_hp_2 
			ON w_hp 
			USING btree (mois_activite)
			;

			CREATE INDEX i_w_hp_3
			ON w_hp 
			USING btree (mois_paie)
			;
			
			CREATE INDEX i_w_hp_4 
			ON w_hp 
			USING btree (rubrique)
			;
			
			-- Insertion dans la table de production CTI.
			TRUNCATE rh.p_historique_paie
			;
			
			SELECT base.cti_stash_table_indexes('rh', 'p_historique_paie')
			;

			INSERT INTO rh.p_historique_paie(
				  age_id,
                  nombre,
				  base,
				  contrat_id,
				  contrat_mois_id,
				  date_debut,
				  date_fin,
				  date_paie,
				  mois_activite,
				  mois_paie,
				  heure_contrat,
                  heure_payee,
                  heure_travaillee,
				  montant_avantage_nature,
				  montant_brut,
                  montant_masse_salariale,
				  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,
				  rubrique_id,
				  salarie_id,
				  taux_cotisation_patronale,
				  taux_cotisation_salarie,
				  compte_id)
				SELECT
					date_part('year', age(w_hp.date_debut, date_naissance)) AS age_id,
                    w_hp.nombre,
					w_hp.base AS base,
					(max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.contrat_id]))[2] AS contrat_id,
					(max(ARRAY[EXTRACT(EPOCH FROM p_contrats_mois.date_fin),p_contrats_mois.oid]))[2] AS contrat_mois_id,
					w_hp.date_debut,
					w_hp.date_fin,
					w_hp.date_paie,
					w_hp.mois_activite,
					w_hp.mois_paie,
					w_hp.heure_contrat,
                    w_hp.heure_payee,
                    w_hp.heure_travaillee,
					w_hp.montant_avantage_nature,
					w_hp.montant_brut,
                    w_hp.montant_masse_salariale,
					w_hp.montant_cotisation_patronale,
					w_hp.montant_cotisation_salarie,
					w_hp.montant_frais_imposables,
					w_hp.montant_net_a_payer_salarie,
					w_hp.montant_net_imposable_salarie,
					w_hp.montant_od_net_salarie,
                    w_hp.montant_od_net_patronale,
					0 AS organisme_cotisation_id,
					t_rubriques.oid AS rubrique_id,
					p_salaries.oid AS salarie_id,
					w_hp.tx_pat AS taux_cotisation_patronale,
					w_hp.tx_sal AS taux_cotisation_salarie,
					0 AS compte_id
				FROM w_hp
					JOIN rh.t_rubriques ON t_rubriques.code_original = w_hp.rubrique
					JOIN rh.p_salaries ON p_salaries.matricule = w_hp.matricule
					-- LEFT JOIN rh.t_organismes_cotisation ON t_organismes_cotisation.code_original = w_hp.organisme
					LEFT JOIN rh.p_contrats_mois ON 1=1
						AND p_contrats_mois.salarie_id = p_salaries.oid
						--AND p_contrats_mois.mois_activite = w_hp.mois
						AND base.cti_overlaps(p_contrats_mois.date_debut, p_contrats_mois.date_fin, w_hp.date_debut, w_hp.date_fin)
					-- LEFT JOIN rh.t_compte ON t_compte.code_original = w_hp.compte
                WHERE w_hp.p_detail
				GROUP BY 1,2,3,  6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, w_hp.ctid
			;
			
			SELECT base.cti_stash_pop_table_indexes('rh', 'p_historique_paie')
			;
			

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


            -- FIXME ATTENTION AUX DOUBLONS !!!
            -- FIXME Bulletins sur 201600 ...
			CREATE TEMP TABLE w_totaux AS
                with ligne as (
                        select
                            bul_id,
                            ligne.ent_id,
                            pla_id,
                            lig_bas1,
                            lig_bas2,
                            lig_mont1,
                            lig_mont2
                        from w_ligne as ligne
                            JOIN w_ets ON w_ets.ent_id = ligne.ent_id
                    union all
                        select
                            bul_id,
                            ent_id,
                            code as pla_id,
                            base as lig_bas1,
                            nombre as lig_bas2,
                            0 as lig_mont1,
                            0 as lig_mont2
                        from w_ligne_fj)
				select
					-- Dates d'activité
					date_debut,
					date_fin,
					to_char(date_fin, 'YYYYMM')::numeric AS mois_activite,
					-- Dates de paie
					date_paie,
					substr(bulletin.bul_id, 1, 6)::numeric AS mois_paie,
                    bulletin.eta_id,
					bulletin.sal_matr AS matricule,
					substr(bulletin.bul_id, 1, 4)::numeric AS mois,
					sum(case when pla_id = 'BRUT' then lig_mont1 else 0 end)::numeric AS brut,
					sum(case when pla_id = 'IMPO' then lig_mont1 else 0 end)::numeric AS net_imposable,
					sum(case when pla_id = 'NETT' then lig_mont1 else 0 end)::numeric AS net_a_payer,
					sum(case when pla_id = 'TOTR' then lig_mont1 else 0 end)::numeric AS mt_sal,
					sum(case when pla_id = 'TOTR' then lig_mont2 * (-1) else 0 end)::numeric AS mt_pat
				from w_bulletin AS bulletin
                    JOIN w_ets ON w_ets.eta_id = bulletin.eta_id
					join ligne ON 1=1
                        AND ligne.bul_id = bulletin.bul_id
                        AND ligne.ent_id = bulletin.ent_id
				where pla_id IN ('BRUT', 'TOTR', 'IMPO', 'NETT')
				group by 1,2,3,4,5,6,7,8
			;

			-- #correction
			UPDATE w_totaux
			SET date_paie = (mois_paie||'01')::date + '1 month - 1 day'::interval
			WHERE to_char(date_paie, 'YYYYMM')::numeric != mois_paie
			;
			
			-- Inserer pour chaque bulletin une ligne qui va faire le compte avec le total (rubrique 'C000' nommée 'Ecart cumulé')
			INSERT INTO rh.p_historique_paie(
                age_id,
                contrat_id,
                contrat_mois_id,
                date_debut,
                date_fin,
                date_paie,
                mois_activite,
                mois_paie,
                nombre,
                base,
                heure_payee,
                heure_travaillee,
                montant_masse_salariale,
                montant_brut,
                montant_avantage_nature,
                montant_frais_imposables,
                montant_cotisation_salarie,
                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, -- @deprecated
                rubrique_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie)
				SELECT
                    age_id,
                    contrat_id,
                    contrat_mois_id,
                    subq.date_debut,
                    subq.date_fin,
                    subq.date_paie,
                    subq.mois_activite,
                    subq.mois_paie,
                    0 as nombre,
                    0 AS base,
                    0 AS heure_payee,
                    0 as heure_travaillee,
                    0 as montant_masse_salariale,
                    sum(brut - subq.montant_brut) AS montant_brut,
                    0 AS montant_avantage_nature,
                    0 AS montant_frais_imposables,
                    sum(mt_sal - subq.montant_cotisation_salarie) AS montant_cotisation_salarie,
                    sum(mt_pat - subq.montant_cotisation_patronale) AS montant_cotisation_patronale,
                    0 as montant_od_net_salarie,
                    0 as montant_od_net_patronale,
                    sum(net_imposable - subq.montant_net_imposable_salarie) AS montant_net_imposable_salarie,
                    sum(net_a_payer - subq.montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
                    subq.organisme_cotisation_id AS organisme_cotisation_id,
                    subq.profil_id AS profil_id,
                    (SELECT oid FROM rh.t_rubriques WHERE code = 'C000') AS rubrique_id,
                    subq.salarie_id AS salarie_id,
                    0 AS taux_cotisation_patronale,
                    0 AS taux_cotisation_salarie
				FROM
					(SELECT
                        p_historique_paie.age_id,
                        p_historique_paie.contrat_id,
                        p_historique_paie.contrat_mois_id,
                        p_historique_paie.date_debut,
                        p_historique_paie.date_fin,
                        p_historique_paie.date_paie,
                        p_historique_paie.mois_activite,
                        p_historique_paie.mois_paie,
                        0 as nombre,
                        0 AS base,
                        sum(heure_payee) as heure_payee,
                        sum(heure_travaillee) as heure_travaillee,
                        sum(montant_masse_salariale) as montant_masse_salariale,
                        sum(montant_brut) AS montant_brut,
                        sum(montant_avantage_nature) AS montant_avantage_nature,
                        sum(montant_frais_imposables) AS montant_frais_imposables,
                        sum(montant_cotisation_salarie) AS montant_cotisation_salarie,
                        sum(montant_cotisation_patronale) AS montant_cotisation_patronale,
                        sum(montant_od_net_salarie) as montant_od_net_salarie,
                        sum(montant_od_net_patronale) as montant_od_net_patronale,
                        sum(montant_net_imposable_salarie) AS montant_net_imposable_salarie,
                        sum(montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
                        0 AS organisme_cotisation_id,
                        0 AS profil_id, -- p_historique_paie.profil_id,
                        (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                        p_historique_paie.salarie_id,
                        0 AS taux_cotisation_patronale,
                        0 AS taux_cotisation_salarie
					FROM rh.p_historique_paie
                        JOIN rh.p_salaries ON p_salaries.oid = p_historique_paie.salarie_id
					GROUP BY 1,2,3,4,5,6,7,8,9,10, 23,24,25,26,27,28) 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_debut = subq.date_debut
					AND w_totaux.date_fin = subq.date_fin
				GROUP BY 1,2,3,4,5,6,7,8, 23,24,25,26,27,28
				HAVING 1!=1
					OR sum(brut - subq.montant_brut) != 0
					OR sum(mt_pat - subq.montant_cotisation_patronale) != 0
					OR sum(mt_sal - subq.montant_cotisation_salarie) != 0
					OR sum(net_a_payer - subq.montant_net_a_payer_salarie) != 0
					OR sum(net_imposable - subq.montant_net_imposable_salarie) != 0
			;

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

			]]></sqlcmd>
		</NODE>
		<NODE label="Ventilation des profils">
			<sqlcmd><![CDATA[
			
			-- Alimentation des profils simultanés.
			TRUNCATE rh.p_profil_contrat_mois
			;
			
			INSERT INTO rh.p_profil_contrat_mois (
				profil_id,
				contrat_mois_id,
				salarie_id,
				ratio,
				mois)
				select
					w_profils.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 w_profils ON w_profils.code_original = p_contrats_mois.code_original
				group by 1,2,3,4,5
			;

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