<?xml version="1.0" encoding="ISO-8859-15"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
        <NODE label="Pré-traitements">
			<sqlcmd><![CDATA[

            SET DATESTYLE TO ISO, European
            ;
			
			-- Matérialisation tables historique
			DROP TABLE IF EXISTS MATERIAL_HIST_RUBR_SALA_T;
			CREATE TEMP TABLE MATERIAL_HIST_RUBR_SALA_T AS
			SELECT 
				PERI,
				ID_RUBR,
				ID_SALA,
				LIBELLE,
				NOMB,
				BASE,
				TAUX_SALA,
				MONT_SALA,
				TAUX_PATR,
				MONT_PATR,
				BASE_COTI,
				DATE_PAIE,
				DATE_DEBU_PERI,
				DATE_FIN_PERI,
				ID_ETAB,
				CODE_ANAL,
				CATE_PROF,
				SERV,
				DEPA,
				ID_SOCI,
				ID_MODBULL,
				ID_CAIS,
				CODE_RUBR,
				INTI_RUBR,
				TYPE_RUBR,
				ID_SIMU,
				FIXE,
				ACTI,
				NEUT_CODE,
				REGR,
				EMPL,
				ID_EMPL,
				MONT_PATR_IMPO,
				EQUI,
				ID_PERS
			FROM prod_nibelis.HIST_RUBR_SALA_T
			;
			
			ANALYSE MATERIAL_HIST_RUBR_SALA_T
			;
			
			CREATE INDEX i_MATERIAL_HIST_RUBR_SALA_T_1
			ON MATERIAL_HIST_RUBR_SALA_T
			USING btree
			(ID_SALA);

			CREATE INDEX i_MATERIAL_HIST_RUBR_SALA_T_2
			ON MATERIAL_HIST_RUBR_SALA_T
			USING btree
			(ID_RUBR);
			
			
			DROP TABLE IF EXISTS MATERIAL_HIST_CONS_SALA;
			CREATE TEMP TABLE MATERIAL_HIST_CONS_SALA AS
			SELECT PERI, ID_SALA, CODE_CONS, VALE
			FROM prod_nibelis.HIST_CONS_SALA_CUMUL
			WHERE CODE_CONS = ANY(ARRAY['COEFFIC', 'PRESENCE', 'TOTALH', 'TOTALHTRAV'])
			;
			
			ANALYSE MATERIAL_HIST_CONS_SALA
			;
			
			CREATE INDEX i_MATERIAL_HIST_CONS_SALA_1
			ON MATERIAL_HIST_CONS_SALA
			USING btree
			(ID_SALA);

			CREATE INDEX i_MATERIAL_HIST_CONS_SALA_2
			ON MATERIAL_HIST_CONS_SALA
			USING btree
			(CODE_CONS);
			
			
			
			
			-- Table de travail HIST_SALARIE
			DROP TABLE IF EXISTS w_HIST_SALARIE
            ;
			
            CREATE TEMP TABLE w_HIST_SALARIE AS
                SELECT *
                FROM prod_nibelis.HIST_SALARIE HIST_SALARIE
                WHERE DATE_DEBU_CONT IS NOT NULL
			;
			
			ANALYSE w_HIST_SALARIE
			;
			
			CREATE INDEX i_w_HIST_SALARIE_1
			ON w_HIST_SALARIE
			USING btree
			(ID_SALA);
			
			-- Attention, le matricule du salarie a pu changer. On garde le courant
			UPDATE w_HIST_SALARIE HIST_SALARIE
            SET MATR = SALARIE_T.MATR
            FROM prod_nibelis.SALARIE_T
			WHERE HIST_SALARIE.ID_SALA = SALARIE_T.ID_SALA AND
				HIST_SALARIE.MATR IS DISTINCT FROM SALARIE_T.MATR
			;
			

            DROP TABLE IF EXISTS w_ets
            ;

            CREATE TEMP TABLE w_ets AS
                SELECT
					id_etab,
                    id_soci::int,
                    sire,
					0::bigint as entreprise_id,
                    0::bigint as etablissement_id
				from prod_nibelis.etablissement_t
				where 1=1
					AND (1!=1
                        OR substr(sire, 1, 9) IN (SELECT rhp_in('siren')) -- Soit un ou plusieurs SIREN ont été défini,
                        OR sire IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs SIRET,
                        OR id_etab IN (SELECT rhp_in('siren'))) -- et/ou soit un ou plusieurs codes établissement.
            ;

            DROP TABLE IF EXISTS w_sal2excl
            ;

            CREATE TEMP TABLE w_sal2excl AS
                select id_sala
                from prod_nibelis.salarie_t
                where true
                    and id_etab in (select id_etab from w_ets group by 1)
                    and id_simu is not null
            ;
			
			DROP TABLE IF EXISTS w_HIST_RUBR_SALA_T;
                CREATE TEMP TABLE w_HIST_RUBR_SALA_T AS
                SELECT ID_SALA, PERI
                FROM MATERIAL_HIST_RUBR_SALA_T HIST_RUBR_SALA_T
                GROUP BY 1,2
			;
			
			ANALYSE w_HIST_RUBR_SALA_T
			;

            DROP TABLE IF EXISTS w_cnt
            ;

            CREATE TEMP TABLE w_cnt AS
                with cnt_agg as (
                    select
                        id_etab::bigint,
                        hist_salarie.id_sala::bigint,
                        trim(matr) as matr,
                        trim(matr)||'-'::text||to_char(to_date(COALESCE(hist_salarie.date_debu_cont,hist_salarie.date_emba),'DD/MM/YYYY'), 'YYYYMMDD') as ncnt,
                        trim(id_etab)||'-'::text||trim(hist_salarie.id_sala)||'-'::text||trim(matr)||'-'::text||to_char(to_date(COALESCE(hist_salarie.date_debu_cont,hist_salarie.date_emba),'DD/MM/YYYY'), 'YYYYMMDD') as ncnt_ori,
                        COALESCE(hist_salarie.date_debu_cont,hist_salarie.date_emba)::date AS date_debu_cont,
                        (max(array[hist_salarie.peri::date, date_fin_cont::date]))[2] as date_fin_cont,
                        MAX(sala_supp) AS sala_supp,
                        (max(array[hist_salarie.peri::date, date_anci::date]))[2] as date_anci
                    from w_HIST_SALARIE AS HIST_SALARIE
                    LEFT JOIN w_HIST_RUBR_SALA_T ON
						w_HIST_RUBR_SALA_T.ID_SALA = HIST_SALARIE.ID_SALA AND
						w_HIST_RUBR_SALA_T.PERI = HIST_SALARIE.PERI
                    where true
						and (hist_salarie.SALA_SUPP <> '' OR w_HIST_RUBR_SALA_T.ID_SALA IS NOT NULL)
                        and id_etab in (select id_etab from w_ets group by 1)
                        and hist_salarie.id_sala not in (select id_sala from w_sal2excl) -- suppression des salariés de démo.
                    group by 1,2,3,4,5,6)
                select
                    id_etab,
                    id_sala,
                    matr,
                    ncnt,
                    ncnt_ori,
                    date_debu_cont,
                    coalesce(date_fin_cont, lead(date_debu_cont) over w - '1 day'::interval, '2099-12-31'::date)::date as date_fin_cont,
                    sala_supp,
                    case when date_anci > date_debu_cont then date_debu_cont else date_anci end as date_anci
                from cnt_agg
                window w as (partition by id_etab, id_sala order by date_debu_cont)
            ;

            DROP TABLE IF EXISTS w_cnt_bul
            ;

            CREATE TEMP TABLE w_cnt_bul AS
                with histo_rub as (
                    SELECT 
                            id_etab_rub,
                            id_sala_rub,
                            id_empl_rub,
                            peri_rub
                        FROM
                            (select
                                id_etab as id_etab_rub,
                                id_sala as id_sala_rub,
                                id_empl as id_empl_rub,
                                peri as peri_rub,
                                COUNT(*) OVER (PARTITION BY id_sala, id_etab, peri) AS nb_lignes
                            from MATERIAL_HIST_RUBR_SALA_T HIST_RUBR_SALA_T
                            group by 1,2,3,4
                            ) AS subview
                    -- Permet d'éviter le problème de rubriques en doubles dans certains cas 
                    WHERE subview.nb_lignes = 1 OR (subview.nb_lignes > 1 AND id_empl_rub IS NOT NULL)
                    )
                , w_emplois as (
                    select
                        trim(id_empl) as id_empl,
                        trim(libe) as libe,
                        trim(code_inse) as code_inse
                    from prod_nibelis.emplois
                    where id_soci::bigint = (select id_soci from w_ets limit 1)
                    group by 1,2,3)
                , w_coeff as (
                    select
                        id_sala as coeff_id_sala,
                        peri as coeff_peri,
                        coalesce(vale, '0') as coeff
                    from MATERIAL_HIST_CONS_SALA hist_cons_sala
                    where code_cons = 'COEFFIC'
                    group by 1,2,3)
                select
                    hist_salarie.id_etab::bigint,
                    hist_salarie.id_sala::bigint,
                    trim(hist_salarie.matr) as matr,
                    trim(hist_salarie.matr)||'-'::text||to_char(to_date(hist_salarie.date_debu_cont,'DD/MM/YYYY'), 'YYYYMMDD') as ncnt,
                    trim(hist_salarie.id_etab)||'-'::text||trim(hist_salarie.id_sala)||'-'::text||trim(hist_salarie.matr)||'-'::text||to_char(to_date(hist_salarie.date_debu_cont,'DD/MM/YYYY'), 'YYYYMMDD') as ncnt_ori,
                    w_cnt.date_debu_cont,
                    w_cnt.date_fin_cont,
                    w_cnt.date_anci,
                    hist_salarie.peri::date,
                    to_char(hist_salarie.peri::date, 'YYYYMM')::int as mois_paie,
                    trim(hist_salarie.nume_secu_soci) as nume_secu_soci,
                    trim(hist_salarie.cle_secu_soci) as cle_secu_soci,
                    trim(hist_salarie.titr) as titr,
                    trim(hist_salarie.nom) as nom,
                    trim(hist_salarie.nom_jeun_fill) as nom_jeun_fill,
                    trim(hist_salarie.pren) as pren,
                    trim(hist_salarie.code_post) as code_post,
                    trim(hist_salarie.nati) as nati,
                    hist_salarie.date_nais::date,
                    trim(hist_salarie.situ_fami) as situ_fami,
                    hist_salarie.date_emba::date,
                    trim(hist_salarie.code_moti_recr_cdd) as code_moti_recr_cdd,
                    coalesce(hist_salarie.date_depa::date, '2099-12-31'::date) as date_depa,
                    trim(hist_salarie.moti_depa) as moti_depa,
                    w_emplois.id_empl as id_empl,
                    w_emplois.code_inse as code_inse,
                    trim(hist_salarie.cate_prof) as cate_prof,
                    trim(hist_salarie.natu_cont) as natu_cont,
                    trim(hist_salarie.serv) as serv,
                    trim(hist_salarie.equi) as equi,
                    trim(hist_salarie.regr) as regr,
                    trim(hist_salarie.cate_conv) as cate_conv,
					trim(hist_salarie.fili_conv) as fili_conv,
					REPLACE(hist_salarie.hora_mens_fich, ',', '.')::numeric AS hora_mens_fich,
					w_coeff.coeff,
					case when replace(hist_salarie.hora_mens_fich, ',', '.')::numeric = 0 then 1.0 else replace(hist_salarie.hora_mens_fich, ',', '.')::numeric / 151.67 end as ratio_theo,
					'':: text as ttt,
					'':: text as ttt_libelle,
					'':: text as ttt_libelle_court,
					array_remove(ARRAY[
					CASE WHEN (hist_salarie.code_anal IS NOT NULL AND hist_salarie.code_anal != '') THEN hist_salarie.code_anal ELSE 'NO_CODE_ANAL' END, 
					CASE WHEN (hist_salarie.code_anal_axe2 IS NOT NULL AND hist_salarie.code_anal_axe2 != '') THEN hist_salarie.code_anal_axe2 ELSE 'NO_CODE_ANAL' END, 
					CASE WHEN (hist_salarie.code_anal_axe3 IS NOT NULL AND hist_salarie.code_anal_axe3 != '') THEN hist_salarie.code_anal_axe3 ELSE 'NO_CODE_ANAL' END,
					CASE WHEN (hist_salarie.code_anal_axe4 IS NOT NULL AND hist_salarie.code_anal_axe4 != '') THEN hist_salarie.code_anal_axe4 ELSE 'NO_CODE_ANAL' END,
					CASE 
						WHEN 
							(hist_salarie.code_anal IS NULL OR hist_salarie.code_anal = '') AND 
							(hist_salarie.code_anal_axe2 IS NULL OR hist_salarie.code_anal = '') AND 
							(hist_salarie.code_anal_axe3 IS NULL OR hist_salarie.code_anal = '') AND 
							(hist_salarie.code_anal_axe4 IS NULL OR hist_salarie.code_anal = '')
						THEN chr(1)||'*' 
						ELSE 'NO_CODE_ANAL' 
					END
					], 'NO_CODE_ANAL') AS codes_anal,
					array_remove(ARRAY[
						CASE WHEN (hist_salarie.code_anal IS NOT NULL AND hist_salarie.code_anal != '') THEN REPLACE(hist_salarie.pour_affe_anal, ',', '.') ELSE 'NO_CODE_ANAL' END, 
						CASE WHEN (hist_salarie.code_anal_axe2 IS NOT NULL AND hist_salarie.code_anal_axe2 != '') THEN REPLACE(hist_salarie.pour_affe_anal_axe2, ',', '.') ELSE 'NO_CODE_ANAL' END, 
						CASE WHEN (hist_salarie.code_anal_axe3 IS NOT NULL AND hist_salarie.code_anal_axe3 != '') THEN REPLACE(hist_salarie.pour_affe_anal_axe3, ',', '.') ELSE 'NO_CODE_ANAL' END, 
						CASE WHEN (hist_salarie.code_anal_axe4 IS NOT NULL AND hist_salarie.code_anal_axe4 != '') THEN REPLACE(hist_salarie.pour_affe_anal_axe4, ',', '.') ELSE 'NO_CODE_ANAL' END,
						CASE 
							WHEN 
								(hist_salarie.code_anal IS NULL OR hist_salarie.code_anal = '') AND 
								(hist_salarie.code_anal_axe2 IS NULL OR hist_salarie.code_anal = '') AND 
								(hist_salarie.code_anal_axe3 IS NULL OR hist_salarie.code_anal = '') AND 
								(hist_salarie.code_anal_axe4 IS NULL OR hist_salarie.code_anal = '')
							THEN '100' 
							ELSE 'NO_CODE_ANAL' 
						END
					], 'NO_CODE_ANAL') AS codes_anal_ratio
                from w_HIST_SALARIE AS HIST_SALARIE
                    join w_cnt on w_cnt.ncnt_ori = trim(hist_salarie.id_etab)||'-'::text||trim(hist_salarie.id_sala)||'-'::text||trim(hist_salarie.matr)||'-'::text||to_char(to_date(hist_salarie.date_debu_cont,'DD/MM/YYYY'), 'YYYYMMDD')
                    left join histo_rub on true
                        and histo_rub.id_etab_rub = hist_salarie.id_etab
                        and histo_rub.id_sala_rub = hist_salarie.id_sala
                        and histo_rub.peri_rub = hist_salarie.peri
                    left join w_emplois on w_emplois.id_empl = histo_rub.id_empl_rub
                    left join w_coeff on true
                        and w_coeff.coeff_id_sala = hist_salarie.id_sala
                        and w_coeff.coeff_peri = hist_salarie.peri
                where true
                    and hist_salarie.id_etab in (select id_etab from w_ets group by 1)
                    and hist_salarie.id_sala not in (select id_sala from w_sal2excl) -- suppression des salariés de démo.
            ;

            update w_cnt_bul set
                ttt = case when ratio_theo = 1 then 'TC100' else 'TP'||lpad((ratio_theo * 100)::int::text, 3, '0') end,
                ttt_libelle = case when ratio_theo = 1 then 'Temps Complet' else 'Temps Partiel '||lpad((ratio_theo * 100)::int::text, 3, '0')|| ' %' end,
                ttt_libelle_court = case when ratio_theo = 1 then 'TC' else 'TP '||lpad((ratio_theo * 100)::int::text, 3, '0')|| ' %' end
            ;

            DROP TABLE IF EXISTS w_hp_0
            ;

            CREATE TEMP TABLE w_hp_0 AS
                select
                    id_etab::bigint,
                    id_sala::bigint,
                    trim(HIST_RUBR_SALA_T.id_rubr) as id_rubr,
                    peri::date,
                    to_char(peri::date, 'YYYYMM')::int as mois_paie,
                    -- cate_prof,
                    -- serv,
                    id_modbull::bigint,
                    id_cais::bigint,
                    neut_code,
                    round(replace(nomb, ',', '.')::numeric, 2) as nombre,
                    round(replace(base, ',', '.')::numeric, 2) as base,
                    replace(taux_sala, ',', '.')::numeric as tx_sal,
                    round(replace(mont_sala, ',', '.')::numeric, 2) as mt_sal,
                    replace(taux_patr, ',', '.')::numeric as tx_pat,
                    round(replace(mont_patr, ',', '.')::numeric, 2) as mt_pat
                from MATERIAL_HIST_RUBR_SALA_T HIST_RUBR_SALA_T
                    left join rh.t_rubriques on t_rubriques.code_original = HIST_RUBR_SALA_T.id_rubr
                where true
                    and id_etab in (select id_etab from w_ets group by 1)
                    and id_sala not in (select id_sala from w_sal2excl) -- suppression des salariés de démo.
                    and (false
                        or t_rubriques.p_cumul -- il faut remonter toutes les rubriques de totalisation, même celles à 0.
                        or replace(nomb, ',', '.')::numeric != 0
                        or replace(base, ',', '.')::numeric != 0
                        or replace(mont_sala, ',', '.')::numeric != 0
                        or replace(mont_patr, ',', '.')::numeric != 0)
            ;

            with ets_sal as (
                select
                    id_etab,
                    id_sala as ets_id_sala,
                    peri as ets_peri
                from w_hp_0
                group by 1,2,3)
            INSERT INTO w_hp_0
                select
                    id_etab::bigint,
                    id_sala::bigint,
                    code_cons as id_rubr,
                    peri::date,
                    to_char(peri::date, 'YYYYMM')::int as mois_paie,
                    -- cate_prof,
                    -- serv,
                    0,
                    0,
                    '',
                    round(replace(vale, ',', '.')::numeric, 2) as nombre,
                    round(replace(vale, ',', '.')::numeric, 2) as base,
                    0 as tx_sal,
                    0 as mt_sal,
                    0 as tx_pat,
                    0 as mt_pat
                from MATERIAL_HIST_CONS_SALA hist_cons_sala
                    join ets_sal on true
                        and ets_sal.ets_id_sala = hist_cons_sala.id_sala::bigint
                        and ets_sal.ets_peri = hist_cons_sala.peri::date
                where code_cons in ('PRESENCE', 'TOTALH', 'TOTALHTRAV')
            ;

			]]></sqlcmd>
		</NODE>
		<NODE name="INIT" type="common" />
		<NODE label="Mise é jour des informations permanentes">
			<sqlcmd><![CDATA[
			
			-- Forcage paramétrage des rubriques nouvelle version
			UPDATE rh.t_divers
			SET valeur = '1'
			WHERE code = 'OPT_STD_HP' AND
				valeur <> '1'
			;

			-- Màj des Entreprises.
			INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court)
                select
                    id_soci,
                    MAX(substr(sire, 1, 9)),
                    MAX(nom),
					MAX(substr(nom, 1, 50))
                from prod_nibelis.etablissement_t
                where 1=1
                    AND id_soci NOT IN (SELECT code_original FROM rh.t_entreprises WHERE code_original IS NOT NULL)
					AND id_etab in (select id_etab from w_ets group by 1)
				GROUP BY 1
			;

			-- Màj des Etablissements.
			INSERT INTO rh.t_etablissements(code_original, code, texte, texte_court, entreprise_id)
                SELECT
					id_etab,
                    sire,
					nom,
					substr(nom, 1, 50),
					t_entreprises.oid
				from prod_nibelis.etablissement_t
					JOIN rh.t_entreprises ON t_entreprises.code_original = etablissement_t.id_soci
				where 1=1
                    AND id_etab NOT IN (SELECT code_original FROM rh.t_etablissements WHERE code_original IS NOT NULL)
					and id_etab in (select id_etab from w_ets group by 1)
			;

			-- Màj des catégories socio-professionnelles
			INSERT INTO rh.t_categories_socio_professionnelle (code_original, code, texte, texte_court)
				SELECT lower(code_inse), lower(code_inse), lower(code_inse), substr(lower(code_inse), 1, 50)
				FROM prod_nibelis.emplois
				WHERE true
                    and lower(code_inse) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle WHERE code_original IS NOT NULL)
                    and id_soci::bigint = (select id_soci from w_ets limit 1)
				GROUP BY 1,2,3,4
			;

            -- Màj des sections analytiques comptables.
            INSERT INTO rh.t_sections_analytiques(code_original, code, texte, texte_court)
                SELECT code_anal, code_anal, libe_code_anal, substr(libe_code_anal, 1, 50)
                FROM prod_nibelis.code_analytique
                WHERE code_anal NOT IN (SELECT code_original FROM rh.t_sections_analytiques WHERE code_original IS NOT NULL)
            ;

			-- Màj des sections analytiques paie.
            INSERT INTO rh.t_sections_analytiques_paie(code_original, code, texte, texte_court)
                SELECT code_anal, code_anal, libe_code_anal, substr(libe_code_anal, 1, 50)
                FROM prod_nibelis.code_analytique
                WHERE code_anal NOT IN (SELECT code_original FROM rh.t_sections_analytiques_paie WHERE code_original IS NOT NULL)
            ;

			-- Màj des motifs de début de contrat.
			INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
				SELECT code_moti_recr_cdd, code_moti_recr_cdd, code_moti_recr_cdd, substr(code_moti_recr_cdd, 1, 50)
				FROM w_cnt_bul
				WHERE code_moti_recr_cdd NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat WHERE code_original IS NOT NULL)
				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 moti_depa, moti_depa, moti_depa, substr(moti_depa, 1, 50)
				FROM w_cnt_bul
				WHERE moti_depa NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des nationalités.
			INSERT INTO rh.t_nationalites(code_original, code, texte, texte_court)
				SELECT nati, nati, nati, substr(nati, 1, 50)
				FROM w_cnt_bul
				WHERE nati NOT IN (SELECT code_original FROM rh.t_nationalites WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des qualifications
			INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
				SELECT id_empl, id_empl, libe, substr(libe, 1, 50)
				FROM prod_nibelis.emplois
				WHERE true
                    and id_empl NOT IN (SELECT code_original FROM rh.t_qualifications WHERE code_original IS NOT NULL)
                    and id_soci::bigint = (select id_soci from w_ets limit 1)
				GROUP BY 1,2,3,4
			;
			
			-- Rubriques
            DROP TABLE IF EXISTS w_RUBRIQUE_HIST;
			CREATE TEMP TABLE w_RUBRIQUE_HIST AS
			SELECT ID_RUBR, 
				MAX(CODE_RUBR) AS CODE_RUBR,
				MAX(LIBELLE) AS LIBELLE,
				MAX(base.cti_to_number(CODE_RUBR)) AS ORDR
			FROM MATERIAL_HIST_RUBR_SALA_T HIST_RUBR_SALA_T
			GROUP BY 1
			;

			INSERT INTO w_RUBRIQUE_HIST
			SELECT
				CODE_CONS,
				CODE_CONS,
				CODE_CONS,
				-1
			FROM MATERIAL_HIST_CONS_SALA HIST_CONS_SALA
			WHERE CODE_CONS IN ('PRESENCE', 'TOTALH', 'TOTALHTRAV')
			GROUP BY 1
			;

			UPDATE rh.t_rubriques SET
				code = CODE_RUBR,
				texte = LIBELLE,
				texte_court = substr(LIBELLE, 1, 50)
			FROM w_RUBRIQUE_HIST
			WHERE t_rubriques.code_original = ID_RUBR AND
				(
				code IS DISTINCT FROM CODE_RUBR OR
				texte IS DISTINCT FROM LIBELLE OR
				texte_court IS DISTINCT FROM substr(LIBELLE, 1, 50)
				)
			;

			INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
			SELECT
				ID_RUBR,
			    CODE_RUBR,
			    LIBELLE,
			    substr(LIBELLE, 1, 50),
			    ORDR
			FROM w_RUBRIQUE_HIST
			WHERE ID_RUBR NOT IN (SELECT code_original FROM rh.t_rubriques WHERE code_original IS NOT NULL)
			GROUP BY 1,2,3,4,5
		    ;

			
			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(code_original, code, texte, texte_court)
				SELECT situ_fami, situ_fami, situ_fami, substr(situ_fami,1,50)
				FROM w_cnt_bul
				WHERE situ_fami NOT IN (SELECT code_original FROM rh.t_situations_famille WHERE code_original IS NOT NULL)
				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 natu_cont, natu_cont, natu_cont, substr(natu_cont, 1, 50)
				FROM w_cnt_bul
				WHERE natu_cont NOT IN (SELECT code_original FROM rh.t_types_contrat WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des statuts
			INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
				SELECT cate_prof, cate_prof, cate_prof, substr(cate_prof, 1, 50)
				FROM w_cnt_bul
				WHERE cate_prof NOT IN (SELECT code_original FROM rh.t_statuts WHERE code_original IS NOT NULL)
				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 ttt, ttt, ttt_libelle, ttt_libelle_court
                from w_cnt_bul
                where ttt NOT IN (SELECT code_original FROM rh.t_types_temps_travail WHERE code_original IS NOT NULL)
                group by 1,2,3,4
			;

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

            -- Màj des types horaires.
			INSERT INTO rh.t_types_horaire(code_original, code, texte, texte_court)
				SELECT equi, substr(equi,1,30), substr(equi,1,255), substr(equi, 1, 50)
				FROM w_cnt_bul
				WHERE equi NOT IN (SELECT code_original FROM rh.t_types_horaire WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des codes emploi
			INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
				SELECT regr, regr, regr, substr(regr, 1, 50)
				FROM w_cnt_bul
				WHERE regr NOT IN (SELECT code_original FROM rh.t_codes_emploi WHERE code_original IS NOT NULL)
				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 cate_conv, cate_conv, cate_conv, substr(cate_conv, 1, 50)
				FROM w_cnt_bul
				WHERE cate_conv NOT IN (SELECT code_original FROM rh.t_grilles_groupes WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
            ;

            -- Màj des grilles
            INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
                SELECT fili_conv, fili_conv, fili_conv, substr(fili_conv, 1, 50)
				FROM w_cnt_bul
				WHERE fili_conv NOT IN (SELECT code_original FROM rh.t_grilles WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
            ;

            -- Màj des spécialités (coefficient nibélis).
            INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
                SELECT coeff, coeff, coeff, substr(coeff, 1, 50)
				FROM w_cnt_bul
				WHERE coeff NOT IN (SELECT code_original FROM rh.t_specialites WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
            ;

			]]></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
			
			WITH rub_param AS (
			SELECT
				ID_RUBR,
				MAX(TYPE_RUBR) AS TYPE_RUBR,
				MAX(LIBELLE) AS LIBELLE
			FROM MATERIAL_HIST_RUBR_SALA_T HIST_RUBR_SALA_T
			GROUP BY 1)
			UPDATE rh.t_rubriques SET
				p_cumul = subq.p_cumul,
                p_detail = subq.p_detail,
                p_nombre = subq.p_nombre,
                s_nombre = 0,
                c_nombre = 1,
                p_base = subq.p_base,
                s_base = 1,
                c_base = 1,
                p_heures_contrat = subq.p_heures_contrat,
                s_heures_contrat = 0,
                c_heures_contrat = 1,
                p_heures_payees = subq.p_heures_payees,
                s_heures_payees = 0,
                c_heures_payees = 1,
                p_heures_travaillees = subq.p_heures_travaillees,
                s_heures_travaillees = 0,
                c_heures_travaillees = 1,
                p_masse_salariale = subq.p_masse_salariale,
                s_masse_salariale = case when subq.p_cotisation_patronale or subq.p_od_net_patronale then 5 else 3 end,
                c_masse_salariale = 1,
                p_brut = subq.p_brut,
                s_brut = 3,
                c_brut = 1,
                p_avantage_nature = subq.p_avantage_nature,
                s_avantage_nature = 3,
                c_avantage_nature = 1,
                p_frais_imposables = subq.p_frais_imposables,
                s_frais_imposables = 3,
                c_frais_imposables = 1,
                p_cotisation_salarie = subq.p_cotisation_salarie,
                s_cotisation_salarie = 3,
                c_cotisation_salarie = -1,
                p_cotisation_patronale = subq.p_cotisation_patronale,
                s_cotisation_patronale = 5,
                c_cotisation_patronale = 1,
                p_od_net_salarie = subq.p_od_net_salarie,
                s_od_net_salarie = 3,
                c_od_net_salarie = -1,
                p_od_net_patronale = subq.p_od_net_patronale,
                s_od_net_patronale = 5,
                c_od_net_patronale = 1,
                p_net_imposable = subq.p_net_imposable,
                s_net_imposable = 3,
                c_net_imposable = case when subq.p_cotisation_salarie then -1 else 1 end,
                p_net_a_payer = subq.p_net_a_payer,
                s_net_a_payer = 3,
                c_net_a_payer = case when subq.p_cotisation_salarie or subq.p_od_net_salarie then -1 else 1 end
            FROM (
				SELECT
                    oid,
                    code,
                    rub_param.TYPE_RUBR = '4' AS p_cumul,
                    rub_param.TYPE_RUBR != '4' AS p_detail,
                    rub_param.TYPE_RUBR != '4'AS p_nombre,
                    rub_param.TYPE_RUBR != '4' AS p_base,
                    false AS p_heures_contrat,
                    false AS p_heures_payees,
                    false AS p_heures_travaillees,
                    TYPE_RUBR IN ('1', '2') OR TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL BRUT' OR rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL COTISATIONS' AS p_masse_salariale,
                    TYPE_RUBR = '1' OR TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL BRUT' AS p_brut,
                    false AS p_avantage_nature,
                    false AS p_frais_imposables,
                    TYPE_RUBR = '2' OR rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL COTISATIONS' AS p_cotisation_salarie,
                    TYPE_RUBR = '2' OR rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL COTISATIONS' AS p_cotisation_patronale,
                    TYPE_RUBR = '3' OR rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL BRUT' OR rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL COTISATIONS' AS p_od_net_salarie,
                    false AS p_od_net_patronale,
                    TYPE_RUBR IN ('1', '2') AS p_net_imposable,
                    rub_param.TYPE_RUBR != '4' AS p_net_a_payer
                FROM rh.t_rubriques
                    join rub_param ON rub_param.id_rubr = t_rubriques.code_original
                WHERE 1=1
                    AND t_rubriques.oid != 0
                    AND t_rubriques.user_modified = false
                    AND t_rubriques.code not ilike 'C%'
                    AND (
						rub_param.TYPE_RUBR != '4' OR
						rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL BRUT' OR
						rub_param.TYPE_RUBR = '4' AND LIBELLE ILIKE 'TOTAL COTISATIONS'
						)
			) AS subq
			WHERE 1=1
				AND t_rubriques.oid = subq.oid
				AND NOT t_rubriques.user_modified
			;

			

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

			DROP TABLE IF EXISTS w_profils;

			CREATE TEMP TABLE w_profils AS
				select
					row_number() over () as row_id,
					0 as profil_id,
					0 as contrat_id,
					0 as contrat_mois_id,
					0 as salarie_id,
					w_cnt_bul.id_etab,
					w_cnt_bul.id_sala,
					w_cnt_bul.matr,
					w_cnt_bul.ncnt_ori,
					w_cnt_bul.peri,
					w_cnt_bul.ratio_theo,
					w_cnt_bul.date_debu_cont,
					w_cnt_bul.date_fin_cont,
					w_cnt_bul.date_anci,
					case when to_char(w_cnt_bul.peri, 'YYYYMM') = to_char(w_cnt_bul.date_debu_cont, 'YYYYMM') then w_cnt_bul.date_debu_cont else base.cti_first_day((to_char(w_cnt_bul.peri, 'YYYYMM')||'01')::date) end as date_debut,
					case when to_char(w_cnt_bul.peri, 'YYYYMM') = to_char(w_cnt_bul.date_fin_cont, 'YYYYMM') then w_cnt_bul.date_fin_cont else base.cti_last_day((to_char(w_cnt_bul.peri, 'YYYYMM')||'01')::date) end as date_fin,
					w_cnt_bul.date_nais,
					w_cnt_bul.mois_paie,
					w_cnt_bul.peri as date_paie,
					case when to_char(w_cnt_bul.peri, 'YYYYMM') between to_char(w_cnt_bul.date_debu_cont, 'YYYYMM') and to_char(w_cnt_bul.date_fin_cont, 'YYYYMM') then '0' else '1' end as est_hors_periode,
					-- **** code original ****
					coalesce(code_moti_recr_cdd, chr(1)||'*') as motif_debut_code_original,
					coalesce(moti_depa, chr(1)||'*') as motif_fin_code_original,
					coalesce(code_inse, chr(1)||'*') AS categorie_socio_professionnelle_code_original,
					coalesce(id_empl, chr(1)||'*') AS qualification_code_original,
					coalesce(serv, chr(1)||'*') AS service_code_original,
					coalesce(regr, chr(1)||'*') AS code_emploi_code_original,
					coalesce(fili_conv, chr(1)||'*') AS grille_code_original,
					coalesce(cate_conv, chr(1)||'*') AS grille_groupe_code_original,
					coalesce(coeff, chr(1)||'*') AS specialite_code_original,
					chr(1)||'*' AS groupe_cotisant_code_original,
					chr(1)||'*' AS section_analytique_code_original,
                    chr(1)||'*' AS section_analytique_paie_code_original,
					chr(1)||'*' AS societe_interim_code_original,
					w_cnt_bul.codes_anal,
					w_cnt_bul.codes_anal_ratio,
					hora_mens_fich,
					coalesce(cate_prof, chr(1)||'*') AS statut_code_original,
					coalesce(natu_cont, chr(1)||'*') as type_contrat_code_original,
					coalesce(equi, chr(1)||'*') AS type_horaire_code_original,
					coalesce(ttt, chr(1)||'*') AS type_temps_travail_code_original,
					-- Champs réservés au public.
					chr(1)||'*' AS cadre_emploi_code_original, -- public
					chr(1)||'*' AS categorie_conge_code_original, -- public
					chr(1)||'*' AS categorie_statutaire_code_original, -- public
					chr(1)||'*' AS commission_paritaire_code_original, -- public
					chr(1)||'*' AS compte_salarie_code_original, -- public
					chr(1)||'*' AS filiere_code_original, -- public
					chr(1)||'*' AS lettre_budgetaire_code_original, -- public
					chr(1)||'*' AS unite_fonctionnelle_code_original -- public
				from w_cnt_bul
			;

			UPDATE w_profils SET
				salarie_id = p_salaries.oid
			FROM rh.p_salaries
			WHERE w_profils.matr = p_salaries.code_original
			; 
            
            ]]>
		</sqlcmd>
		</NODE>
		<NODE name="PROFIL" type="common" />
		<NODE label="Profils par code analytique">
		<sqlcmd><![CDATA[
			-- Création des profils
            DROP TABLE IF EXISTS w_profils_anal
            ;

            CREATE TEMP TABLE w_profils_anal AS
                WITH contrats_mois AS (
                SELECT
                    salarie_id,
                    mois_paie,
                    date_fin_cont,
                    code_anal,
                    REPLACE(code_anal_ratio, ',', '.')::numeric AS code_anal_ratio
                FROM w_profils,  unnest(codes_anal, codes_anal_ratio) as x(code_anal, code_anal_ratio)
                ),
                codes_anal AS (
                SELECT 
                    salarie_id,
                    mois_paie,
                    date_fin_cont,
                    code_anal,
                    SUM(code_anal_ratio) AS code_anal_ratio
                FROM contrats_mois
                GROUP BY 1,2,3,4
                )
                SELECT 
                    row_number() over () as row_id,
                    profil_id,
                    contrat_id,
                    contrat_mois_id,
                    w_profils.salarie_id,
                    w_profils.id_etab,
                    w_profils.id_sala,
                    w_profils.matr,
                    w_profils.ncnt_ori,
                    w_profils.peri,
                    w_profils.date_debu_cont,
                    w_profils.date_fin_cont,
                    w_profils.date_anci,
                    w_profils.date_debut,
                    w_profils.date_fin,
                    w_profils.date_nais,
                    w_profils.mois_paie,
                    w_profils.date_paie,
                    w_profils.est_hors_periode,
                    w_profils.motif_debut_code_original,
                    w_profils.motif_fin_code_original,
                    w_profils.categorie_socio_professionnelle_code_original,
                    w_profils.qualification_code_original,
                    w_profils.service_code_original,
                    w_profils.code_emploi_code_original,
                    w_profils.grille_code_original,
                    w_profils.grille_groupe_code_original,
                    w_profils.specialite_code_original,
                    w_profils.groupe_cotisant_code_original,
                    w_profils.societe_interim_code_original,
                    w_profils.hora_mens_fich,
                    w_profils.statut_code_original,
                    w_profils.type_contrat_code_original,
                    w_profils.type_horaire_code_original,
                    w_profils.type_temps_travail_code_original,
                    w_profils.cadre_emploi_code_original, -- public
                    w_profils.categorie_conge_code_original, -- public
                    w_profils.categorie_statutaire_code_original, -- public
                    w_profils.commission_paritaire_code_original, -- public
                    w_profils.compte_salarie_code_original, -- public
                    w_profils.filiere_code_original, -- public
                    w_profils.lettre_budgetaire_code_original, -- public
                    w_profils.unite_fonctionnelle_code_original, -- public,
                    codes_anal.code_anal AS section_analytique_code_original,
                    codes_anal.code_anal AS section_analytique_paie_code_original,
                    codes_anal.code_anal_ratio
                FROM w_profils
                JOIN codes_anal ON codes_anal.salarie_id = w_profils.salarie_id AND codes_anal.mois_paie = w_profils.mois_paie AND codes_anal.date_fin_cont = w_profils.date_fin_cont
            ;
            ]]></sqlcmd>
		</NODE>
		<NODE label="Salariés">
			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_salaries
			;

			CREATE TEMP TABLE w_salaries AS
				select
                    rhp('finess') AS finess,
                    trim(w_cnt_bul.matr) as matricule,
                    trim(w_cnt_bul.matr) as matricule_planning,
                    trim(w_cnt_bul.matr) as code,
                    trim(w_cnt_bul.matr) as code_original,
                    t_etablissements.entreprise_id,
                    (max(array[w_cnt_bul.peri::text , nom]))[2] as nom,
                    (max(array[w_cnt_bul.peri::text , nom_jeun_fill]))[2] as nom_naissance,
                    (max(array[w_cnt_bul.peri::text , pren]))[2] as prenom,
                    (max(array[w_cnt_bul.peri, w_cnt_bul.date_nais]))[2]::date as date_naissance,
                    case when (max(array[w_cnt_bul.peri::text , titr]))[2] = 'Mr' then 'M' else 'F' end as sexe,
                    coalesce((max(array[extract(epoch from w_cnt_bul.peri) , t_nationalites.oid]))[2], 0) as nationalite_id,
                    coalesce((max(array[extract(epoch from w_cnt_bul.peri) , t_codes_postaux.oid]))[2], 0) as code_postal_id,
                    coalesce((max(array[extract(epoch from w_cnt_bul.peri) , t_situations_famille.oid]))[2], 0) AS situation_famille_id,
                    coalesce((max(array[extract(epoch from w_cnt_bul.peri) , w_profils.profil_id]))[2], 0) AS profil_id,
                    max(w_cnt_bul.date_debu_cont) AS date_debut,
                    max(w_cnt_bul.date_fin_cont) AS date_fin,
                    min(w_cnt_bul.date_emba) as date_entree_ets,
                    max(w_cnt_bul.date_depa) 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
                from w_cnt_bul
                    JOIN rh.t_etablissements ON t_etablissements.code_original = w_cnt_bul.id_etab
                    LEFT JOIN rh.t_situations_famille on t_situations_famille.code_original = w_cnt_bul.situ_fami
                    LEFT JOIN rh.t_nationalites on t_nationalites.code_original = w_cnt_bul.nati
                    LEFT JOIN rh.t_codes_postaux on t_codes_postaux.code = w_cnt_bul.code_post
                    LEFT JOIN w_profils on w_profils.matr = w_cnt_bul.matr
                group by 1,2,3,4,5,6,  20,21,22,23,24
			;

			]]></sqlcmd>
		</NODE>
		<NODE name="SALARIE" type="common" />
        <NODE label="Salariés (Màj oid)">
            <sqlcmd><![CDATA[

            UPDATE w_profils SET
                salarie_id = p_salaries.oid
            FROM rh.p_salaries
            WHERE w_profils.matr = p_salaries.code_original
            ;

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

			TRUNCATE rh.p_contrats
			;

			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

			INSERT INTO rh.p_contrats(
					salarie_id,
					date_debut,
					date_fin,
					numero_contrat,
					code_original,
					etablissement_id,
					profil_id)
				SELECT
					p_salaries.oid AS salarie_id,
					w_cnt.date_debu_cont AS date_debut,
					w_cnt.date_fin_cont AS date_fin,
					w_cnt.ncnt AS numero_contrat,
					w_cnt.ncnt_ori AS code_original,
					t_etablissements.oid AS etablissement_id,
                    0 as profil_id
				FROM w_cnt
                    JOIN rh.p_salaries ON p_salaries.code_original = w_cnt.matr
					JOIN rh.t_etablissements ON t_etablissements.code_original = w_cnt.id_etab
                GROUP BY 1,2,3,4,5,6,7
			;

            UPDATE rh.p_contrats
            SET
                anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
                anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_calculee_mois
            FROM (
                select
                    ncnt_ori,
                    coalesce(sum(date_fin_cont - date_debu_cont + 1) over w, 0) AS anciennete_anterieure_jours,
                    coalesce(sum(date_fin_cont - date_debu_cont + 1) over w / 30::numeric, 0) AS anciennete_anterieure_calculee_mois
                from w_cnt
                window w as (partition by id_etab, id_sala order by date_debu_cont rows between UNBOUNDED PRECEDING and 1 preceding)) AS subq
            WHERE 1=1
                AND p_contrats.code_original = subq.ncnt_ori
            ;

			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

            INSERT INTO rh.p_contrats_mois(
                salarie_id,
                contrat_id,
                profil_id,
                code_original,
                mois_activite,
                date_debut,
                date_fin,
                nombre_entrees,
                nombre_departs,
                nombre_debut_contrat,
                nombre_fin_contrat,
                est_hors_periode, -- bulletins de paie hors période de contrat.
                present_debut_mois,
                present_fin_mois,
                equivalent_temps_plein,
                age_id,
                age_jours,
                anciennete_jours,
                anciennete_mois,
                anciennete_annee_id,
                etablissement_id)
                SELECT
                    p_contrats.salarie_id,
                    p_contrats.oid as contrat_id,
                    w_profils.profil_id,
                    w_profils.row_id,
                    w_profils.mois_paie as mois_activite,
                    w_profils.date_debut,
                    w_profils.date_fin,
                    case when p_salaries.date_entree_ets between w_profils.date_debut and w_profils.date_fin then 1 else 0 end as nombre_entrees,
                    case when p_salaries.date_sortie_ets between w_profils.date_debut and w_profils.date_fin then 1 else 0 end as nombre_departs,
                    case when p_contrats.date_debut between w_profils.date_debut and w_profils.date_fin then 1 else 0 end as nombre_debut_contrat,
                    case when p_contrats.date_fin between w_profils.date_debut and w_profils.date_fin then 1 else 0 end as nombre_fin_contrat,
                    w_profils.est_hors_periode,
                    case when w_profils.date_debut = base.cti_first_day(w_profils.date_debut) then 1 else 0 end as present_debut_mois,
                    case when w_profils.date_fin = base.cti_last_day(w_profils.date_fin) then 1 else 0 end as present_fin_mois,
                    1 as equivalent_temps_plein, -- ! Mettre le bon ETP.
                    base.cti_age(w_profils.date_fin, coalesce(w_profils.date_nais, '1962-04-18'::date), 'ny') AS age_id,
                    w_profils.date_fin - coalesce(w_profils.date_nais, '1962-04-18'::date) AS age_jours,
                    p_contrats.anciennete_anterieure_jours
						+ (w_profils.date_fin - w_profils.date_debu_cont)
						+ 1
					    AS anciennete_jours,
					base.cti_age(date_trunc('month', w_profils.date_fin)::date, date_trunc('month', w_profils.date_debu_cont)::date, 'nm')
						+ p_contrats.anciennete_anterieure_calculee_mois + 1
                        AS anciennete_mois,
					floor((base.cti_age(date_trunc('month', w_profils.date_fin)::date, date_trunc('month', w_profils.date_debu_cont)::date, 'nm')
						+ p_contrats.anciennete_anterieure_calculee_mois + 1) / 12)
                        AS anciennete_annee_id,
                    p_contrats.etablissement_id
                FROM w_profils
                    JOIN rh.p_contrats on p_contrats.code_original = w_profils.ncnt_ori
                    JOIN rh.p_salaries on p_salaries.oid = p_contrats.salarie_id
            ;

			-- Association contrat selon code orginal
			UPDATE w_profils
			SET contrat_id = p_contrats_mois.contrat_id,
				contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			JOIN rh.p_contrats ON p_contrats_mois.contrat_id = p_contrats.oid
			WHERE ncnt_ori = p_contrats.code_original AND
				p_contrats_mois.mois_activite = w_profils.mois_paie
            ;
			
			UPDATE w_profils_anal
			SET contrat_id = p_contrats_mois.contrat_id,
				contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			JOIN rh.p_contrats ON p_contrats_mois.contrat_id = p_contrats.oid
			WHERE ncnt_ori = p_contrats.code_original AND
				p_contrats_mois.mois_activite = w_profils_anal.mois_paie
            ;
			
			-- Ancienne version par securite
			UPDATE w_profils SET
				contrat_id = p_contrats_mois.contrat_id,
				contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			WHERE w_profils.contrat_id = 0 AND
				p_contrats_mois.salarie_id = w_profils.salarie_id AND p_contrats_mois.mois_activite = w_profils.mois_paie
            ;
			
			-- Ancienne version par securite
			UPDATE w_profils_anal
			SET contrat_id = p_contrats_mois.contrat_id,
				contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			WHERE w_profils_anal.contrat_id = 0 AND
				p_contrats_mois.salarie_id = w_profils_anal.salarie_id AND p_contrats_mois.mois_activite = w_profils_anal.mois_paie
            ;

			]]></sqlcmd>
		</NODE>
        <NODE label="Pre-traitement de la paie">
            <sqlcmd><![CDATA[

            DROP TABLE IF EXISTS w_hp
            ;

            CREATE TEMP TABLE w_hp AS
                SELECT
                    trim(w_hp_0.id_sala)||'-'::text||w_hp_0.peri as id_bul,
                    w_hp_0.id_etab,
                    w_hp_0.id_sala,
                    w_profils.matr,
                    w_profils.contrat_mois_id,
                    w_profils.contrat_id,
                    w_profils.salarie_id,
                    w_profils.profil_id,
                    case when to_char(w_profils.date_debu_cont, 'YYYYMM') = to_char(w_hp_0.peri, 'YYYYMM') then w_profils.date_debu_cont else base.cti_first_day(w_hp_0.peri) end as date_debut,
                    case when to_char(w_profils.date_fin_cont, 'YYYYMM') = to_char(w_hp_0.peri, 'YYYYMM') then w_profils.date_fin_cont else base.cti_last_day(w_hp_0.peri) end as date_fin,
                    w_hp_0.peri as date_paie,
                    w_hp_0.mois_paie,
                    t_rubriques.oid AS rubrique_id,
                    t_rubriques.p_detail,
                    t_rubriques.p_cumul,
                    t_rubriques.c_base
                        * case when @t_rubriques.c_base != 1 then coalesce(case when proratiser_conversion then w_profils.ratio_theo else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_base THEN (CASE s_base
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                            END) else 0 end AS base,
                    t_rubriques.c_nombre
                        * case when @t_rubriques.c_nombre != 1 then coalesce(case when proratiser_conversion then w_profils.ratio_theo else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_nombre THEN (CASE s_nombre
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                            END) else 0 end AS nombre,
                    t_rubriques.c_heures_contrat
                        * case when @t_rubriques.c_heures_contrat != 1 then coalesce(case when proratiser_conversion then w_profils.ratio_theo else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_contrat
                            then (CASE s_heures_contrat
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                            END)
                            else 0 end
                        AS heure_contrat,
                    t_rubriques.c_heures_payees
                        * case when @t_rubriques.c_heures_payees != 1 then coalesce(case when proratiser_conversion then w_profils.ratio_theo else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_payees
                            then (CASE s_heures_payees
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                            END) else 0 end AS heure_payee,
                    t_rubriques.c_heures_travaillees
                        * case when @t_rubriques.c_heures_travaillees != 1 then coalesce(case when proratiser_conversion then w_profils.ratio_theo else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_travaillees
                            then (CASE s_heures_travaillees
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END) else 0 end AS heure_travaillee,
                    t_rubriques.c_masse_salariale
                        * (CASE WHEN p_masse_salariale      THEN
                            (CASE s_masse_salariale
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            else 0 end) AS masse_salariale,
                    t_rubriques.c_brut
                        * (CASE WHEN p_brut                 THEN
                            (CASE s_brut
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            else 0 end) AS montant_brut,
                    t_rubriques.c_frais_imposables
                        * (case when p_frais_imposables     then
                            (CASE s_frais_imposables
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            else 0 end) AS montant_frais_imposables,
                    t_rubriques.coefficient_txs * (case when p_cotisation_salarie   then w_hp_0.tx_sal else 0 end) AS taux_sal,
                    t_rubriques.c_cotisation_salarie
                        * (case when p_cotisation_salarie   then
                            (CASE s_cotisation_salarie
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            else 0 end) AS montant_cot_sal,
                    t_rubriques.coefficient_txp * (case when p_cotisation_patronale then w_hp_0.tx_pat else 0 end) AS taux_pat,
                    t_rubriques.c_cotisation_patronale
                        * (case when p_cotisation_patronale then
                            (CASE s_cotisation_patronale
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            else 0 end) AS montant_cot_pat,
                    t_rubriques.c_od_net_salarie
                        * (CASE WHEN p_od_net_salarie       THEN
                            (CASE s_od_net_salarie
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            ELSE 0 END) AS od_net,
                    t_rubriques.c_od_net_patronale
                        * (CASE WHEN p_od_net_patronale     THEN
                            (CASE s_od_net_patronale
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            ELSE 0 END) AS od_net_p,
                    t_rubriques.c_avantage_nature
                        * (CASE WHEN p_avantage_nature      THEN
                            (CASE s_avantage_nature
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            ELSE 0 END) AS avt_nat,
                    t_rubriques.c_net_imposable
                        * (CASE WHEN p_net_imposable        THEN
                            (CASE s_net_imposable
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            ELSE 0 END) AS net_imposable,
                    t_rubriques.c_net_a_payer
                        * (CASE WHEN p_net_a_payer          THEN
                            (CASE s_net_a_payer
                                WHEN 0 THEN w_hp_0.nombre
                                WHEN 1 THEN w_hp_0.base
                                WHEN 2 THEN w_hp_0.tx_sal
                                WHEN 3 THEN w_hp_0.mt_sal
                                WHEN 4 THEN w_hp_0.tx_pat
                                WHEN 5 THEN w_hp_0.mt_pat
                                WHEN 6 THEN w_hp_0.mt_sal + w_hp_0.mt_pat
                                WHEN 7 THEN w_hp_0.mt_sal - w_hp_0.mt_pat
                                WHEN 8 THEN w_hp_0.mt_pat - w_hp_0.mt_sal
                                END)
                            ELSE 0 END) AS net_a_payer
                FROM w_hp_0
                    JOIN w_profils ON true
                        and w_profils.id_etab = w_hp_0.id_etab
                        and w_profils.id_sala = w_hp_0.id_sala
                        and w_profils.peri = w_hp_0.peri
                    JOIN rh.t_rubriques ON t_rubriques.code_original = w_hp_0.id_rubr
                where 1=1
                    AND w_hp_0.peri >= rhp('rhprovider_start')::date
                    -- Filtrer les lignes générées systématiquement tous les mois par Sage pour chaque salarié méme s'il n'y a rien.
                    AND (false
                        OR p_nombre
                        OR p_base
                        OR p_heures_contrat
                        OR p_heures_payees
                        OR p_heures_travaillees
                        OR p_masse_salariale
                        OR p_brut
                        OR p_avantage_nature
                        OR p_frais_imposables
                        OR p_cotisation_salarie
                        OR p_cotisation_patronale
                        OR p_od_net_salarie
                        OR p_od_net_patronale
                        OR p_net_imposable
                        OR p_net_a_payer)
            ;

			]]></sqlcmd>
		</NODE>
        <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_etablissements.entreprise_id,
                    t_etablissements.oid as etablissement_id,
                    w_hp.mois_paie,
                    count(DISTINCT matr),
                    sum(CASE WHEN p_cumul THEN montant_brut ELSE 0 END),
                    sum(CASE WHEN p_cumul THEN heure_payee ELSE 0 END)
                FROM w_hp
                    JOIN rh.t_etablissements ON t_etablissements.code_original = w_hp.id_etab
                WHERE true
                    and w_hp.mois_paie >= to_char(rhp('rhprovider_start')::date, 'YYYYMM')::int
                 GROUP BY 1,2,3
			;

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

            -- Génération paie
            SELECT base.cti_stash_table_indexes('rh', 'p_historique_paie')
            ;

            TRUNCATE rh.p_historique_paie
            ;

            INSERT INTO rh.p_historique_paie(
                code_original,
                age_id,
                base,
                nombre,
                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,
                organisme_cotisation_id,
                profil_id,
                rubrique_id,
                compte_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie)
                SELECT
                    w_hp.id_bul as code_original,
                    date_part('year', age(w_hp.date_fin, date_naissance)) AS age_id,
                    w_hp.base,
                    w_hp.nombre,
                    w_hp.contrat_id,
                    w_hp.contrat_mois_id,
                    w_hp.date_debut,
                    w_hp.date_fin,
                    w_hp.date_paie AS date_paie,
                    w_hp.mois_paie AS mois_activite,
                    w_hp.mois_paie AS mois_paie,
                    w_hp.heure_contrat,
                    w_hp.heure_payee,
                    w_hp.heure_travaillee,
                    w_hp.avt_nat AS montant_avantage_nature,
                    w_hp.montant_brut AS montant_brut,
                    w_hp.masse_salariale as montant_masse_salariale,
                    w_hp.montant_cot_pat AS montant_cotisation_patronale,
                    w_hp.montant_cot_sal AS montant_cotisation_salarie,
                    w_hp.montant_frais_imposables,
                    w_hp.net_a_payer AS montant_net_a_payer_salarie,
                    w_hp.net_imposable AS montant_net_imposable_salarie,
                    w_hp.od_net AS montant_od_net_salarie,
                    0 AS organisme_cotisation_id,
                    w_hp.profil_id,
                    w_hp.rubrique_id,
                    0 AS compte_id,
                    w_hp.salarie_id,
                    w_hp.taux_pat AS taux_cotisation_patronale,
                    w_hp.taux_sal AS taux_cotisation_salarie
                FROM w_hp
                    JOIN rh.p_salaries ON p_salaries.oid = w_hp.salarie_id
                WHERE p_detail
            ;

            SELECT base.cti_stash_pop_table_indexes('rh', 'p_historique_paie')
            ;

            -- 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_avantage_nature) as total_avantage_nature,
                    bool_or(p_cumul and p_brut) as total_brut,
                    bool_or(p_cumul and p_masse_salariale) as total_masse_salariale,
                    bool_or(p_cumul and p_cotisation_patronale) as total_cot_pat,
                    bool_or(p_cumul and p_cotisation_salarie) as total_cot_sal,
                    bool_or(p_cumul and p_net_a_payer) as total_payer,
                    bool_or(p_cumul and p_net_imposable) as total_imposable,
                    bool_or(p_cumul and p_heures_contrat) as total_h_contrat,
                    bool_or(p_cumul and p_heures_payees) as total_h_payees,
                    bool_or(p_cumul and p_heures_travaillees) as total_h_travaillees
                FROM rh.t_rubriques
            ;

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

            CREATE TEMP TABLE w_totaux AS
                SELECT
                    w_hp.id_bul as code_original,
                    w_hp.id_etab,
                    w_hp.id_sala,
                    w_hp.date_paie as date,
                    w_hp.mois_paie,
                    round(sum(case when p_cumul then avt_nat else 0 end), 2) AS hcum_avantage_nature,
                    round(sum(case when p_cumul then montant_brut else 0 end), 2) AS hcum_brut,
                    round(sum(case when p_cumul then masse_salariale else 0 end), 2) AS hcum_masse_salariale,
                    round(sum(case when p_cumul then montant_cot_pat else 0 end), 2) AS hcum_cotisation_patronale,
                    round(sum(case when p_cumul then montant_cot_sal else 0 end), 2) AS hcum_cotisation_salarie,
                    0::numeric AS hcum_frais_imposables,
                    round(sum(case when p_cumul then net_a_payer else 0 end), 2) AS hcum_net_a_payer_salarie,
                    round(sum(case when p_cumul then net_imposable else 0 end), 2) AS hcum_net_imposable_salarie,
                    sum(case when p_cumul then heure_contrat else 0 end) AS hcum_heures_contrat,
                    sum(case when p_cumul then heure_payee else 0 end) AS hcum_heures_payees,
                    sum(case when p_cumul then heure_travaillee else 0 end) AS hcum_heures_travaillees,
                    0::numeric AS montant_od_net_salarie
                FROM w_hp
                WHERE p_cumul
                GROUP BY 1,2,3,4,5
            ;

			-- Insérer 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 (
                code_original,
				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_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,
                organisme_cotisation_id,
                profil_id,
                rubrique_id,
				compte_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie)
				SELECT
                    subq.code_original,
					subq.age_id,
					subq.contrat_id,
					subq.contrat_mois_id,
					subq.date_debut,
					subq.date_fin,
					subq.date_paie,
					subq.mois_activite,
					subq.mois_paie,
					0 AS base,
                    0 AS nombre,
                    case when total_h_contrat then COALESCE(hcum_heures_contrat, 0) - subq.heure_contrat else 0.0 end AS heure_contrat,
                    case when total_h_payees then COALESCE(hcum_heures_payees,0) - subq.heure_payee else 0.0 end AS heure_payee,
                    case when total_h_travaillees then COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee else 0.0 end AS heure_travaillee,
					case when total_avantage_nature then COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature else 0.0 end AS montant_avantage_nature,
					case when total_brut then COALESCE(hcum_brut,0) - subq.montant_brut else 0.0 end AS montant_brut,
                    case when total_masse_salariale then COALESCE(hcum_masse_salariale, 0) - subq.montant_masse_salariale else 0.0 end AS montant_masse_salariale,
					case when total_cot_pat then COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale else 0.0 end AS montant_cotisation_patronale,
					case when total_cot_sal then COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie else 0.0 end AS montant_cotisation_salarie,
					0 AS montant_frais_imposables,
					case when total_payer then COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie else 0.0 end AS montant_net_a_payer_salarie,
					case when total_imposable then COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie else 0.0 end AS montant_net_imposable_salarie,
					0 AS montant_od_net_salarie,
					subq.organisme_cotisation_id AS organisme_cotisation_id,
					subq.profil_id AS profil_id,
					(SELECT oid FROM rh.t_rubriques WHERE code = 'C000') AS rubrique_id,
					0 AS compte_id,
					subq.salarie_id AS salarie_id,
					0 AS taux_cotisation_patronale,
					0 AS taux_cotisation_salarie
				FROM (
					SELECT
                        p_historique_paie.code_original,
						p_historique_paie.age_id,
						p_historique_paie.contrat_id,
						p_historique_paie.contrat_mois_id,
						p_historique_paie.date_debut,
						p_historique_paie.date_fin,
						p_historique_paie.date_paie,
						p_historique_paie.mois_activite,
						p_historique_paie.mois_paie,
						0 AS base,
                        0 AS nombre,
                        sum(heure_contrat) AS heure_contrat,
                        sum(heure_payee) AS heure_payee,
                        sum(heure_travaillee) AS heure_travaillee,
						sum(montant_avantage_nature) AS montant_avantage_nature,
						sum(montant_brut) AS montant_brut,
                        sum(montant_masse_salariale) AS montant_masse_salariale,
						sum(montant_cotisation_patronale) AS montant_cotisation_patronale,
						sum(montant_cotisation_salarie) AS montant_cotisation_salarie,
						0 AS montant_frais_imposables,
						sum(montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
						sum(montant_net_imposable_salarie) AS montant_net_imposable_salarie,
						0 AS montant_od_net_salarie,
						p_historique_paie.organisme_cotisation_id,
						p_historique_paie.profil_id,
						(SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
						p_historique_paie.salarie_id,
						0 AS taux_cotisation_patronale,
						0 AS taux_cotisation_salarie
					FROM rh.p_historique_paie
						JOIN rh.p_salaries ON p_salaries.oid = p_historique_paie.salarie_id
					GROUP BY 1,2,3,4,5,6,7,8,9,10,11, 24,25,26,27) AS subq
				JOIN w_totaux ON w_totaux.code_original = subq.code_original
                JOIN w_cumul ON true
			WHERE 1!=1
				OR case when total_avantage_nature then COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature != 0 else false end
				OR case when total_brut then COALESCE(hcum_brut,0) - subq.montant_brut != 0 else false end
                OR case when total_masse_salariale then COALESCE(hcum_masse_salariale,0) - subq.montant_masse_salariale != 0 else false end
				OR case when total_payer then COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie != 0 else false end
				OR case when total_imposable then COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie != 0 else false end
                OR case when total_cot_pat then COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale != 0 else false end
                OR case when total_cot_sal then COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie != 0 else false end
                OR case when total_h_contrat then COALESCE(hcum_heures_contrat, 0) - subq.heure_contrat != 0 else false end
                OR case when total_h_payees then COALESCE(hcum_heures_payees,0) - subq.heure_payee != 0 else false end
                OR case when total_h_travaillees then COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee != 0 else false end
			;
			
			ANALYSE rh.p_historique_paie
			;

            ]]></sqlcmd>
        </NODE>
		<NODE label="Ventilation des profils">
			<sqlcmd><![CDATA[
			
			-- Ajout des nouveaux profils analytiques
			INSERT INTO rh.p_profils
			(
				cadre_emploi_code_original,
				categorie_conge_code_original,
				categorie_socio_professionnelle_code_original,
				categorie_statutaire_code_original,
				code_emploi_code_original,
				commission_paritaire_code_original,
				compte_salarie_code_original,
				filiere_code_original,
				grille_code_original,
				grille_groupe_code_original,
				groupe_cotisant_code_original,
				lettre_budgetaire_code_original,
				motif_debut_code_original,
				motif_fin_code_original,
				qualification_code_original,
				section_analytique_code_original,
				section_analytique_paie_code_original,
				service_code_original,
				societe_interim_code_original,
				specialite_code_original,
				statut_code_original,
				type_contrat_code_original,
				type_horaire_code_original,
				type_temps_travail_code_original,
				unite_fonctionnelle_code_original
			)
			SELECT
				w_profils_anal.cadre_emploi_code_original,
				w_profils_anal.categorie_conge_code_original,
				w_profils_anal.categorie_socio_professionnelle_code_original,
				w_profils_anal.categorie_statutaire_code_original,
				w_profils_anal.code_emploi_code_original,
				w_profils_anal.commission_paritaire_code_original,
				w_profils_anal.compte_salarie_code_original,
				w_profils_anal.filiere_code_original,
				w_profils_anal.grille_code_original,
				w_profils_anal.grille_groupe_code_original,
				w_profils_anal.groupe_cotisant_code_original,
				w_profils_anal.lettre_budgetaire_code_original,
				w_profils_anal.motif_debut_code_original,
				w_profils_anal.motif_fin_code_original,
				w_profils_anal.qualification_code_original,
				w_profils_anal.section_analytique_code_original,
				w_profils_anal.section_analytique_paie_code_original,
				w_profils_anal.service_code_original,
				w_profils_anal.societe_interim_code_original,
				w_profils_anal.specialite_code_original,
				w_profils_anal.statut_code_original,
				w_profils_anal.type_contrat_code_original,
				w_profils_anal.type_horaire_code_original,
				w_profils_anal.type_temps_travail_code_original,
				w_profils_anal.unite_fonctionnelle_code_original
			FROM w_profils_anal
			LEFT JOIN rh.p_profils ON
				w_profils_anal.cadre_emploi_code_original = p_profils.cadre_emploi_code_original AND
				w_profils_anal.categorie_conge_code_original = p_profils.categorie_conge_code_original AND
				w_profils_anal.categorie_socio_professionnelle_code_original = p_profils.categorie_socio_professionnelle_code_original AND
				w_profils_anal.categorie_statutaire_code_original = p_profils.categorie_statutaire_code_original AND
				w_profils_anal.code_emploi_code_original = p_profils.code_emploi_code_original AND
				w_profils_anal.commission_paritaire_code_original = p_profils.commission_paritaire_code_original AND
				w_profils_anal.compte_salarie_code_original = p_profils.compte_salarie_code_original AND
				w_profils_anal.filiere_code_original = p_profils.filiere_code_original AND
				w_profils_anal.grille_code_original = p_profils.grille_code_original AND
				w_profils_anal.grille_groupe_code_original = p_profils.grille_groupe_code_original AND
				w_profils_anal.groupe_cotisant_code_original = p_profils.groupe_cotisant_code_original AND
				w_profils_anal.lettre_budgetaire_code_original = p_profils.lettre_budgetaire_code_original AND
				w_profils_anal.motif_debut_code_original = p_profils.motif_debut_code_original AND
				w_profils_anal.motif_fin_code_original = p_profils.motif_fin_code_original AND
				w_profils_anal.qualification_code_original = p_profils.qualification_code_original AND
				w_profils_anal.section_analytique_code_original = p_profils.section_analytique_code_original AND
				w_profils_anal.section_analytique_paie_code_original = p_profils.section_analytique_paie_code_original AND
				w_profils_anal.service_code_original = p_profils.service_code_original AND
				w_profils_anal.societe_interim_code_original = p_profils.societe_interim_code_original AND
				w_profils_anal.specialite_code_original = p_profils.specialite_code_original AND
				w_profils_anal.statut_code_original = p_profils.statut_code_original AND
				w_profils_anal.type_contrat_code_original = p_profils.type_contrat_code_original AND
				w_profils_anal.type_horaire_code_original = p_profils.type_horaire_code_original AND
				w_profils_anal.type_temps_travail_code_original = p_profils.type_temps_travail_code_original AND
				w_profils_anal.unite_fonctionnelle_code_original = p_profils.unite_fonctionnelle_code_original
			WHERE p_profils.oid IS NULL
			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
			;

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

			-- Màj des profil_id dans la table temporaire
			UPDATE w_profils_anal
			SET profil_id = p_profils.oid
			FROM rh.p_profils
			WHERE 1=1
				AND p_profils.cadre_emploi_code_original                    = w_profils_anal.cadre_emploi_code_original
				AND p_profils.categorie_conge_code_original                 = w_profils_anal.categorie_conge_code_original
				AND p_profils.categorie_socio_professionnelle_code_original = w_profils_anal.categorie_socio_professionnelle_code_original
				AND p_profils.categorie_statutaire_code_original            = w_profils_anal.categorie_statutaire_code_original
				AND p_profils.code_emploi_code_original                     = w_profils_anal.code_emploi_code_original
				AND p_profils.commission_paritaire_code_original            = w_profils_anal.commission_paritaire_code_original
				AND p_profils.compte_salarie_code_original                  = w_profils_anal.compte_salarie_code_original
				AND p_profils.filiere_code_original                         = w_profils_anal.filiere_code_original
				AND p_profils.grille_code_original                          = w_profils_anal.grille_code_original
				AND p_profils.grille_groupe_code_original                   = w_profils_anal.grille_groupe_code_original
				AND p_profils.groupe_cotisant_code_original                 = w_profils_anal.groupe_cotisant_code_original
				AND p_profils.lettre_budgetaire_code_original               = w_profils_anal.lettre_budgetaire_code_original
				AND p_profils.motif_debut_code_original                     = w_profils_anal.motif_debut_code_original
				AND p_profils.motif_fin_code_original                       = w_profils_anal.motif_fin_code_original
				AND p_profils.qualification_code_original                   = w_profils_anal.qualification_code_original
				AND p_profils.section_analytique_code_original              = w_profils_anal.section_analytique_code_original
				AND p_profils.section_analytique_paie_code_original         = w_profils_anal.section_analytique_paie_code_original
				AND p_profils.service_code_original                         = w_profils_anal.service_code_original
				AND p_profils.societe_interim_code_original                 = w_profils_anal.societe_interim_code_original
				AND p_profils.specialite_code_original                      = w_profils_anal.specialite_code_original
				AND p_profils.statut_code_original                          = w_profils_anal.statut_code_original
				AND p_profils.type_contrat_code_original                    = w_profils_anal.type_contrat_code_original
				AND p_profils.type_horaire_code_original                    = w_profils_anal.type_horaire_code_original
				AND p_profils.type_temps_travail_code_original              = w_profils_anal.type_temps_travail_code_original
				AND p_profils.unite_fonctionnelle_code_original             = w_profils_anal.unite_fonctionnelle_code_original
            ;

            -- On renseigne le dernier profil connu (= dernière situation) pour chaque contrat.
            WITH toto AS (
                SELECT
                    contrat_id,
                    (max(ARRAY[extract(EPOCH from date_debut), profil_id]))[2] as profil_id
                FROM rh.p_contrats_mois
                GROUP BY 1
            )
            UPDATE rh.p_contrats SET
                profil_id = toto.profil_id
            FROM toto
            WHERE p_contrats.oid = toto.contrat_id
            ;
			
            -- Regroupement des codes analytiques par mois
            DROP TABLE IF EXISTS w_profil_contrat_mois_anal
            ;

			CREATE TEMP TABLE w_profil_contrat_mois_anal AS (
                SELECT
                    profil_id, 
                    contrat_mois_id,
                    SUM(code_anal_ratio) / 100 AS ratio_theo
                FROM w_profils_anal
                GROUP BY profil_id, contrat_mois_id
            )
            ;
			
			-- Correction si somme différente de 1
			UPDATE w_profil_contrat_mois_anal
			SET ratio_theo = ratio_theo * coeff
			FROM
			(
                SELECT contrat_mois_id, sum(ratio_theo), base.cti_division(1,sum(ratio_theo)) AS coeff
                FROM w_profil_contrat_mois_anal
                GROUP BY 1
                HAVING sum(ratio_theo) <> 1 AND sum(ratio_theo) <> 0
			) AS subview
			WHERE w_profil_contrat_mois_anal.contrat_mois_id = subview.contrat_mois_id
			;

			UPDATE w_profil_contrat_mois_anal
			SET ratio_theo = ratio_corr
			FROM
			(
                SELECT contrat_mois_id, sum(ratio_theo), base.cti_division(1,count(*)) AS ratio_corr
                FROM w_profil_contrat_mois_anal
                GROUP BY 1
                HAVING sum(ratio_theo) = 0
			) AS subview
			WHERE w_profil_contrat_mois_anal.contrat_mois_id = subview.contrat_mois_id
			;

			-- 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_profil_contrat_mois_anal.profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					w_profil_contrat_mois_anal.ratio_theo AS ratio,
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
	            JOIN w_profil_contrat_mois_anal ON w_profil_contrat_mois_anal.contrat_mois_id = p_contrats_mois.oid
                GROUP BY 1,2,3,4,5
            ;

			]]></sqlcmd>
		</NODE>
	</NODE>
	<NODE name="POST" label="POST-TRAITEMENTS">
		<NODE name="DIVERS" type="common"/>
		<NODE label="Mise é jour de la table Divers (mois en cours)">
			<sqlcmd><![CDATA[

			-- Màj du mois non cléturé.
			-- DELETE FROM rh.t_divers
			-- WHERE code = 'MOIS_EN_COURS'
			-- ;

			-- INSERT INTO rh.t_divers(
			-- 	code,
  			-- 	texte,
  			-- 	valeur,
  			-- 	valeur_date,
  			-- 	description)
			-- VALUES(
			-- 	'MOIS_EN_COURS',
			-- 	'Mois en cours (non cléturé).',
			-- 	(SELECT to_char(date_paie_encours, 'YYYYMM') FROM w_periode),
			-- 	(SELECT date_paie_encours FROM w_periode),
			-- 	'Mois en cours (non cléturé).'
			-- 	)
			-- ;
			
			]]></sqlcmd>
		</NODE>
		<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>