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

            -- Rubrique C000 d'écart 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)
            ;

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

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

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

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

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

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

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

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

            -- Màj des Entreprises
            INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court)
                SELECT
                    s_siren,
                    s_siren,
                    max(s_lib),
                    substr(max(s_lib), 1, 50)
                FROM prod_eig.sgrheig_structures
                WHERE 1=1
                    -- @todo AND s_siren IN (SELECT rhp('siren'))
                    AND s_siren NOT IN (SELECT code_original FROM rh.t_entreprises)
                    --AND s_etab IN ('ET40', 'ET50', 'ET52', 'ET54', 'ET55', 'ET60')
                GROUP BY 1,2
            ;

            -- Màj des Etablissements
            INSERT INTO rh.t_etablissements(code_original, code, texte, texte_court, entreprise_id)
                SELECT
                    s_etab,
                    s_etab,
                    max(s_lib),
                    substr(max(s_lib), 1, 50),
                    t_entreprises.oid
                FROM prod_eig.sgrheig_structures
                    --JOIN prod_eig.sgrheig_structures ON etablissement = s_etab AND section0 = s_sect
                    JOIN rh.t_entreprises ON t_entreprises.code_original = sgrheig_structures.s_siren
                WHERE 1=1
                    -- @todo AND s_siren IN (SELECT rhp('siren'))
                    -- AND s_nic IN (SELECT rhp('entreprise'))
                    AND s_etab NOT IN (SELECT code FROM rh.t_etablissements)
                    --AND s_etab IN ('ET40', 'ET50', 'ET52', 'ET54', 'ET55', 'ET60')
                group by 1,2,5
            ;

            -- Màj des catégories socio-professionnelles
            -- TODO : voir pourquoi certains codes métiers ont plusieurs libellés (idem dans sgrheig_grilles_convention)
            INSERT INTO rh.t_categories_socio_professionnelle (code, texte, texte_court, code_original)
                SELECT lower(ctrmetier), max(ctremploi), substr(max(ctremploi), 1, 50), lower(ctrmetier)
                FROM prod_eig.sgrheig_contrats
                WHERE 1=1
                    AND lower(ctrmetier) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
                GROUP BY 1,4
            ;

            -- Màj des groupes cotisants.
			
			INSERT INTO rh.t_groupes_cotisant(code_original, code, texte, texte_court)
                SELECT split_part(regid,'.',1), split_part(regid,'.',1), reglibelle, regalias
                FROM prod_eig.sgrheig_r_gimes
                WHERE 1=1
                    AND split_part(regid,'.',1) NOT IN (SELECT code_original FROM rh.t_groupes_cotisant WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4   
            ;

            -- MOtifs début
            INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
                SELECT libalias::int::text, libalias::int::text, liblibelle, substr(liblibelle,1,50)
                FROM prod_eig.sgrheig_libell_s
                WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat WHERE code_original IS NOT NULL)
                    AND liscleliste = 'MOCO'
            ;

            INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
                SELECT 'CTI-EMB', 'CTI-EMB', 'Embauche', 'Embauche'
                WHERE 'CTI-EMB' NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat WHERE code_original IS NOT NULL)
            ;

            -- Màj des motifs de fin de contrat
            INSERT INTO rh.t_motifs_fin_contrat(code, texte, texte_court, code_original)
                SELECT libalias::int::text, liblibelle, substr(liblibelle,1,50), libalias::int::text
                FROM prod_eig.sgrheig_libell_s
                WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat WHERE code_original IS NOT NULL)
                    AND liscleliste = 'CLOT'
            ;

            -- Màj des nationalités
            INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
                SELECT percodepays, max(upper(perpays)), max(substr(upper(perpays),1,50)), percodepays
                FROM prod_eig.sgrheig_personnes
                WHERE 1=1
                    AND percodepays IS NOT NULL 
                    AND percodepays != ''
                    AND percodepays NOT IN (SELECT code_original FROM rh.t_nationalites)
                GROUP BY 1,4
            ;
            
            INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
                SELECT percodepaysnais, max(upper(perpaysnais)), max(substr(upper(perpaysnais),1,50)), percodepaysnais
                FROM prod_eig.sgrheig_personnes
                WHERE 1=1
                    AND percodepaysnais IS NOT NULL 
                    AND percodepaysnais != ''
                    AND percodepaysnais NOT IN (SELECT code_original FROM rh.t_nationalites)
                GROUP BY 1,4
            ;

            -- @TODO Màj des organismes de cotisation

            -- Màj des qualifications
            -- @TODO pour l'instant = grilles a voir avec buleltins
            INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
                --SELECT libalias::int::text, liblibelle, substr(liblibelle,1,50), libalias::int::text
                --FROM prod_eig.sgrheig_libell_s
                --WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_qualifications WHERE code_original IS NOT NULL)
                --  AND liscleliste = 'CEMP'
                SELECT  split_part(grialias,'.',1), grilibelle, substr(grilibelle,1,50), grialias
                FROM prod_eig.sgrheig_grilles_convention
                WHERE split_part(grialias,'.',1) NOT IN (SELECT code_original FROM rh.t_qualifications WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;


            -- Màj des rubriques (rang_edition est utilise pour stocker rubid)
            INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
                SELECT cru_rubrique__code__, cru_rubrique__lib__, substr(cru_rubrique__lib__,1,50), rubid::int::text, rubid::int
                FROM prod_eig.sgrheig_rubriques
                WHERE rubid::int::text NOT IN (SELECT code_original FROM rh.t_rubriques)
                GROUP BY 1,2,3,4,5
            ;

            -- comptes
			DROP TABLE IF EXISTS w_compte;
			CREATE TEMP TABLE w_compte AS 
			SELECT CPTCOMPTE, MAX(CPTLIB) AS CPTLIB
			FROM prod_eig.SBASE_EIG_A_COMPTES
			GROUP BY 1
			;
			
			INSERT INTO rh.t_compte(code, texte, texte_court, code_original)
			SELECT CPTCOMPTE, CPTLIB, CPTLIB, CPTCOMPTE
			FROM w_compte
			WHERE 1=1
				AND CPTCOMPTE NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
            ;

            UPDATE rh.t_compte SET
				code = CPTCOMPTE,
				texte_court = CPTLIB,
				texte = CPTLIB
			FROM w_compte
			WHERE CPTCOMPTE = code_original AND
				(
				code IS DISTINCT FROM CPTCOMPTE OR
				texte_court IS DISTINCT FROM CPTLIB OR
				texte IS DISTINCT FROM CPTLIB
				)
			;
			
            INSERT INTO rh.t_compte(code, texte, texte_court, code_original)
                SELECT v_cptcompte, MAX(v_cptlibelle), MAX(v_cptlibelle), v_cptcompte
                FROM prod_eig.sgrheig_profil_comptable
                WHERE 1=1
                    AND v_cptcompte NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
                GROUP BY 1
            ;
			
			INSERT INTO rh.t_compte(code, texte, texte_court, code_original)
                SELECT V_CPTLIGCOMPTE, MAX(COALESCE(CPTLIB,V_CPTLIBELLE)), MAX(COALESCE(CPTLIB,V_CPTLIBELLE)), V_CPTLIGCOMPTE
                FROM prod_eig.SGRHEIG_PROFIL_COMPTABLE
                LEFT JOIN prod_eig.SBASE_EIG_A_COMPTES ON V_CPTLIGCOMPTE = CPTCOMPTE
                WHERE 1=1
                    AND V_CPTLIGCOMPTE NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
                GROUP BY 1
            ;

            -- Màj des situations de famille
            INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
                SELECT substr(persitfam,1,1), persitfam, substr(persitfam,1,50), substr(persitfam,1,1)
                FROM prod_eig.sgrheig_personnes
                WHERE 1=1
                    AND substr(persitfam,1,1) NOT IN (SELECT code_original FROM rh.t_situations_famille)
                    AND persitfam IS NOT NULL
                GROUP BY 1,2,3,4
            ;

            -- Màj des types de contrat
            -- @TODO vérifier s'il ne faut pas utiliser la liste de libelle NACO
            INSERT INTO rh.t_types_contrat(code, texte, texte_court, code_original)
                SELECT ctrtypecontrat, ctrtypecontrat, ctrtypecontrat, ctrtypecontrat
                FROM prod_eig.sgrheig_contrats
                WHERE ctrtypecontrat NOT IN (SELECT code_original FROM rh.t_types_contrat WHERE code_original IS NOT NULL)
                GROUP BY 1
                --SELECT libalias::int::text, liblibelle, substr(liblibelle,1,50), libalias::int::text
                --FROM prod_eig.sgrheig_libell_s
                --WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_types_contrat WHERE code_original IS NOT NULL)
                --  AND liscleliste = 'NACO'
            ;

            -- Màj des statuts
            INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
                SELECT libalias::int::text, libalias::int::text, liblibelle, substr(liblibelle,1,50)
                FROM prod_eig.sgrheig_libell_s
                WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_statuts WHERE code_original IS NOT NULL)
                    AND liscleliste = 'CASP'
            ;
            

            -- Màj des types de temps de travail
            INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
            SELECT 
                    case when ctretp = 1 then 'TC' else 'TP'||(ctretp * 100)::int::text end,
                    case when ctretp = 1 then 'TC' else 'TP'||(ctretp * 100)::int::text end,
                    case when ctretp = 1 then 'Temps Complet' else 'Temps Partiel '||(ctretp * 100)::int::text|| ' %' end,
                    case when ctretp = 1 then 'TC' else 'TP '||(ctretp * 100)::int::text|| ' %' end
                FROM prod_eig.sgrheig_contrats
                WHERE  (case when ctretp = 1 then 'TC' else 'TP'||(ctretp * 100)::int::text end) NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
                GROUP BY 1,2,3,4
                ORDER BY 1 DESC
            ;

            -- Màj des services
            DROP TABLE IF EXISTS w_services_sections_etablissement
            ;

            CREATE TEMP TABLE w_services_sections_etablissement AS
                with services AS (
                    SELECT 
                        libalias::int::text AS code, 
                        liblibelle AS libelle, 
                        0::numeric AS type -- Services
                    FROM prod_eig.sgrheig_libell_s
                    WHERE liscleliste = 'SERV' 
                ),
                sections_etablissement AS (
                    SELECT 
                        ets_section AS code, 
                        s_lib AS libelle, 
                        1::numeric AS type -- Sections contrats
                    FROM prod_eig.sgrheig_structures
                )
                SELECT *
                FROM services
                UNION 
                SELECT *
                FROM sections_etablissement
                UNION
                SELECT 
                    sections_etablissement.code || ' - ' || services.code,
                    sections_etablissement.libelle || ' - ' || services.libelle,
                    2::numeric AS type -- Sections contrats + Services
                FROM sections_etablissement, services
                GROUP BY 1,2
                ORDER BY type
            ;

            INSERT INTO rh.t_services(code_original, code, texte, texte_court)
                SELECT 
                    code, 
                    code, 
                    libelle, 
                    substr(libelle,1,50)
                FROM w_services_sections_etablissement
                WHERE 
                    code NOT IN (SELECT code_original FROM rh.t_services WHERE code_original IS NOT NULL) AND
                    (SELECT valeur FROM rh.t_divers WHERE code = 'EIG_SERVICE') = w_services_sections_etablissement.type
                ORDER BY 1
            ;

            -- Màj des spécialités
            INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
                SELECT libalias::int::text, libalias::int::text, liblibelle, substr(liblibelle,1,50)
                FROM prod_eig.sgrheig_libell_s
                WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_specialites WHERE code_original IS NOT NULL)
                    AND liscleliste = 'CAPE'
            ;

            -- Màj des codes emploi
            INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
			   SELECT split_part(libalias,'.',1), split_part(libalias,'.',1), MAX(liblibelle), libalias
			   FROM prod_eig.sgrheig_libell_s
			   WHERE 1=1
					AND liscleliste = 'CEMP'
					AND split_part(libalias,'.',1) NOT IN (SELECT code_original FROM rh.t_codes_emploi)
			   GROUP BY 1,2, 4
           ;

            -- Màj des types d'horaire
            INSERT INTO rh.t_types_horaire(code_original, code, texte, texte_court)
                SELECT
                    ctrtypehoraire,
                    ctrtypehoraire,
                    ctrtypehoraire,
                    ctrtypehoraire
                FROM prod_eig.sgrheig_contrats
                WHERE true
                    AND ctrtypehoraire NOT IN (SELECT code_original FROM rh.t_types_horaire)
                GROUP BY 1,2,3,4
            ;

            -- Màj des grilles
            INSERT INTO rh.t_grilles(code, texte, texte_court, code_original)
                SELECT grialias, grilibelle, substr(grilibelle,1,50), grialias
                FROM prod_eig.sgrheig_grilles_convention
                WHERE grialias NOT IN (SELECT code_original FROM rh.t_grilles WHERE code_original IS NOT NULL)
            ;

            -- Màj des groupes de grilles
            INSERT INTO rh.t_grilles_groupes(code_original, code, texte, texte_court)
                SELECT libalias::int::text, libalias::int::text, substr(liblibelle,1,50),  substr(liblibelle,1,50)
                FROM prod_eig.sgrheig_libell_s
                WHERE 1=1
                    AND libalias::int::text NOT IN (SELECT code_original FROM rh.t_grilles_groupes WHERE code_original IS NOT NULL)
                    AND liscleliste = 'CACP'
            ;
			
			UPDATE rh.t_grilles_groupes SET
				code = libalias::int::text,
				texte_court =  substr(liblibelle,1,50),
				texte = substr(liblibelle,1,50)
			FROM prod_eig.sgrheig_libell_s
			WHERE code_original = libalias::int::text AND
				liscleliste = 'CACP' AND
				(
				code IS DISTINCT FROM libalias::int::text OR
				texte_court IS DISTINCT FROM  substr(liblibelle,1,50) OR
				texte IS DISTINCT FROM substr(liblibelle,1,50)
				)
			;

            -- Màj des sections analytiques comptables.
            INSERT INTO rh.t_sections_analytiques(code_original, code, texte, texte_court)
                SELECT etssect, etssect, MAX(designation), MAX(substr(designation, 1, 50))
                FROM prod_eig.sbase_eig_lib_section
                WHERE etssect NOT IN (SELECT code_original FROM rh.t_sections_analytiques WHERE code_original IS NOT NULL)
				GROUP BY 1
            ;

			-- Màj des sections analytiques paie.
            INSERT INTO rh.t_sections_analytiques_paie(code_original, code, texte, texte_court)
                SELECT etssect, etssect, MAX(designation), MAX(substr(designation, 1, 50))
                FROM prod_eig.sbase_eig_lib_section
                WHERE etssect NOT IN (SELECT code_original FROM rh.t_sections_analytiques_paie WHERE code_original IS NOT NULL)
				GROUP BY 1
            ;

            -- Màj des motifs d'arret
            INSERT INTO rh.t_motifs_arret(code_original, code, texte, texte_court)
                -- SELECT libalias::int::text, libalias::int::text, liblibelle, substr(liblibelle,1,50)
                -- FROM prod_eig.sgrheig_libell_s
                -- WHERE libalias::int::text NOT IN (SELECT code_original FROM rh.t_motifs_arret WHERE code_original IS NOT NULL)
                --     AND liscleliste = 'MOAB'
                SELECT rubid::int::text, cru_rubrique__code__, cru_rubrique__lib__, substr(cru_rubrique__lib__, 1, 50)
                FROM prod_eig.sgrheig_rubriques
                WHERE rubid::int::text NOT IN (SELECT code_original FROM rh.t_motifs_arret)
                GROUP BY 1,2,3,4
            ;

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

            -- Periode de paie en cours
            DROP TABLE IF EXISTS w_periode
            ;

            CREATE TEMP TABLE w_periode AS
                SELECT
                    base.cti_last_monthday(max(to_date(to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00') , 'YYYYMM') + '1 month'::interval)) as date_paie_encours,
                    to_char(base.cti_last_monthday(max(to_date(to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00') , 'YYYYMM') + '1 month'::interval)),'YYYYMM') as mois_paie_encours
                FROM prod_eig.sgrheig_historique
                    JOIN rh.t_etablissements ON t_etablissements.code_original = bl_histo_etab
                WHERE true
                    AND bl_histo_permat::int not in (5660, 6024) -- Suppression du matricule de simulation.
                    -- AND bl_histo_permat::int = 1004
                    -- AND bl_histo_etab = 'ET40'
            ;

            TRUNCATE rh.p_chiffrier_production
            ;

            DROP TABLE IF EXISTS w_hst_hp
            ;

            CREATE TEMP TABLE w_hst_hp AS
                SELECT
                    bl_histo_permat::int as v_matpers,
                    bl_histo_permat::text||'-'::text||dense_rank() OVER  (PARTITION BY bl_histo_permat ORDER BY (to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00'))::int, bl_histo_ctrid) AS cti_bul,
                    -- greatest(base.cti_first_day((bl_histo_annee::text||lpad(bl_histo_mois, 2, '0')||'01')::date), ctrdebactivite::date) as date_debut,
                    -- least(base.cti_last_day((bl_histo_annee::text||lpad(bl_histo_mois, 2, '0')||'01')::date), coalesce(ctrdaterupture::date, '2099-12-31'::date)) as date_fin,
                    -- greatest(base.cti_first_day((bl_histo_annee::text||lpad(bl_histo_mois, 2, '0')||'01')::date), ctrdebactivite::date) as datehist,
                    -- ctrdebactivite::date as date_debut,
                    -- coalesce(ctrdaterupture::date, '2099-12-31'::date) as date_fin,
                    base.cti_first_day((to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00')||'01'::text)::date) as date_debut,
                    base.cti_last_day((to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00')||'01'::text)::date) as date_fin,
                    (bl_histo_annee::int::text||lpad(bl_histo_mois::int::text, 2, '0'))::int as mois_paie,
                    base.cti_last_day((to_char(BL_HISTO_ANNEE,'FM0000') || to_char(BL_HISTO_MOIS,'FM00')||'01')::date) as date_paie,
                    bl_histo_clerub::int::text||(case when trim(bl_histo_for) like '%MAINTIEN' then '_MAINTIEN'::text else ''::text end) as bl_histo_clerub,
                    bl_histo_rub::text||(case when trim(bl_histo_for) like '%MAINTIEN' then '_MAINTIEN'::text else ''::text end) as bl_histo_rub,
                    bl_histo_sect,
                    bl_histo_schar,
                    bl_histo_ctrid,
                    bl_histo_perid,
                    bl_histo_etab,
					COALESCE(ctrcatcomptable::text,'') AS ctrcatcomptable,
                    ''::text AS bl_histo_compte,
                    SUM(CASE WHEN bl_histo_for = 'COEFBUL' THEN bl_histo_value::numeric ELSE 0 END) as coeff,
                    SUM(CASE WHEN bl_histo_for in ('DUREE', 'DUREEMAINTIEN') THEN bl_histo_value::numeric ELSE 0 END) as nombre,
                    SUM(CASE WHEN bl_histo_for in ('BASE', 'BASEMAINTIEN') THEN bl_histo_value::numeric ELSE 0 END) as base,
                    SUM(CASE WHEN bl_histo_for in ('TAUX', 'TXSALARIAL', 'TAUXMAINTIEN') THEN bl_histo_value::numeric ELSE 0 END) as taux_sal,
                    SUM(CASE WHEN bl_histo_for in ('MONTANT', 'MTSALARIAL', 'MAINTIEN') THEN bl_histo_value::numeric ELSE 0 END) as montant_sal,
                    SUM(CASE WHEN bl_histo_for = 'TXEMP' THEN bl_histo_value::numeric ELSE 0 END) as taux_emp,
                    SUM(CASE WHEN bl_histo_for = 'MTEMP' THEN bl_histo_value::numeric ELSE 0 END) as montant_emp
                FROM prod_eig.sgrheig_historique
                    left join prod_eig.sgrheig_contrats on 1=1
                        and ctrid = bl_histo_ctrid
                        --and (bl_histo_annee::text||lpad(bl_histo_mois, 2, '0'))::int between to_char(ctrdebactivite, 'YYYYMM') and to_char(coalesce(ctrdaterupture, '2099-12-31'::date), 'YYYYMM')
                WHERE bl_histo_permat::int not in (5660, 6024) -- Suppression du matricule de simulation.
                    -- AND bl_histo_permat::int = 1004
                    -- AND bl_histo_etab = 'ET40'
                GROUP BY 1,3,4,5,6,7,8,9,10,11,12,13,14, bl_histo_permat, bl_histo_permat, bl_histo_annee, bl_histo_mois
            ;
			
			-- ISP (349) Application du plan de comptabilisation excel fourni pour avoir les comptes
			SELECT base.cti_execute('
				UPDATE w_hst_hp
				SET bl_histo_compte =
					CASE
						WHEN type_affectation ILIKE ''unique'' THEN compte_affectation[1]
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[2] THEN compte_affectation[2]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[3] THEN compte_affectation[3]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[4] THEN compte_affectation[4]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[5] THEN compte_affectation[5]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[6] THEN compte_affectation[6]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[7] THEN compte_affectation[7]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[8] THEN compte_affectation[8]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[9] THEN compte_affectation[9]  
						WHEN type_affectation ILIKE ''multiple'' AND ctrcatcomptable = categorie_comptable_affectation[10] THEN compte_affectation[10]
						ELSE compte_affectation[1] END
						FROM prod_eig.cti_plancpteig
						WHERE bl_histo_rub = rubrique
					   ',1)
			WHERE 'cti_plancpteig' IN (SELECT table_name FROM information_schema.tables)
			;

            -- Ajout des rubriques de maintien générées dynamiquement.
            INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
                SELECT w_hst_hp.bl_histo_rub, 'Maintien '::text||cru_rubrique__lib__, substr('Maintien '::text||cru_rubrique__lib__,1,50), rubid::int::text||'_MAINTIEN'::text, rubid::int
                FROM w_hst_hp
                    join prod_eig.sgrheig_rubriques on sgrheig_rubriques.cru_rubrique__code__||'_MAINTIEN'::text = w_hst_hp.bl_histo_rub
                WHERE rubid::int::text||'_MAINTIEN'::text NOT IN (SELECT code_original FROM rh.t_rubriques)
                GROUP BY 1,2,3,4,5
            ;

            CREATE INDEX i_hst_bul_v_matpers ON w_hst_hp USING btree(v_matpers);
            CREATE INDEX i_hst_bul_dates      ON w_hst_hp USING btree(date_paie);

            DROP TABLE IF EXISTS w_hst_bul
            ;

            CREATE TEMP TABLE w_hst_bul AS
                select
                    v_matpers,
                    cti_bul,
                    date_debut,
                    date_fin,
                    mois_paie,
                    date_paie,
                    bl_histo_etab,
                    bl_histo_ctrid,
                    max(case when bl_histo_rub = '_COEFBUL' then coeff else 0 end) as coeff,
                    sum(case when bl_histo_rub = ('51_MINCONV') then montant_sal else 0 end) > sum(case when bl_histo_rub IN ('SALBASE', '51_PAY_METIER') then montant_sal else 0 end) as prendre_minconv
                from w_hst_hp
                group by 1,2,3,4,5,6,7,8
            ;

            -- Suppression des rubriques 51_MAINTIEN de septembre 2017 à septembre 2018 inclu (suite à qualif. RH-Paie avec Mme SALMON).
            DELETE FROM w_hst_hp
            WHERE 1=1
                AND bl_histo_rub = '51_MAINTIEN'
                AND mois_paie between 201709 and 201809
            ;

            -- Suppression des rubriques SALBASE et 51_PAY_METIER lorsque le coefficient de la grille est <= 337 (suite à qualif. RH-Paie avec Mme SALMON).
            -- DROP TABLE IF EXISTS w_grille_eig
            -- ;

            -- CREATE TEMP TABLE w_grille_eig AS
            --         SELECT grialias, grilibelle, griid, 0::numeric as griparentid, gricoef -- Correction de la racine qui pointe sur elle-même et bloque la requête récursive qui suit.
            --         FROM prod_eig.sgrheig_grilles_convention
            --         where griid = 1
            --     union
            --         SELECT grialias, grilibelle, griid, griparentid, gricoef
            --         FROM prod_eig.sgrheig_grilles_convention
            --         where griid > 1
            -- ;

            -- DROP TABLE IF EXISTS w_grille_eig_coeff
            -- ;

            -- CREATE TEMP TABLE w_grille_eig_coeff AS
            --     with RECURSIVE search_graph as (
            --             SELECT grialias, grilibelle, griid, griparentid, gricoef
            --             FROM w_grille_eig
            --             where griid = 1
            --         UNION ALL
            --             SELECT o.grialias, o.grilibelle, o.griid, o.griparentid, coalesce(nullif(o.gricoef, 0), search_graph.gricoef) as gricoef -- si le coefficient n'est pas renseigné on prend celui du parent.
            --             FROM w_grille_eig as o
            --                 JOIN search_graph ON search_graph.griid = o.griparentid)
            --     select * from search_graph
            -- ;

            -- DELETE FROM w_hst_hp
            -- USING prod_eig.sgrheig_contrats, w_grille_eig_coeff
            -- WHERE 1=1
            --     AND sgrheig_contrats.ctrid = w_hst_hp.bl_histo_ctrid
            --     AND w_grille_eig_coeff.grialias::int = sgrheig_contrats.v_grialias::int
            --     AND bl_histo_rub IN ('SALBASE', '51_PAY_METIER')
            --     AND gricoef::int <= 337
            -- ;

            -- WITH w_grille_eig_coeff as (
            --     select cti_bul
            --     from w_hst_bul
            --     where coeff <= 328
            -- )
            -- DELETE FROM w_hst_hp
            -- USING w_grille_eig_coeff
            -- WHERE 1=1
            --     AND w_hst_hp.cti_bul = w_grille_eig_coeff.cti_bul
            --     AND bl_histo_rub IN ('SALBASE', '51_PAY_METIER')
            -- ;

            WITH w_minconv as (
                select cti_bul
                from w_hst_bul
                where prendre_minconv
            )
            DELETE FROM w_hst_hp
            USING w_minconv
            WHERE 1=1
                AND w_hst_hp.cti_bul = w_minconv.cti_bul
                AND bl_histo_rub IN ('SALBASE', '51_PAY_METIER')
            ;

            INSERT INTO rh.p_chiffrier_production(entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
                SELECT
                    entreprise_id,
                    t_etablissements.oid,
                    to_char(date_debut, 'YYYYMM')::numeric,
                    count(DISTINCT bl_histo_perid),
                    sum(CASE WHEN p_brut and p_cumul THEN (CASE s_brut
                            WHEN 0 THEN to_number(coalesce(nullif(trim(nombre::text), ''), '0'), '999999999999.9999')
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_brut),
                    sum(CASE WHEN p_heures_payees and p_cumul THEN (CASE s_heures_payees
                            WHEN 0 THEN to_number(coalesce(nullif(trim(nombre::text), ''), '0'), '999999999999.9999')
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_heures_payees)
                FROM w_hst_hp
                    JOIN prod_eig.sgrheig_contrats      ON true
                        AND sgrheig_contrats.v_matpers::int = w_hst_hp.v_matpers
                        AND sgrheig_contrats.ctrid          = w_hst_hp.bl_histo_ctrid
                    JOIN rh.t_etablissements            ON t_etablissements.code_original = w_hst_hp.bl_histo_etab
                    JOIN prod_eig.sgrheig_rubriques     ON sgrheig_rubriques.rubid::int::text = w_hst_hp.bl_histo_clerub
                    JOIN rh.t_rubriques                 ON t_rubriques.code_original = w_hst_hp.bl_histo_clerub
                WHERE 1=1
					AND trim(sgrheig_contrats.v_matpers) != ''
                    AND to_char(date_paie, 'YYYY')::int >= 2015
                    AND (p_cumul OR p_detail)
                GROUP BY 1,2,3
            ;

            -- Ajout de la ligne chiffrier (production) à 0 pour le mois en cours si besoin.
            INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
                SELECT
                    entreprise_id,
                    etablissement_id,
                    mois_paie_encours::numeric,
                    0,0,0
                FROM w_periode, rh.p_chiffrier_production
                WHERE mois_paie_encours NOT IN (SELECT mois FROM rh.p_chiffrier_production GROUP BY 1)
                GROUP BY 1,2,3
            ;

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

            -- Préparation contrats (pb chevauchement)
            DROP TABLE IF EXISTS w_hst_contrat
            ;

            CREATE TEMP TABLE w_hst_contrat AS
                with contrats as (
                    SELECT
                        v_matpers::int as mat,
                        ctrdebactivite::date as date_debut,
                        coalesce(ctrdaterupture, '2099-12-31'::date)::date as date_fin,
                        case when lead(ctrdebactivite) over w = ctrdebactivite then false else true end as to_keep,
                        (SELECT valeur FROM rh.t_divers WHERE code = 'EIG_SERVICE') AS cti_eig_services_param,
                        *
                    FROM prod_eig.sgrheig_contrats
                    where true
                        AND trim(v_matpers) not in ('5660', '6024', '') -- Suppression du matricule de simulation et des matricules vides
                        -- AND v_matpers::int = 1004
                    window w as (partition by v_matpers order by ctrdebactivite, ctrdaterupture))
                select
                    v_matpers::text||'-'::text||rank() OVER (PARTITION BY v_matpers ORDER BY ctrdebactivite) as cti_cnt,
                    CASE 
                        WHEN cti_eig_services_param = 0 THEN ctrservice::int::text
                        WHEN cti_eig_services_param = 1 THEN co_etssect::int::text
                        WHEN cti_eig_services_param = 2 THEN co_etssect::text || ' - ' || ctrservice::text
                    END AS ctrservice_ajuste,
                    *
                from contrats
                where to_keep
            ;

            CREATE INDEX i_hst_contrat_v_matpers ON w_hst_contrat USING btree(v_matpers);
            CREATE INDEX i_hst_contrat_dates      ON w_hst_contrat USING btree(date_debut, date_fin);

            -- Historique des affections au travers des bulletins.
            -- @TODO voir si autre affectations utiles
            
            -- Historique des bulletins 
        
            -- Identification des dates limites pour chaque salariés (pour des raisons de performances).
            -- Basé sur les contrats et les bulletins (historique des cumuls t_hcum).
            DROP TABLE IF EXISTS w_lim_sal
            ;

            CREATE TEMP TABLE w_lim_sal AS
                select
                    mat as v_matpers,
                    min(date_debut) as date_debut,
                    --coalesce(nullif(max(date_fin), '2099-12-31'::date), base.cti_last_day(current_date)) as date_fin
                    max(date_fin) as date_fin
                from (
                        select
                            mat,
                            min(w_hst_contrat.date_debut) as date_debut,
                            --max(date_fin) as date_fin
                            coalesce(nullif(max(w_hst_contrat.date_fin), '2099-12-31'::date), max(date_paie_encours)) as date_fin -- 2099-12-31 correspond à "contrat en cours" => on met le mois de paie en cours (et surtout pas current_date).
                        from w_hst_contrat, w_periode
                        group by 1
                    UNION ALL
                        select
                            v_matpers as mat,
                            min(date_debut) as date_debut,
                            max(greatest(date_fin, date_paie)) as date_fin
                        from w_hst_bul
                        group by 1
                    ) as subq
                    join prod_eig.sgrheig_personnes on sgrheig_personnes.permatricule::int = subq.mat
                        JOIN rh.t_etablissements ON peretab = t_etablissements.code_original
                group by 1
            ;

            CREATE INDEX i_lim_sal_v_matpers ON w_lim_sal USING btree(v_matpers);
            CREATE INDEX i_lim_sal_dates      ON w_lim_sal USING btree(date_debut, date_fin);

            DROP TABLE IF EXISTS w_evt_mois
            ;

            -- CREATE TEMP TABLE w_evt_mois AS
            --     select
            --         w_lim_sal.v_matpers,
            --         cti_cnt, -- contrat
            --         cti_bul, -- bulletin.
            --         p_calendrier.mois,
            --         min(p_calendrier.date) as date_debut,
            --         max(p_calendrier.date) as date_fin,
            --         (max(p_calendrier.date) - min(p_calendrier.date) + 1)::numeric / (base.cti_last_day(max(p_calendrier.date)) - base.cti_first_day(min(p_calendrier.date)) + 1)::numeric as ratio_temps
            --     from base.p_calendrier
            --         join w_lim_sal on p_calendrier.date between w_lim_sal.date_debut and w_lim_sal.date_fin
            --         left join w_hst_contrat on 1=1
            --             and w_hst_contrat.mat = w_lim_sal.v_matpers
            --             and p_calendrier.date between w_hst_contrat.date_debut and w_hst_contrat.date_fin
            --         left join w_hst_bul on 1=1
            --             and w_hst_bul.v_matpers = w_lim_sal.v_matpers
            --             and p_calendrier.date between w_hst_bul.date_debut and w_hst_bul.date_fin
            --     group by 1,2,3,4--5,,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38
            --     having 1!=1
            --         or cti_cnt is not null -- on ne conserve que les évenements ou il y a un contrat OU
            --         or cti_bul is not null -- un bulletin
            -- ;

            CREATE TEMP TABLE w_evt_mois AS
                with ValidDates as ( 
                        select v_matpers::int, date_debut::date as date from w_hst_contrat
                    union select v_matpers::int, date_fin::date as date from w_hst_contrat
                      union  select v_matpers, date_debut::date as date from w_hst_bul
                    union select v_matpers, date_fin::date as date from w_hst_bul
                    )
                , ValidDateRanges1 as ( 
                    select *, case when lead(date) over w = date + '1 day'::interval then false else true end as correct, 
                    (case when lead(date) over w = date + '1 day'::interval then null else (date + '1 day'::interval) end)::date as date_debut,
                    (case when lead(date) over w = date + '1 day'::interval then null else (lead(date) over w - '1 day'::interval) end)::date as date_fin
                    from ValidDates
                    window w as (partition by v_matpers order by Date)
                    )
                , ValidDateRanges as (
                    select v_matpers, date_debut as ValidFrom, date_fin as ValidTo from ValidDateRanges1 where correct
                    union 
                    select v_matpers, date, date from ValidDates 
                    )
                , detail as (
                    select
                        E.v_matpers,
                        OU.cti_cnt,
                        -- L.cti_bul,
                        null::text as cti_bul,
                        D.ValidFrom,
                        D.ValidTo,
                        e.date_fin as max_date
                    from w_lim_sal E 
                        join ValidDateRanges D on E.v_matpers::int=D.v_matpers::int and base.cti_overlaps(E.date_debut::date, E.date_fin::date, D.ValidFrom ,D.ValidTo )
                        left join w_hst_contrat OU on true
                            and OU.v_matpers::int=D.v_matpers
                            and base.cti_overlaps(OU.date_debut::date, OU.date_fin::date, D.ValidFrom ,D.ValidTo ) 
                        -- left join w_hst_bul L on true
                        --     and L.v_matpers=D.v_matpers
                        --     and base.cti_overlaps(L.date_debut::date, L.date_fin::date, D.ValidFrom ,D.ValidTo )
                        --     and L.bl_histo_ctrid = OU.ctrid
                    where false
                        or cti_cnt is not null
                        -- or cti_bul is not null
                    )
                    --,toto as (
                    select
                                    v_matpers,
                                    cti_cnt, -- contrat
                                    cti_cnt as cti_cnt_all,
                                    cti_bul, -- bulletin.
                                    mois,
                                    min(greatest(validfrom, date_debut)) as date_debut,
                                    max(least(validto, date_fin)) as date_fin,
                                   (max(least(validto, date_fin)) - min(greatest(validfrom, date_debut)) + 1)::numeric / (max(date_fin) - min(date_debut) + 1)::numeric as ratio_temps
                            from detail
                                    left join base.p_calendrier_mois on true
                                        and base.cti_overlaps(validfrom, validto, date_debut, date_fin)
                                        and date_fin <= max_date
                                    group by 1,2,3,4,5
               --     )
                -- select
                --     v_matpers,
                --     cti_cnt, -- contrat
                --     -- coalesce(cti_cnt, -- si la valeur est renseignée sur la ligne courante, on la prend.
                --     --     (max(case when cti_cnt is null then null else ARRAY[extract(epoch from date_debut)::text, cti_cnt] end) over wb)[2], -- sinon on prend la valeur renseignée la plus proche dans le passé
                --     --     (min(case when cti_cnt is null then null else ARRAY[extract(epoch from date_debut)::text, cti_cnt] end) over wf)[2], -- sinon on prend la valeur renseignée la plus proche dans le futur
                --     --     null -- sinon on prend null. Ne devrait pas arriver.
                --     -- )
                --     cti_cnt as cti_cnt_all,
                --     cti_bul, -- bulletin.
                --     -- coalesce(cti_bul, -- si la valeur est renseignée sur la ligne courante, on la prend.
                --     --     (max(case when cti_bul is null then null else ARRAY[extract(epoch from date_debut)::text, cti_bul] end) over wb)[2], -- sinon on prend la valeur renseignée la plus proche dans le passé
                --     --     (min(case when cti_bul is null then null else ARRAY[extract(epoch from date_debut)::text, cti_bul] end) over wf)[2], -- sinon on prend la valeur renseignée la plus proche dans le futur
                --     --     null -- sinon on prend null. Ne devrait pas arriver.
                --     -- ) as cti_bul_all,
                --     mois,
                --     date_debut,
                --     date_fin,
                --    ratio_temps
                -- from toto 
                -- window wb as (PARTITION BY v_matpers ORDER BY date_debut rows unbounded preceding), -- sélectionne les lignes précédentes
                --    wf as (PARTITION BY v_matpers ORDER BY date_debut rows between current row and unbounded following) -- sélectionne les lignes suivantes 
            ;

            -- WITH all_rsg as (
            --     SELECT
            --         t1.ctid,
            --         (max(array[t2.date_fin::text, t2.cti_cnt]))[2] as cti_cnt
            --     FROM w_evt_mois as t1
            --         LEFT JOIN w_evt_mois as t2 ON true
            --             AND t1.v_matpers = t2.v_matpers
            --             AND t2.date_fin < t1.date_debut
            --     -- WHERE cti_cnt IS NULL
            --     GROUP BY 1
            --     )
            -- UPDATE w_evt_mois SET
            --     cti_cnt_all = all_rsg.cti_cnt
            -- FROM all_rsg
            -- WHERE true
            --     AND w_evt_mois.ctid = all_rsg.ctid
            --     AND w_evt_mois.cti_cnt IS NULL
            -- ;

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

           
            DROP TABLE IF EXISTS w_profils
            ;

            CREATE TEMP TABLE w_profils AS
                select
                    w_evt_mois.ctid as row_id,
                    0 as profil_id,
                    0 as contrat_id,
                    0 as contrat_mois_id,
                    0 as salarie_id,
                    w_evt_mois.v_matpers,
                    w_evt_mois.mois,
                    w_evt_mois.date_debut,
                    w_evt_mois.date_fin,
                    -- **** contrat ****
                    w_hst_contrat.ctrid,
                    w_hst_contrat.cti_cnt,
                    cti_cnt_all, -- cti_cnt mais renseigné avec les valeurs précédentes ou suivantes lorsque hors période de contrat. Utile pour p_contrats_mois.
                    w_hst_contrat.date_debut as cnt_date_debut,
                    w_hst_contrat.date_fin as cnt_date_fin,
                    w_hst_contrat.ctrdateembauche as date_embauche,
                    coalesce(w_hst_contrat.ctretp, 0) * ratio_temps as cnt_ctretp,
                    ''::text as ets_cnt_all,
                    w_hst_bul.bl_histo_etab,
                    w_hst_contrat.ctrnumetab,
                    -- **** affectations ****
                    w_hst_contrat.ctrnumsect,
                    -- **** affectations bulletins ****
                    --w_hst_affbul.unite, -- utilisé plus tard UNIQUEMENT pour le modèle comptable.
                    --w_hst_affbul.categorie, -- utilisé plus tard UNIQUEMENT pour le modèle comptable.
                    -- **** bulletins ****
                    w_hst_bul.cti_bul,
                    w_hst_bul.bl_histo_ctrid,
                    w_hst_bul.date_debut as bul_date_debut,
                    w_hst_bul.date_fin as bul_date_fin,
                    --w_hst_bul.cumul_68,
                    --w_hst_bul.cumul_81,
                    case when w_hst_contrat.cti_cnt is null then 1 else 0 end as est_hors_periode,
                    case when dense_rank() over w = 1 then true else false end as est_profil_principal,
                    --coalesce(vhi_taux/vhi_base, 1) as vhi_ratio,
                    coalesce(ven_taux/ven_base, 1) as vhi_ratio,
                    -- **** code original ****
                    chr(1)||'*' AS cadre_emploi_code_original, -- public
                    chr(1)||'*' AS categorie_conge_code_original, -- public
                    coalesce(lower(w_hst_contrat.ctrmetier), chr(1)||'*') AS categorie_socio_professionnelle_code_original,
                    chr(1)||'*' AS categorie_statutaire_code_original, -- public
                    LTRIM(w_hst_contrat.li_code_item, '0') AS code_emploi_code_original,
                    chr(1)||'*' AS commission_paritaire_code_original, -- public
                    chr(1)||'*' AS compte_salarie_code_original, -- public
                    chr(1)||'*' AS filiere_code_original, -- public
                    w_hst_contrat.v_grialias AS grille_code_original,
                    coalesce(w_hst_contrat.ctrcatcomptable::int::text, chr(1)||'*') AS grille_groupe_code_original, -- Catégorie comptable EIG.
                    split_part(w_hst_contrat.ctridregime,'.',1) AS groupe_cotisant_code_original,
                    chr(1)||'*' AS lettre_budgetaire_code_original, -- public
                    coalesce(case
                        when w_hst_contrat.ctrtypecontrat::text = 'CDI' then 'CTI-EMB'
                        else w_hst_contrat.ctrmotifprecis::int::text end, chr(1)||'*') as motif_debut_code_original,
                    coalesce(w_hst_contrat.ctrtyperupture::int::text, chr(1)||'*') as motif_fin_code_original,
                    w_hst_contrat.v_grialias  AS qualification_code_original,
                    -- coalesce(vhi_etssect, chr(1)||'*') AS section_analytique_code_original,
                    coalesce(ve_etssect, chr(1)||'*') AS section_analytique_code_original,
                    chr(1)||'*' AS section_analytique_paie_code_original,
                    coalesce(w_hst_contrat.ctrservice_ajuste, chr(1)||'*') AS service_code_original,
                    chr(1)||'*' AS societe_interim_code_original,
                    coalesce(w_hst_contrat.ctrcatpers::int::text, chr(1)||'*') AS specialite_code_original,
                    coalesce(w_hst_contrat.ctrcatsp::int::text,  chr(1)||'*') AS statut_code_original,
                    coalesce(w_hst_contrat.ctrtypecontrat::text, chr(1)||'*') as type_contrat_code_original,
                    w_hst_contrat.ctrtypehoraire AS type_horaire_code_original,
                    case when w_hst_contrat.ctretp = 1 then 'TC' else 'TP'||(w_hst_contrat.ctretp * 100)::int::text end  AS type_temps_travail_code_original,
                    chr(1)||'*' AS unite_fonctionnelle_code_original -- public
                from w_evt_mois
                    left join w_hst_contrat on w_hst_contrat.cti_cnt = w_evt_mois.cti_cnt
                    --left join w_sal_ets on w_sal_ets.cti_ets = w_evt_mois.cti_ets
                    left join w_hst_bul on w_hst_bul.cti_bul = w_evt_mois.cti_bul
                    -- left join prod_eig.sgrheig_histo_ventilations on 1=1
                    --     and vhi_ctr = w_hst_contrat.ctrid
                    --     and (vhi_annee::text||lpad(vhi_mois, 2, '0'))::int = w_evt_mois.mois
                    left join (
                        SELECT 
                            ven_etab,
                            ven_libetab,
                            ven_sect,
                            ven_libsect,
                            ven_base,
                            ven_taux,
                            ven_ctr,
                            ve_etssect
                         FROM 
                            prod_eig.sgrheig_ventilations_cpt 
                        GROUP BY 1,2,3,4,5,6,7,8) sgrheig_ventilations_cpt on ven_ctr = w_hst_contrat.ctrid
                -- window w as (PARTITION BY vhi_ctr, vhi_annee, vhi_mois order by vhi_taux desc, vhi_etssect)
                window w as (PARTITION BY ven_ctr order by ven_taux desc, ve_etssect)
                -- window wb as (PARTITION BY w_evt_mois.v_matpers ORDER BY w_evt_mois.date_debut rows unbounded preceding), -- sélectionne les lignes précédentes
                --     wf as (PARTITION BY w_evt_mois.v_matpers ORDER BY w_evt_mois.date_debut rows between current row and unbounded following) -- sélectionne les lignes suivantes
            ;

			UPDATE w_profils
			SET
				section_analytique_paie_code_original = vhi_etssect
			FROM 
				(
					SELECT
						vhi_ctr,
						((vhi_annee::int)::text||lpad((vhi_mois::int), 2, '0'))::int AS vhi_mois,
						(MAX(ARRAY[vhi_taux::text || '-' || vhi_etssect,vhi_etssect::text]))[2] AS vhi_etssect
					FROM prod_eig.sgrheig_histo_ventilations
					GROUP BY 1,2
				) sub
			WHERE 1=1 AND
				vhi_ctr = ctrid AND
				vhi_mois = w_profils.mois
			;
			
            ]]></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,
                    sgrheig_personnes.pernom AS nom,
                    sgrheig_personnes.perprenom AS prenom,
                    coalesce(sgrheig_personnes.pernaisdate::date, '1900-01-01'::date) AS date_naissance,
                    CASE WHEN sgrheig_personnes.percivilite = 'Monsieur'
                        THEN 'M'
                        ELSE 'F'
                    END AS sexe,
                    lpad(w_profils.v_matpers, 6, '0') AS matricule,
                    lpad(w_profils.v_matpers, 6, '0') AS code,
                    w_profils.v_matpers AS code_original,
                    coalesce((max(distinct array[extract(epoch from w_profils.date_fin), t_etablissements.entreprise_id]))[2], 0) AS entreprise_id,
                    coalesce(t_nationalites.oid, 0) AS nationalite_id,
                    coalesce(t_codes_postaux.oid, 0) AS code_postal_id,
                    sgrheig_personnes.perfille AS nom_naissance,
                    coalesce(t_situations_famille.oid, 0) AS situation_famille_id,
                    (MAX(distinct array[w_profils.date_fin::text, profil_id::text]))[2]::bigint AS profil_id,
                    MAX(cnt_date_debut) AS date_debut, -- utilisé pour la partie "Dernier contrat" du détail salarié
                    MAX(cnt_date_fin) AS date_fin, -- utilisé pour la partie "Dernier contrat" du détail salarié
                    MIN(date_embauche) as date_entree_ets,
                    MAX(cnt_date_fin) 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,
                    permatretraite AS matricule_retraite,
                    sgrheig_personnes.peretab,
                    sgrheig_personnes.persecu AS nir
                FROM w_profils
                    JOIN prod_eig.sgrheig_personnes ON w_profils.v_matpers = sgrheig_personnes.permatricule
                    LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = sgrheig_personnes.percp
                    LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = peretab
                    LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = substr(persitfam,1,1)
                    LEFT JOIN rh.t_nationalites ON t_nationalites.code_original = percodepaysnais
                WHERE est_profil_principal
                GROUP BY 1,2,3,4,5,6,7,8,10,11,12,13,23,24,25
            ;

            ]]></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.v_matpers = p_salaries.code_original
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="MAJ établissement des salariés en fonction du paramétrage EIG_ETABLISSEMENT">
            <sqlcmd><![CDATA[

            UPDATE w_profils
            SET ets_cnt_all = subview.etablissement_code
            FROM (
                SELECT 
                    w_profils.row_id,
                    CASE
                        WHEN t_divers.valeur = '0' AND w_profils.bl_histo_etab IS NOT NULL THEN w_profils.bl_histo_etab -- Bulletin 
                        WHEN t_divers.valeur = '1' AND w_profils.ctrnumetab IS NOT NULL THEN w_profils.ctrnumetab -- Contrat
                        WHEN t_divers.valeur = '2' AND w_salaries.peretab IS NOT NULL THEN w_salaries.peretab -- Personne
                        ELSE COALESCE(w_profils.bl_histo_etab, w_profils.ctrnumetab, w_salaries.peretab)
                    END AS etablissement_code
                FROM w_profils
                JOIN w_salaries ON w_salaries.code_original = w_profils.v_matpers
                LEFT JOIN rh.t_divers ON t_divers.code = 'EIG_ETABLISSEMENT'  
            ) AS subview
            WHERE w_profils.row_id = subview.row_id
            ;

            ]]></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_profils.cnt_date_debut AS date_debut,
                    w_profils.cnt_date_fin AS date_fin,
                    w_profils.cti_cnt AS numero_contrat,
                    w_profils.ctrid AS code_original,
                    coalesce((max(distinct array[extract(epoch from w_profils.date_fin), t_etablissements.oid]))[2], 0)AS etablissement_id,
                    coalesce((max(distinct array[extract(epoch from w_profils.date_fin), w_profils.profil_id]))[2], 0) as profil_id
                FROM w_profils
                    JOIN rh.p_salaries ON p_salaries.code_original = w_profils.v_matpers
                    LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = w_profils.ets_cnt_all
                WHERE true
                    and cti_cnt is not null
                    and est_profil_principal
                GROUP BY 1,2,3,4,5
            ;

           -- Màj de l'ancienneté.
            UPDATE rh.p_contrats SET
                anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
                anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_calculee_mois
            FROM (
                select
                    numero_contrat,
                    coalesce(sum(date_fin - date_debut + 1) over w, 0) AS anciennete_anterieure_jours,
                    coalesce(sum(date_fin - date_debut + 1) over w / 30::numeric, 0) AS anciennete_anterieure_calculee_mois
                from rh.p_contrats
                window w as (partition by salarie_id order by date_debut rows between UNBOUNDED PRECEDING and 1 preceding)) AS subq
            WHERE 1=1
                AND p_contrats.numero_contrat = subq.numero_contrat
            ;

            SELECT base.cti_stash_table_indexes('rh.p_contrats_mois')
            ;

            TRUNCATE rh.p_contrats_mois
            ;

            ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
            ;

            DROP TABLE IF EXISTS w_contrats_mois
            ;

            CREATE TEMP TABLE w_contrats_mois AS
                SELECT
                    nextval('rh.s_contrats_mois'::regclass) as contrat_mois_id,
                    p_salaries.oid AS salarie_id,
                    p_contrats.oid AS contrat_id,
                    w_profils.mois 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 w_profils.cnt_date_debut BETWEEN w_profils.date_debut AND w_profils.date_fin THEN 1 ELSE 0 END AS nombre_debut_contrat,
                    CASE WHEN w_profils.cnt_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 base.cti_first_day(w_profils.date_debut) BETWEEN w_profils.cnt_date_debut AND w_profils.cnt_date_fin THEN 1 ELSE 0 END AS present_debut_mois,
                    CASE WHEN base.cti_last_day(w_profils.date_debut) BETWEEN w_profils.cnt_date_debut AND w_profils.cnt_date_fin THEN 1 ELSE 0 END AS present_fin_mois,
                    case when cti_cnt IS NOT NULL then cnt_ctretp end AS equivalent_temps_plein,
                    base.cti_age(least(w_profils.date_fin, w_profils.cnt_date_fin)::date, coalesce(p_salaries.date_naissance, '1962-04-18'::date), 'ny') AS age_id,
                    least(w_profils.date_fin, w_profils.cnt_date_fin)::date - coalesce(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
                    case when cti_cnt IS NOT NULL then 
                        p_contrats.anciennete_anterieure_jours
                        + (w_profils.date_fin - w_profils.cnt_date_debut)
                        + 1
                    else 0 end AS anciennete_jours,
                    case when cti_cnt IS NOT NULL then base.cti_age(date_trunc('month', w_profils.date_fin::date)::date, date_trunc('month', w_profils.cnt_date_debut)::date, 'nm')
                        + greatest(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) + 1 else 0 end AS anciennete_mois,
                    case when cti_cnt IS NOT NULL then floor((base.cti_age(date_trunc('month', w_profils.date_fin::date)::date, date_trunc('month', w_profils.cnt_date_debut)::date, 'nm')
                        + greatest(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) + 1) / 12) else 0 end AS anciennete_annee_id,
                    coalesce(t_etablissements.oid, p_contrats.etablissement_id, 0) as etablissement_id,
                    array_agg(w_profils.row_id) as array_row_id -- array des profils.
                FROM w_profils
                    JOIN rh.p_salaries ON w_profils.v_matpers = p_salaries.code_original
                    LEFT JOIN rh.p_contrats ON p_contrats.numero_contrat = w_profils.cti_cnt_all
                    LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = w_profils.ets_cnt_all
                WHERE true
                    AND est_profil_principal
                    AND (false -- Il faut au moins un contrat ou un bulletin.
                        OR cti_cnt IS NOT NULL
                        OR cti_bul IS NOT NULL)
                GROUP BY 2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
            ;

                -- On renseigne les id de contrats de w_profils.
            UPDATE w_profils
            SET contrat_id = subq.contrat_id,
                contrat_mois_id = subq.contrat_mois_id
            FROM (
                select
                    unnest(array_row_id) as row_id,
                    contrat_mois_id,
                    contrat_id
                from w_contrats_mois) as subq
            WHERE w_profils.row_id = subq.row_id
            ;

            INSERT INTO rh.p_contrats_mois(
                oid,
                salarie_id,
                contrat_id,
                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
                    contrat_mois_id,
                    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,
                    age_id,
                    age_jours,
                    anciennete_jours,
                    anciennete_mois,
                    anciennete_annee_id,
                    etablissement_id
                FROM w_contrats_mois
            ;

            SELECT base.cti_stash_pop_table_indexes('rh.p_contrats_mois')
            ;

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

            DROP TABLE IF EXISTS w_hp
            ;

            CREATE TEMP TABLE w_hp AS
                SELECT
                    w_hst_hp.v_matpers,
                    -- lpad(w_hst_hp.v_matpers,10,'0')||lpad(sgrheig_contrats.ctrid,5,'0') AS cti_cnt_id,
                    mois_paie as mois,
                    cti_bul,
                    min(date_debut)::date AS date_debut,
                    max(date_fin)::date AS date_fin,
                    -- max(cal_nperiode) AS cal_nperiode,
                    -- max(bul_datepaie) AS bul_datepaie, -- ne plus utiliser car il semblerait que ce soit la date de remise du bulletin de paie (et != de mois_paie).
                    --bl_histo_perid,
                    bl_histo_etab,
                    bl_histo_ctrid,
                    bl_histo_clerub,
                    mois_paie,
                    date_paie,
                    t_rubriques.oid as rubrique_id,
					COALESCE(t_compte.oid,0) as compte_id,
                    sum(CASE WHEN p_base THEN (CASE s_base
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_base) AS base,
                    sum(CASE WHEN p_nombre THEN (CASE s_nombre
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_nombre) AS nombre,
                    sum(CASE WHEN p_heures_contrat THEN (CASE s_heures_contrat
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_heures_contrat) AS heures_contrat,
					sum(CASE WHEN p_heures_payees THEN (CASE s_heures_payees
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_heures_payees) AS heures_payees,
                    sum(CASE WHEN p_heures_travaillees THEN (CASE s_heures_travaillees
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_heures_travaillees) AS heures_travaillees,
                    sum(CASE WHEN p_masse_salariale THEN (CASE s_masse_salariale
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN (montant_sal + montant_emp)
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_masse_salariale) AS montant_masse_salariale,
                    sum(CASE WHEN p_brut THEN (CASE s_brut
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_brut) AS montant_brut,
                    sum(CASE WHEN p_avantage_nature THEN (CASE s_avantage_nature
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_avantage_nature) AS montant_avantage_nature,
                    sum(CASE WHEN p_frais_imposables THEN (CASE s_frais_imposables
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_frais_imposables) AS montant_frais_imposables,
                    sum(taux_sal * coefficient_txs) AS taux_cotisation_salarie,
                    sum(CASE WHEN p_cotisation_salarie THEN (CASE s_cotisation_salarie
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_cotisation_salarie) AS montant_cotisation_salarie,
                    sum(taux_emp * coefficient_txp) AS taux_cotisation_patronale,
                    sum(CASE WHEN p_cotisation_patronale THEN (CASE s_cotisation_patronale
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_cotisation_patronale) AS montant_cotisation_patronale,
                    sum(CASE WHEN p_od_net_salarie THEN (CASE s_od_net_salarie
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_od_net_salarie) AS montant_od_net_salarie,
                    sum(CASE WHEN p_od_net_patronale THEN (CASE s_od_net_patronale
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_od_net_patronale) AS montant_od_net_patronale,
                    sum(CASE WHEN p_net_imposable THEN (CASE s_net_imposable
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_net_imposable) AS montant_net_imposable_salarie,
                    sum(CASE WHEN p_net_a_payer THEN (CASE s_net_a_payer
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_net_a_payer) AS montant_net_a_payer_salarie,
                    sum(CASE WHEN p_nombre_provisions THEN (CASE s_nombre_provisions
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_nombre_provisions) AS nombre_provisions,
                    sum(CASE WHEN p_montant_provisions THEN (CASE s_montant_provisions
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_montant_provisions) AS montant_provisions,
                    sum(CASE WHEN p_masse_salariale_provisionnee THEN (CASE s_masse_salariale_provisionnee
                            WHEN 0 THEN nombre
                            WHEN 1 THEN base
                            WHEN 2 THEN taux_sal
                            WHEN 3 THEN montant_sal
                            WHEN 4 THEN taux_emp
                            WHEN 5 THEN montant_emp
                            WHEN 6 THEN montant_sal + montant_emp
                            WHEN 7 THEN montant_sal - montant_emp
                            WHEN 8 THEN -montant_sal + montant_emp
                        END) ELSE 0 END * c_masse_salariale_provisionnee) AS montant_masse_salariale_provisionnee
                FROM w_hst_hp
                    JOIN rh.t_rubriques             ON t_rubriques.code_original = w_hst_hp.bl_histo_clerub
					LEFT JOIN rh.t_compte             ON t_compte.code_original = w_hst_hp.bl_histo_compte
                WHERE true
                    AND to_char(date_paie, 'YYYY')::int >= 2015
                    AND t_rubriques.p_detail
                GROUP BY 1,2,3, 6,7,8,9,10,11,12
            ;

            DROP TABLE IF EXISTS w_hp_1
            ;

            CREATE TEMP TABLE w_hp_1 AS
                SELECT
                    (max(ARRAY[extract(epoch from p_contrats.date_fin)::text, p_contrats.code_original]))[2] as cti_cnt_id,
                    cti_bul,
                    w_hp.date_debut,
                    w_hp.date_fin,
                    w_hp.mois_paie,
                    w_hp.date_paie,
                    p_salaries.oid as salarie_id,
                    (max(ARRAY[extract(epoch from p_contrats.date_fin), p_contrats.oid]))[2] as contrat_id,
                    (max(ARRAY[extract(epoch from p_contrats_mois.date_fin), p_contrats_mois.oid]))[2] as contrat_mois_id,
                    mois,
                    w_hp.rubrique_id,
					w_hp.compte_id,
                    0 as organisme_cotisation_id,
                    t_etablissements.oid as etablissement_id,
                    w_hp.base,
                    w_hp.nombre,
                    w_hp.heures_contrat,
					w_hp.heures_payees,
                    w_hp.heures_travaillees,
                    w_hp.montant_masse_salariale,
                    w_hp.montant_brut,
                    w_hp.montant_avantage_nature,
                    w_hp.montant_frais_imposables,
                    w_hp.taux_cotisation_salarie,
                    w_hp.montant_cotisation_salarie,
                    w_hp.taux_cotisation_patronale,
                    w_hp.montant_cotisation_patronale,
                    w_hp.montant_od_net_salarie,
                    w_hp.montant_od_net_patronale,
                    w_hp.montant_net_imposable_salarie,
                    w_hp.montant_net_a_payer_salarie,
                    w_hp.nombre_provisions,
					w_hp.montant_provisions,
					w_hp.montant_masse_salariale_provisionnee
                FROM w_hp
                    JOIN rh.p_salaries on p_salaries.code_original = w_hp.v_matpers
                    LEFT JOIN rh.p_contrats on p_contrats.code_original = w_hp.bl_histo_ctrid
                    LEFT JOIN rh.p_contrats_mois on 1=1
                        AND p_contrats_mois.contrat_id = p_contrats.oid
                        AND p_contrats_mois.mois_activite = w_hp.mois_paie
                    JOIN rh.t_etablissements on t_etablissements.code_original = w_hp.bl_histo_etab
                GROUP BY  2,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, w_hp.ctid
            ;

            -- Associer les bulletins hors contrat (is null) avec le contrat précédent.
            UPDATE w_hp_1
            SET contrat_id = subq.contrat_id,
                contrat_mois_id = subq.contrat_mois_id
            FROM (
                select
                    w_hp_1.ctid,
                    (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
                from w_hp_1
                    join rh.p_contrats_mois on true
                        and p_contrats_mois.salarie_id = w_hp_1.salarie_id
                        and p_contrats_mois.date_fin < w_hp_1.date_debut
                where contrat_mois_id is null
                group by 1) as subq
            WHERE true
                AND w_hp_1.ctid = subq.ctid
                AND w_hp_1.contrat_mois_id is null
            ;

            -- Associer les bulletins hors contrat (is null) avec le contrat suivant.
            UPDATE w_hp_1
            SET contrat_id = subq.contrat_id,
                contrat_mois_id = subq.contrat_mois_id
            FROM (
                select
                    w_hp_1.ctid,
                    (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
                from w_hp_1
                    join rh.p_contrats_mois on true
                        and p_contrats_mois.salarie_id = w_hp_1.salarie_id
                        and p_contrats_mois.date_fin > w_hp_1.date_debut
                where contrat_mois_id is null
                group by 1) as subq
            WHERE true
                AND w_hp_1.ctid = subq.ctid
                AND w_hp_1.contrat_mois_id is null
            ;

            TRUNCATE rh.p_historique_paie
            ;

            INSERT INTO rh.p_historique_paie(
                salarie_id,
                contrat_id,
                contrat_mois_id,
                mois_activite,
                date_debut,
                date_fin,
                mois_paie,
                date_paie,
                rubrique_id,
				compte_id,
                organisme_cotisation_id,
                etablissement_id,
                base,
                nombre,
                heure_contrat,
				heure_payee,
                heure_travaillee,
                montant_masse_salariale,
                montant_brut,
                montant_avantage_nature,
                montant_frais_imposables,
                taux_cotisation_salarie,
                montant_cotisation_salarie,
                taux_cotisation_patronale,
                montant_cotisation_patronale,
                montant_od_net_salarie,
                montant_od_net_patronale,
                montant_net_imposable_salarie,
                montant_net_a_payer_salarie,
                nombre_provisions,
                montant_provisions,
                montant_masse_salariale_provisionnee)
                SELECT
                    salarie_id,
                    contrat_id,
                    contrat_mois_id,
                    mois,
                    date_debut,
                    date_fin,
                    mois_paie,
                    date_paie, --bul_datepaie,
                    rubrique_id,
					compte_id,
                    organisme_cotisation_id,
                    etablissement_id,
                    base,
                    nombre,
                    heures_contrat,
					heures_payees,
                    heures_travaillees,
                    montant_masse_salariale,
                    montant_brut,
                    montant_avantage_nature,
                    montant_frais_imposables,
                    taux_cotisation_salarie,
                    montant_cotisation_salarie,
                    taux_cotisation_patronale,
                    montant_cotisation_patronale,
                    montant_od_net_salarie,
                    montant_od_net_patronale,
                    montant_net_imposable_salarie,
                    montant_net_a_payer_salarie,
                    nombre_provisions,
					montant_provisions,
					montant_masse_salariale_provisionnee
                FROM w_hp_1
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Calul de l'écart cumulé">
            <sqlcmd><![CDATA[

            -- 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
                    cti_bul,
                    w_hst_hp.v_matpers AS matricule,
                    w_hst_hp.date_paie AS date,
                    w_hst_hp.mois_paie AS mois,
                    sum(CASE WHEN p_cumul AND p_avantage_nature      THEN montant_sal * c_avantage_nature ELSE 0 END) AS hcum_avantage_nature,
                    sum(CASE WHEN p_cumul AND p_brut                 THEN montant_sal * c_brut ELSE 0 END) AS hcum_brut,
                    sum(CASE
                        WHEN p_cumul AND p_brut THEN montant_sal * c_brut
                        WHEN p_cumul AND p_cotisation_patronale THEN montant_sal * c_cotisation_patronale
                        ELSE 0 END) AS hcum_masse_salariale,
                    sum(CASE WHEN p_cumul AND p_cotisation_patronale THEN montant_sal * c_cotisation_patronale ELSE 0 END) AS hcum_cotisation_patronale,
                    sum(CASE WHEN p_cumul AND p_cotisation_salarie   THEN montant_sal * c_cotisation_salarie ELSE 0 END) AS hcum_cotisation_salarie,
                    0::numeric AS hcum_frais_imposables,
                    sum(CASE WHEN p_cumul AND p_net_a_payer          THEN montant_sal * c_net_a_payer ELSE 0 END) AS hcum_net_a_payer_salarie,
                    sum(CASE WHEN p_cumul AND p_net_imposable        THEN montant_sal * c_net_imposable ELSE 0 END) AS hcum_net_imposable_salarie,
					sum(CASE WHEN p_cumul AND p_heures_contrat       THEN montant_sal * c_heures_contrat ELSE 0 END) AS hcum_heures_contrat,
                    sum(CASE WHEN p_cumul AND p_heures_payees        THEN montant_sal * c_heures_payees ELSE 0 END) AS hcum_heures_payees,
                    sum(CASE WHEN p_cumul AND p_heures_travaillees   THEN montant_sal * c_heures_travaillees ELSE 0 END) AS hcum_heures_travaillees,
                    0::numeric AS hcum_montant_od_net_salarie,
                    sum(CASE WHEN p_nombre_provisions AND p_nombre_provisions   THEN montant_sal * c_nombre_provisions ELSE 0 END) AS hcum_nombre_provisions,
                    sum(CASE WHEN p_montant_provisions AND p_montant_provisions   THEN montant_sal * c_montant_provisions ELSE 0 END) AS hcum_montant_provisions,
                    sum(CASE WHEN p_cumul AND p_masse_salariale_provisionnee   THEN montant_sal * c_masse_salariale_provisionnee ELSE 0 END) AS hcum_masse_salariale_provisionnee
                FROM w_hst_hp
                    JOIN rh.t_rubriques ON t_rubriques.code_original = w_hst_hp.bl_histo_clerub
                WHERE true
                    AND to_char(date_paie, 'YYYY')::int >= 2015
                    -- AND p_cumul -- NE PAS LE METTRE ICI, ça enlève trop de ligne !!
                GROUP BY 1,2,3,4
            ;

            -- 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 (
                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,
                etablissement_id,
                rubrique_id,
                compte_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie,
                nombre_provisions,
                montant_provisions,
                montant_masse_salariale_provisionnee)
                SELECT
                    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,
                    COALESCE(hcum_heures_contrat,0) - subq.heure_contrat AS heure_contrat,
					COALESCE(hcum_heures_payees,0) - subq.heure_payee AS heure_payee,
                    COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee AS heure_travaillee,
                    COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature AS montant_avantage_nature,
                    COALESCE(hcum_brut,0) - subq.montant_brut AS montant_brut,
                    COALESCE(hcum_masse_salariale, 0) - subq.montant_masse_salariale AS montant_masse_salariale,
                    COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale AS montant_cotisation_patronale,
                    COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie AS montant_cotisation_salarie,
                    0 AS montant_frais_imposables,
                    COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie AS montant_net_a_payer_salarie,
                    COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie AS montant_net_imposable_salarie,
                    0 AS montant_od_net_salarie,
                    subq.organisme_cotisation_id AS organisme_cotisation_id,
                    subq.etablissement_id as etablissement_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,
                    COALESCE(hcum_nombre_provisions,0) - subq.nombre_provisions AS nombre_provisions,
                    COALESCE(hcum_montant_provisions,0) - subq.montant_provisions AS montant_provisions,
                    COALESCE(hcum_masse_salariale_provisionnee,0) - subq.montant_masse_salariale_provisionnee AS montant_masse_salariale_provisionnee
                FROM (
                    SELECT
                        cti_bul,
                        contrat_id,
                        contrat_mois_id,
                        date_debut,
                        date_fin,
                        date_paie as date_paie,
                        mois as mois_activite,
                        mois_paie as mois_paie,
                        0 AS base,
                        0 AS nombre,
                        sum(heures_contrat) AS heure_contrat,
						sum(heures_payees) AS heure_payee,
                        sum(heures_travaillees) 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,
                        organisme_cotisation_id,
                        etablissement_id,
                        (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                        salarie_id,
                        0 AS taux_cotisation_patronale,
                        0 AS taux_cotisation_salarie,
                        sum(nombre_provisions) AS nombre_provisions,
                        sum(montant_provisions) AS montant_provisions,
                        sum(montant_masse_salariale_provisionnee) AS montant_masse_salariale_provisionnee
                    FROM w_hp_1
                    GROUP BY 1,2,3,4,5,6,7,8,9,10, 22, 23,24,25,26) AS subq
                JOIN w_totaux ON w_totaux.cti_bul = subq.cti_bul
            WHERE 1!=1
                OR COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature != 0
                OR COALESCE(hcum_brut,0) - subq.montant_brut != 0
                OR COALESCE(hcum_masse_salariale,0) - subq.montant_masse_salariale != 0
                OR COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie != 0
                OR COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie != 0
                OR COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale != 0
                OR COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie != 0
				OR COALESCE(hcum_heures_contrat,0) - subq.heure_contrat != 0
                OR COALESCE(hcum_heures_payees,0) - subq.heure_payee != 0
                OR COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee != 0
                OR COALESCE(hcum_nombre_provisions,0) - subq.nombre_provisions != 0
                OR COALESCE(hcum_montant_provisions,0) - subq.montant_provisions != 0
                OR COALESCE(hcum_masse_salariale_provisionnee,0) - subq.montant_masse_salariale_provisionnee != 0
            ;

            ]]></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,
                    sum(vhi_ratio) AS ratio,
                    p_contrats_mois.mois_activite
                FROM rh.p_contrats_mois
                    JOIN w_profils ON w_profils.contrat_mois_id = p_contrats_mois.oid
                GROUP BY 1,2,3,5
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Arrêt">
            <sqlcmd><![CDATA[

            -- Création d'une table temporaire
            DROP TABLE IF EXISTS w_arrets
            ;

            CREATE TEMP TABLE w_arrets AS
                with exc_mar as (
                    SELECT trim(unnest(string_to_array(valeur, ','))) as code
                    FROM rh.t_divers
                    WHERE code = 'IMP_EXC_MAR')
                ,exc_mar_arr as (
                    select array_agg(code) as codes from exc_mar)
                ,arrets as (
                    select
                        abs.absid as uid,
                        to_char(abs.absdatestart, 'YYYYMM')::numeric AS mois_activite,
                        abs.absdatestart::date as date_debut,
                        abs.absdateend::date as date_fin,
                        (abs.absdateend::date + '1 day'::interval)::date as date_reprise,
                        abs.absdateend::date - abs.absdatestart::date + 1 as duree,
                        abs.absdureejrsvalo as nb_jours,
                        abs.absdureehrsvalo as nb_heures,
                        abs.absrubid::int::text as motif,
                        sgrheig_personnes.permatricule::int as matricule,
                        case when count(*) over w = 1 then true else false end as to_keep -- on conserve uniquement les arrêts n'ayant pas eu de régulation.
                    from prod_eig.sgrheig_absences as abs
                        join prod_eig.sgrheig_personnes on sgrheig_personnes.perid = abs.lkaperid
                        left join exc_mar_arr on abs.v_absrubalias ilike any (exc_mar_arr.codes)
                    where 1=1
                        and absmcgid = -1
                        and exc_mar_arr.codes is null
                    group by 1,2,3,4,5,6,7,8,9,10
                    window w as (partition by abs.absid))
                select
                    *
                from arrets
                where to_keep
            ;

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

            ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
            ;

            INSERT INTO rh.p_arrets_travail(
                salarie_id,
                contrat_id,
                mois_activite,
                date_debut,
                date_fin,
                date_reprise,
                motif_arret_id,
                precision_motif_arret_id,
                nb_jours,
                nb_heures
                )
                SELECT 
                    p_salaries.oid,
                    max(p_contrats.oid), -- on prend le max car il peut y avoir un changement de contrat pendant un arrêt.
                    w_arrets.mois_activite,
                    w_arrets.date_debut,
                    w_arrets.date_fin,
                    w_arrets.date_reprise,
                    coalesce(t_motifs_arret.oid, 0) AS motif_arret_id,
                    0 AS precision_motif_arret_id,
                    w_arrets.duree,
                    w_arrets.nb_heures
                FROM w_arrets
                    JOIN rh.p_salaries ON p_salaries.code_original = w_arrets.matricule
                    LEFT JOIN rh.t_motifs_arret ON t_motifs_arret.code_original = w_arrets.motif
                    JOIN rh.p_contrats ON 1=1
                        AND p_contrats.salarie_id = p_salaries.oid
                        AND base.cti_overlaps(w_arrets.date_debut, w_arrets.date_fin, p_contrats.date_debut, p_contrats.date_fin)
                GROUP BY 1,3,4,5,6,7,8,9,10
            ;

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

            INSERT INTO rh.p_arrets_travail_mois(
                arret_travail_id,
                salarie_id,
                contrat_id,
                contrat_mois_id,
                mois_activite,
                nb_debut_arret,
                nb_fin_arret,
                nb_reprise_apres_arret,
                date_debut,
                date_fin,
                nb_jours,
                nb_heures,
                nb_arret
                )
                SELECT
                    p_arrets_travail.oid AS arret_travail_id,
                    p_arrets_travail.salarie_id AS salarie_id,
                    p_arrets_travail.contrat_id AS contrat_id,
                    (max(DISTINCT ARRAY[p_contrats_mois.date_fin - p_contrats_mois.date_debut, p_contrats_mois.oid]))[2] AS contrat_mois_id, -- On ratache l'arrêt au contrat le plus long dans le mois lorsque plusieurs contrat sur la même période.
                    p_contrats_mois.mois_activite,
                    CASE WHEN p_arrets_travail.date_debut BETWEEN min(p_contrats_mois.date_debut) AND max(p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nombre_debut_arret,
                    CASE WHEN p_arrets_travail.date_fin BETWEEN min(p_contrats_mois.date_debut) AND max(p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nombre_fin_arret,
                    CASE WHEN p_arrets_travail.date_reprise BETWEEN min(p_contrats_mois.date_debut) AND max(p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nb_reprise_apres_arret,
                    min(GREATEST(p_contrats_mois.date_debut, p_arrets_travail.date_debut)) AS date_debut,
                    max(LEAST(p_contrats_mois.date_fin, p_arrets_travail.date_fin)) AS date_fin,
                    max(LEAST(p_contrats_mois.date_fin, p_arrets_travail.date_fin)::date) - min(GREATEST(p_contrats_mois.date_debut, p_arrets_travail.date_debut)::date) + 1 AS nb_jours,
                    nb_heures * base.cti_division(max(LEAST(p_contrats_mois.date_fin, p_arrets_travail.date_fin)::date) - min(GREATEST(p_contrats_mois.date_debut, p_arrets_travail.date_debut)::date) + 1, nb_jours) as nb_heures,
                    CASE WHEN base.cti_overlaps(p_arrets_travail.date_debut, p_arrets_travail.date_fin, p_contrats_mois.date_debut, p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nb_arret
                FROM rh.p_contrats_mois
                    JOIN rh.p_arrets_travail ON 1=1
                        AND p_contrats_mois.contrat_id = p_arrets_travail.contrat_id
                        AND base.cti_overlaps(p_arrets_travail.date_debut, p_arrets_travail.date_reprise, p_contrats_mois.date_debut, p_contrats_mois.date_fin)
                GROUP BY 1,2,3,5, p_arrets_travail.date_debut, p_arrets_travail.date_fin, p_arrets_travail.date_reprise, nb_heures, nb_jours, 13
                ORDER BY 9
            ;

            -- Suppression des nb_reprise_apres_arret lorsqu'un arrêt suit un autre arrêt.
            update rh.p_arrets_travail_mois
            set nb_reprise_apres_arret = 0
            from (
                select 
                    t1.arret_travail_id,
                    t1.mois_activite
                from rh.p_arrets_travail_mois as t1
                    join rh.p_arrets_travail ON p_arrets_travail.oid = t1.arret_travail_id
                    left join rh.p_arrets_travail_mois as t2 ON 1=1
                        AND t1.salarie_id = t2.salarie_id
                        AND t1.arret_travail_id != t2.arret_travail_id
                WHERE t1.nb_reprise_apres_arret = 1
                GROUP BY 1,2
                HAVING min(case when p_arrets_travail.date_reprise between t2.date_debut and t2.date_fin then 0 else 1 end) = 0
                ) as subq
            where 1=1
                and p_arrets_travail_mois.arret_travail_id = subq.arret_travail_id
                and p_arrets_travail_mois.mois_activite = subq.mois_activite
            ;

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

            DROP TABLE IF EXISTS w_visites_medicales
            ;

            CREATE TEMP TABLE w_visites_medicales AS
                SELECT 
                    permatricule::int AS matricule,
                    perdatevisitemed::date AS date,
                    to_char(perdatevisitemed, 'YYYYMM')::numeric AS mois_activite,
                    p_contrats_mois.oid AS contrat_mois_id,
                    p_contrats_mois.contrat_id,
                    p_salaries.oid AS salarie_id,
                    0 AS motif_visite_id
                FROM prod_eig.sgrheig_personnes
                JOIN rh.p_salaries ON p_salaries.code_original = permatricule::int 
                JOIN rh.p_contrats_mois ON p_contrats_mois.salarie_id = p_salaries.oid AND perdatevisitemed BETWEEN p_contrats_mois.date_debut AND p_contrats_mois.date_fin
            ;

            INSERT INTO rh.p_visites_medicales(
                contrat_id,
                contrat_mois_id,
                date,
                mois_activite,
                motif_visite_id,
                salarie_id
                )
                SELECT
                    contrat_id,
                    contrat_mois_id,
                    date,
                    mois_activite,
                    motif_visite_id,
                    salarie_id
                FROM w_visites_medicales
            ;

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