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

			-- Màj des codes postaux
			INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id,
				departement_code, departement_texte)
				SELECT
					pysalarie.per_cp,
					max(pysalarie.per_ville), -- Attention : il peut y avoir plusieurs libellés (per_ville) pour un même CP (per_cp).
					max(pysalarie.per_ville),
					coalesce(t_departements.oid,0),
					coalesce(t_departements.code,''),
					coalesce(t_departements.texte,'')
				FROM prod_cegi.pysalarie
					LEFT JOIN base.t_departements ON t_departements.code = substr(pysalarie.per_cp, 1,2)
					LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = pysalarie.per_cp
				WHERE
					pysalarie.per_cp is not null
					AND t_codes_postaux.oid is null
				GROUP BY 1,  4,5,6
			;

			INSERT INTO rh.t_codes_postaux(oid, code, texte, texte_court, longitude, latitude, departement_id,
				departement_code, departement_texte)
				SELECT
					t_codes_postaux.oid,
					t_codes_postaux.code,
					t_codes_postaux.texte,
					t_codes_postaux.texte_court,
					t_codes_postaux.longitude,
					t_codes_postaux.latitude,
					t_codes_postaux.departement_id,
					t_codes_postaux.departement_code,
					t_codes_postaux.departement_texte
				FROM base.t_codes_postaux
					LEFT JOIN rh.t_codes_postaux t_codes_postaux_rh ON t_codes_postaux_rh.oid = t_codes_postaux.oid
				WHERE t_codes_postaux_rh.oid IS NULL
			;

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

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

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

			INSERT INTO rh.t_departements(code, texte, texte_court)
				SELECT rhdept_code, rhdept_nom, substr(rhdept_nom,1,50)
				FROM prod_cegi.rhdept
				WHERE rhdept_code NOT IN (SELECT code FROM rh.t_departements)
			;

			-- Màj des Entreprises
			INSERT INTO rh.t_entreprises(code, texte, texte_court, code_original)
				SELECT ent_siren, ent_raison, substr(ent_raison,1,50), ent_siren
				FROM prod_cegi.pyetablissement
                    JOIN prod_cegi.pyentreprise ON pyentreprise.ent_id = pyetablissement.ent_id
                    -- JOIN prod_cegi.cmetablissement ON cmetablissement.etab_id = pyetablissement.etab_id
				WHERE 1=1
                    AND ent_siren NOT IN (SELECT code_original FROM rh.t_entreprises)
                    AND (false
                        OR pyentreprise.ent_siren IN (SELECT rhp_in('siren')) -- Soit un ou plusieurs SIREN ont été défini,
                        OR pyetablissement.etab_siret IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs SIRET,
                        OR pyetablissement.etab_code IN (SELECT rhp_in('siren'))) -- et/ou soit un ou plusieurs codes établissement.
			;

			-- Màj des Etablissements
			INSERT INTO rh.t_etablissements(code, texte, texte_court, code_original, entreprise_id)
				SELECT pyetablissement.etab_code, pyetablissement.etab_lib, substr(pyetablissement.etab_lib,1,50), pyetablissement.eta_id, t_entreprises.oid
				FROM prod_cegi.pyetablissement
					JOIN prod_cegi.pyentreprise ON pyentreprise.ent_id = pyetablissement.ent_id
					-- JOIN prod_cegi.cmetablissement ON cmetablissement.etab_id = pyetablissement.etab_id
					JOIN rh.t_entreprises ON t_entreprises.code = pyentreprise.ent_siren
				WHERE 1=1
                    AND pyetablissement.eta_id NOT IN (SELECT code_original FROM rh.t_etablissements)
                    AND (false
                        OR pyentreprise.ent_siren IN (SELECT rhp_in('siren')) -- Soit un ou plusieurs SIREN ont été défini,
                        OR pyetablissement.etab_siret IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs SIRET,
                        OR pyetablissement.etab_code IN (SELECT rhp_in('siren'))) -- et/ou soit un ou plusieurs codes établissement.
			;

            DROP TABLE IF EXISTS w_ets
            ;

            CREATE TEMP TABLE w_ets AS
                SELECT
                    pyentreprise.ent_id,
                    pyetablissement.eta_id,
                    pyentreprise.ent_siren,
                    pyentreprise.ent_raison,
                    entreprise_id,
                    t_etablissements.oid as etablissement_id
                FROM prod_cegi.pyentreprise
                    JOIN prod_cegi.pyetablissement ON pyetablissement.ent_id = pyentreprise.ent_id
                    -- JOIN prod_cegi.cmetablissement ON cmetablissement.etab_id = pyetablissement.etab_id
                    JOIN rh.t_etablissements ON t_etablissements.code_original = pyetablissement.eta_id
                    JOIN rh.t_entreprises ON t_entreprises.oid = t_etablissements.entreprise_id
                WHERE 1!=1
                    OR pyentreprise.ent_siren IN (SELECT rhp_in('siren')) -- Soit un ou plusieurs SIREN ont été défini,
                    OR pyetablissement.etab_siret IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs SIRET,
                    OR pyetablissement.etab_code IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs codes établissement.
            ;

			-- Màj des catégories socio-professionnelles
			INSERT INTO rh.t_categories_socio_professionnelle
						(code, texte, texte_court, code_original)
				SELECT lower(pcs_code_2003), max(qcv_libelle), substr(max(qcv_libelle),1,50), lower(pcs_code_2003)
				FROM prod_cegi.pyqualconv
				WHERE
					lower(pcs_code_2003) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
					AND pcs_code_2003 IS DISTINCT FROM NULL
					AND trim(pcs_code_2003) <> ''
				GROUP BY 1,4
			;
			/*
			INSERT INTO rh.t_categories_socio_professionnelle
						(code, texte, texte_court, code_original)
				SELECT pcs_code, pcs_libelle, substr(pcs_libelle,1,50), pcs_code
				FROM prod_cegi.pypcs
				WHERE pcs_code NOT IN (SELECT code FROM rh.t_categories_socio_professionnelle)
			;
			*/

			-- Màj des groupes cotisants.
			INSERT INTO rh.t_groupes_cotisant(code, texte, texte_court, code_original)
				SELECT typcot_code, typcot_libelle, substr(typcot_libelle,1,50), typcot_code
				FROM prod_cegi.pytypecotisant
				WHERE typcot_code NOT IN (SELECT code_original FROM rh.t_groupes_cotisant)
			;

			-- Màj des motifs de début de contrat
			INSERT INTO rh.t_motifs_debut_contrat(code, texte, texte_court, code_original)
				SELECT mitemb_code, mtemb_libelle, substr(mtemb_libelle,1,50), mitemb_code
				FROM prod_cegi.pymtembauche
				WHERE mitemb_code NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
			;

			-- Màj des motifs de fin de contrat
			INSERT INTO rh.t_motifs_fin_contrat(code, texte, texte_court, code_original)
                    SELECT mtfcnt_code, mtfcnt_libelle, substr(mtfcnt_libelle,1,50), mtfcnt_code
                    FROM prod_cegi.pymtfcnt
                    WHERE mtfcnt_code NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
                UNION ALL
                    SELECT 'EC', 'Contrat en cours', 'Contrat en cours', 'CTI_EC'
                    WHERE 'CTI_EC' NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
			;

			-- Màj des nationalités
			INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
				SELECT nat_code, max(nat_nationalite), max(substr(nat_nationalite,1,50)), nat_code
				FROM prod_cegi.pynationalite
				WHERE nat_code NOT IN (SELECT code_original FROM rh.t_nationalites)
				GROUP BY 1,4
			;

			-- Màj des organismes de cotisation
			INSERT INTO rh.t_organismes_cotisation(code, texte, texte_court, code_original)
				SELECT org_code, org_nom, substr(org_nom_court,1,50), org_code
				FROM prod_cegi.pyorganisme
				WHERE org_code NOT IN (SELECT code_original FROM rh.t_organismes_cotisation)
			;

			-- Màj des qualifications
			DROP TABLE IF EXISTS w_qualifications;
			CREATE TEMP TABLE w_qualifications AS
				SELECT qcv_code AS code, max(qcv_libelle) AS texte, substr(max(qcv_libelle),1,50) AS texte_court, qcv_code AS code_original
				FROM prod_cegi.pyqualconv
				WHERE true
				and (select valeur = 'QUALCONV' FROM rh.t_divers WHERE code = 'CEGI_QUALIFICATION')
				GROUP BY qcv_code
			UNION ALL
				SELECT max(qual_code) AS code, max(qual_libelle) AS texte, substr(max(qual_libelle), 1, 50) AS texte_court, qual_id::text AS code_original
				FROM prod_cegi.pyqualification
				WHERE true
				and (select valeur = 'QUALIFICATION' FROM rh.t_divers WHERE code = 'CEGI_QUALIFICATION')
				GROUP BY qual_id
			;
   
			INSERT INTO rh.t_qualifications(code, texte, texte_court, code_original)
				SELECT code, texte, texte_court, code_original
				FROM w_qualifications
				WHERE true
				and w_qualifications.code_original NOT IN (SELECT t_qualifications.code_original FROM rh.t_qualifications)
			;

			UPDATE rh.t_qualifications SET
				code = w_qualifications.code,
				texte = w_qualifications.texte,
				texte_court = w_qualifications.texte_court
				FROM w_qualifications
				where true
				AND (select valeur = '1' FROM rh.t_divers WHERE code = 'OPT_IMP_QUALIF') AND
				t_qualifications.code_original = w_qualifications.code_original AND
				(
				t_qualifications.code IS DISTINCT FROM w_qualifications.code OR
				t_qualifications.texte IS DISTINCT FROM w_qualifications.texte OR
				t_qualifications.texte_court IS DISTINCT FROM w_qualifications.texte_court

				)
			;

			-- Màj des rubriques
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT lpad(rub_id,5,'0'), rub_libelle, substr(rub_libelle,1,50), rub_id, rub_id
				FROM prod_cegi.pyrubrique
				WHERE rub_id NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			-- Rubrique C000 est créée dans le SHARE.

			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
				SELECT
					upper(substr(valpossible,1,3))||lpad(length(valpossible), 3, '0'),
					valpossible,
					substr(valpossible,1,50),
					upper(substr(valpossible,1,3))||lpad(length(valpossible), 3, '0')
				FROM prod_cegi.pypossible_valeurs
				WHERE
					upper(substr(valpossible,1,3))||lpad(length(valpossible), 3, '0')
						NOT IN (SELECT code_original FROM rh.t_situations_famille)
					AND att_code = 'SITUA'
				GROUP BY 1,2,3,4
			;

			-- Màj des types de contrat
			INSERT INTO rh.t_types_contrat(code, texte, texte_court, code_original)
				SELECT typcnt_code, typcnt_libelle, substr(typcnt_libelle,1,50), typcnt_code
				FROM prod_cegi.PYTYPECONTRAT
				WHERE typcnt_code NOT IN (SELECT code_original FROM rh.t_types_contrat)
			;

			-- Màj des statuts
			INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
                    SELECT rhcatsoc_code, rhcatsoc_code, rhcatsoc_libelle, substr(rhcatsoc_libelle, 1, 50)
                    FROM prod_cegi.rhcatsoc
                    WHERE 1=1
                        and rhcatsoc_code NOT IN (SELECT code_original FROM rh.t_statuts)
                        and (select valeur = 'CATSOC' from rh.t_divers where code = 'CEGI_STATUT')
                    GROUP BY 1,2,3,4
                UNION ALL
                    SELECT gri_code, gri_code, gri_libelle, substr(gri_libelle::text, 1, 50)
                    FROM prod_cegi.pygrilleind
                    WHERE 1=1
                        AND gri_code NOT IN (SELECT code_original FROM rh.t_statuts)
                        and (select valeur = 'GRILLE' from rh.t_divers where code = 'CEGI_STATUT')
                    GROUP BY 1,2,3,4
			;

			-- Màj des types de temps de travail
            INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
                select
                    replace(cst_cnt_valeur, ',', '.'),
                    case when replace(cst_cnt_valeur, ',', '.') = '151.67' then 'TC' else 'TP'||round(replace(cst_cnt_valeur, ',', '.')::numeric/151.67*100, 2) end,
                    case when replace(cst_cnt_valeur, ',', '.') = '151.67' then 'Temps Complet' else 'Temps Partiel '||round(replace(cst_cnt_valeur, ',', '.')::numeric/151.67*100, 2)||'%' end,
                    case when replace(cst_cnt_valeur, ',', '.') = '151.67' then 'TC' else 'TP '||round(replace(cst_cnt_valeur, ',', '.')::numeric/151.67*100, 2)||'%' end
                from prod_cegi.pycst_cnt
                    JOIN prod_cegi.pyconstante on pyconstante.cst_id = pycst_cnt.cst_id
                WHERE true
                    AND cst_code = (select valeur from rh.t_divers where code = 'CEGI_CODE_TTT')
                    AND replace(cst_cnt_valeur, ',', '.') NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
                group by 1,2,3,4
            ;

            -- Màj de la clase de type de temps de travail automatiquement.
            DELETE FROM rh.t_classes_sections_elements
            USING rh.t_classes, rh.t_classes_sections
            WHERE 1=1
                AND t_classes_sections_elements.section_id = t_classes_sections.oid
                AND t_classes_sections.classe_id = t_classes.oid
                AND t_classes.code = 'CTI_TTT'
            ;

            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_types_temps_travail.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join rh.t_types_temps_travail on substr(t_types_temps_travail.code, 1, 2) = t_classes_sections.code
                WHERE t_classes.code = 'CTI_TTT'
            ;

			-- Màj des services
			INSERT INTO rh.t_services(code_original, code, texte, texte_court)
				SELECT svc_code, svc_code, max(svc_court), max(svc_court)
				FROM prod_cegi.PYSERVICE
				WHERE svc_code NOT IN (SELECT code_original FROM rh.t_services)
				GROUP BY 1,2
			;

			-- Màj des spécialités
            INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
                SELECT qcv_code AS code_original, qcv_code AS code, max(qcv_libelle) AS texte, substr(max(qcv_libelle),1,50) AS texte_court
				FROM prod_cegi.pyqualconv
                WHERE qcv_code NOT IN (SELECT code_original FROM rh.t_specialites)
                GROUP BY 1,2
            ;

			-- Màj des codes emploi
           with w_cem AS (
                    SELECT modcnt_code as code_original, modcnt_code as code, max(modcnt_libelle) as texte, max(substr(modcnt_libelle,1,50)) AS texte_court
                    FROM prod_cegi.PYMODELCNT
                    WHERE true
                        AND (select valeur = 'MODCNT' FROM rh.t_divers WHERE code = 'CEGI_CODE_EMPLOI')
                    GROUP BY 1,2
                UNION ALL
                    SELECT qual_id::text AS code_original, max(qual_code) AS code, max(qual_libelle) AS texte, substr(max(qual_libelle), 1, 50) AS texte_court
                    FROM prod_cegi.pyqualification
                    WHERE true
                        and (select valeur = 'QUALIFICATION' FROM rh.t_divers WHERE code = 'CEGI_CODE_EMPLOI')
                    GROUP BY qual_id
			    )
			INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
				SELECT code_original, code, texte, texte_court
				FROM w_cem
				WHERE code_original NOT IN (SELECT code_original FROM rh.t_codes_emploi)
			;

			-- Màj des types d'horaire

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

			-- Màj des grilles
			INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
                    SELECT ech_coefficient::text, ech_coefficient::text, ech_coefficient::text, substr(ech_coefficient::text, 1, 50)
                    FROM prod_cegi.pyvalechelon
                    WHERE 1=1
                        AND ech_coefficient NOT IN (SELECT code_original FROM rh.t_grilles)
                        AND ech_coefficient != 0
                        and (select valeur = 'ECHELON' from rh.t_divers where code = 'CEGI_GRILLE')
                    GROUP BY 1,2,3,4
                UNION ALL
                    SELECT gri_code, gri_code, gri_libelle, substr(gri_libelle::text, 1, 50)
                    FROM prod_cegi.pygrilleind
                    WHERE 1=1
                        AND gri_code NOT IN (SELECT code_original FROM rh.t_grilles)
                        and (select valeur = 'GRILLE' from rh.t_divers where code = 'CEGI_GRILLE')
                    GROUP BY 1,2,3,4
			;

			-- Màj des groupes de grilles
			INSERT INTO rh.t_grilles_groupes(code_original, code, texte, texte_court)
                SELECT rpad(gri_code, 5, '0')||ech_ordre, rpad(gri_code, 5, '0')||ech_ordre, ech_ordre::text||' : '||ech_echelon::text, substr(ech_ordre::text||' : '||ech_echelon::text,1,50)
                FROM prod_cegi.pyechelon
                    JOIN prod_cegi.pygrilleind ON pygrilleind.gri_id = pyechelon.gri_id
                WHERE rpad(gri_code, 5, '0')||ech_ordre NOT IN (SELECT code_original FROM rh.t_grilles_groupes)
			;

			-- Màj des motifs d'arret
			INSERT INTO rh.t_motifs_arret(code_original, code, texte, texte_court)
				SELECT abspar_code, abspar_code, max(abspar_libelle), substr(max(abspar_libelle),1,50)
				FROM prod_cegi.absenceparam
				WHERE abspar_code NOT IN (SELECT code_original FROM rh.t_motifs_arret)
				GROUP BY 1,2
			;

			-- Màj des sections analytiques compta
			INSERT INTO rh.t_sections_analytiques(code_original, code, texte, texte_court)
				SELECT vent_id, vent_code, vent_libelle, substr(vent_libelle,1,50)
				FROM prod_cegi.pyventilation
				WHERE vent_id NOT IN (SELECT code_original FROM rh.t_sections_analytiques)
			;

			-- Màj des sections analytiques paie
			INSERT INTO rh.t_sections_analytiques_paie(code_original, code, texte, texte_court)
				SELECT ana_id, ana_codana, ana_lib, substr(ana_lib,1,50)
				FROM prod_cegi.rhp_cmcodesana
				WHERE ana_id NOT IN (SELECT code_original FROM rh.t_sections_analytiques_paie)
			;

			-- Màj des "Comptes"
			INSERT INTO rh.t_compte(code_original, code, texte, texte_court)
				SELECT plc_compte, plc_compte, plc_libelle, substr(plc_libelle, 1, 50)
                FROM prod_cegi.rhp_cmplancpt
                WHERE plc_compte NOT IN (SELECT code_original FROM rh.t_compte)
			;

			]]></sqlcmd>
		</NODE>
	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
        <NODE label="Paramétrage des rubriques">
            <sqlcmd><![CDATA[

            -- Assiette des rubriques.
            DROP TABLE IF EXISTS w_ass_brut
            ;
            CREATE TEMP TABLE w_ass_brut AS
                SELECT rub_id AS rub
                FROM prod_cegi.pyrubrique
                WHERE true
                    AND rub_id BETWEEN 1050 AND 9979
                    AND rub_id NOT IN (2295,2300,2501,2502,5000,5047,5820,5822,5828,5830,5832,6900,6911,8630,8632,8633,8634,8731,8970,8980,8981,9050,9051,9052,9053,9060,9100,9161,9165,9280,9295,9500,9640,9945)
            ;

            DROP TABLE IF EXISTS w_ass_avtnat
            ;
            CREATE TEMP TABLE w_ass_avtnat AS
                SELECT rub_id AS rub
                FROM prod_cegi.pyrubrique
                WHERE rub_id BETWEEN 8500 AND 8528
            ;

            DROP TABLE IF EXISTS w_ass_cots
            ;
            CREATE TEMP TABLE w_ass_cots AS
                SELECT rub_id AS rub
                FROM prod_cegi.pyrubrique
                WHERE true
                    AND (false
                        OR rub_id BETWEEN 20000 AND 69999
                        OR rub_id BETWEEN 71000 AND 73989)
                    AND rub_id NOT IN (71100,73343,73345,73347)
            ;

            DROP TABLE IF EXISTS w_ass_cotp
            ;
            CREATE TEMP TABLE w_ass_cotp AS
                SELECT rub_id AS rub
                FROM prod_cegi.pyrubrique
                WHERE true
                    AND rub_id BETWEEN 20000 AND 73989
                    AND rub_id NOT IN (20010,73360,73450)
            ;

             DROP TABLE IF EXISTS w_ass_odn
            ;
            CREATE TEMP TABLE w_ass_odn AS
                SELECT rub_id AS rub
                FROM prod_cegi.pyrubrique
                WHERE true
                    AND (false
                        OR rub_id BETWEEN 77000 AND 86700
                        OR rub_id BETWEEN 86800 AND 87000)
                    AND rub_id != 77100
            ;

            -- Pré-paramétrage automatique des rubriques (au mieux).
            -- Cette requête n'intervient pas sur les rubriques paramétrées à la main.

            -- s_* (source_) :
            --   - 0 = nombre
            --   - 1 = base
            --   - 2 = taux salarial
            --   - 3 = montant salarial
            --   - 4 = taux patronal
            --   - 5 = montant patronal
            --   - 6 = montant salarial + montant patronal

            -- Rubriques de détail :
            update rh.t_rubriques
            set
                p_detail = subqq.p_detail,
                p_nombre = subqq.p_nombre,
                s_nombre = 0,
                c_nombre = 1,
                p_base = subqq.p_base,
                s_base = 1,
                c_base = 1,
                p_heures_payees = subqq.p_heures_payees,
                s_heures_payees = 0,
                c_heures_payees = 1,
                p_heures_travaillees = subqq.p_heures_travaillees,
                s_heures_travaillees = 0,
                c_heures_travaillees = 1,
                p_masse_salariale = subqq.p_masse_salariale,
                s_masse_salariale = case when subqq.p_cotisation_patronale or subqq.p_od_net_patronale then 5 else 3 end,
                c_masse_salariale = 1,
                p_brut = subqq.p_brut,
                s_brut = 3,
                c_brut = 1,
                p_avantage_nature = subqq.p_avantage_nature,
                s_avantage_nature = 3,
                c_avantage_nature = 1,
                p_frais_imposables = subqq.p_frais_imposables,
                s_frais_imposables = 3,
                c_frais_imposables = 1,
                p_cotisation_salarie = subqq.p_cotisation_salarie,
                s_cotisation_salarie = 3,
                c_cotisation_salarie = 1,
                p_cotisation_patronale = subqq.p_cotisation_patronale,
                s_cotisation_patronale = 5,
                c_cotisation_patronale = 1,
                p_od_net_salarie = subqq.p_od_net_salarie,
                s_od_net_salarie = 3,
                c_od_net_salarie = 1,
                p_od_net_patronale = subqq.p_od_net_patronale,
                s_od_net_patronale = 5,
                c_od_net_patronale = 1,
                p_net_imposable = subqq.p_net_imposable,
                s_net_imposable = 3,
                c_net_imposable = 1,
                p_net_a_payer = subqq.p_net_a_payer,
                s_net_a_payer = 3,
                c_net_a_payer = 1
            from (
                select
                    rub_id,
                    true AS p_detail,
                    bool_or(brut) AS p_nombre, -- Pas de nombre dans Cegi.
                    bool_or(brut) or bool_or(odns) or bool_or(odnp) or bool_or(cosd) or bool_or(copa) AS p_base,
                    false AS p_heures_payees,
                    false AS p_heures_travaillees,
                    bool_or(brut) or bool_or(odnp) or bool_or(copa) AS p_masse_salariale,
                    bool_or(brut) AS p_brut,
                    bool_or(avtn) AS p_avantage_nature,
                    bool_or(fimp) AS p_frais_imposables,
                    bool_or(cosd) AS p_cotisation_salarie,
                    bool_or(copa) AS p_cotisation_patronale,
                    bool_or(odns) AS p_od_net_salarie,
                    bool_or(odnp) AS p_od_net_patronale,
                    bool_or(brut) or bool_or(cosd) AS p_net_imposable,
                    bool_or(brut) or bool_or(cosd) or bool_or(odns) AS p_net_a_payer
                from (
                    select
                        rub_id,
                        w_ass_brut.rub IS NOT NULL as brut,
                        w_ass_odn.rub IS NOT NULL as odns,
                        false as odnp, -- Pas d'OD net patronale dans Cegi.
                        false as fimp, -- Pas de frais imposables.
                        w_ass_avtnat.rub IS NOT NULL as avtn,
                        w_ass_cots.rub IS NOT NULL as cosd,
                        w_ass_cotp.rub IS NOT NULL as copa
                    from prod_cegi.pyrubrique
                        LEFT JOIN w_ass_brut    ON w_ass_brut.rub   = pyrubrique.rub_id
                        LEFT JOIN w_ass_avtnat  ON w_ass_avtnat.rub = pyrubrique.rub_id
                        LEFT JOIN w_ass_cots    ON w_ass_cots.rub   = pyrubrique.rub_id
                        LEFT JOIN w_ass_cotp    ON w_ass_cotp.rub   = pyrubrique.rub_id
                        LEFT JOIN w_ass_odn     ON w_ass_odn.rub    = pyrubrique.rub_id
                    WHERE false
                        OR w_ass_brut.rub IS NOT NULL
                        OR w_ass_odn.rub IS NOT NULL
                        OR w_ass_avtnat.rub IS NOT NULL
                        OR w_ass_cots.rub IS NOT NULL
                        OR w_ass_cotp.rub IS NOT NULL) as subq
                group by 1) as subqq
            where 1=1
                AND t_rubriques.code_original = subqq.rub_id
                AND NOT t_rubriques.user_modified
            ;

            -- Rubriques de cumul :
            UPDATE rh.t_rubriques SET
                p_cumul = true
            where 1=1
                AND t_rubriques.code_original IN (10000, 10001, 74000, 75000, 90000) -- Uniquement les rubriques de cumul connues,
                AND t_rubriques.code_original != 'C000' -- pas la C000
                AND NOT t_rubriques.user_modified -- et non modifiées manuellement.
            ;

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

			TRUNCATE rh.p_chiffrier_production
			;

			INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
				SELECT
					w_ets.entreprise_id,
					w_ets.etablissement_id,
					(cal_an::int::text||lpad(cal_nperiode, 2, '0'))::numeric,
					count(DISTINCT pybulletin.per_id),
					sum(CASE WHEN p_brut and p_cumul THEN (CASE s_brut
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN lbu_montants + lbu_montantp
                            WHEN 7 THEN lbu_montants - lbu_montantp
                            WHEN 8 THEN -lbu_montants + lbu_montantp
                        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(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN lbu_montants + lbu_montantp
                            WHEN 7 THEN lbu_montants - lbu_montantp
                            WHEN 8 THEN -lbu_montants + lbu_montantp
                        END) ELSE 0 END * c_heures_payees)
				FROM prod_cegi.pybulletin
					JOIN prod_cegi.pylignebulletin ON pylignebulletin.bul_id = pybulletin.bul_id
					JOIN prod_cegi.pycontrat ON 1=1
						AND pybulletin.per_id = pycontrat.per_id
						AND pybulletin.cnt_id = pycontrat.cnt_id
					JOIN w_ets ON w_ets.eta_id = pycontrat.eta_id
                    JOIN rh.t_rubriques ON t_rubriques.code_original = pylignebulletin.rub_id
				WHERE 1=1
                    AND cal_an::int >= 2016
                    AND (p_cumul OR p_detail)
				GROUP BY 1,2,3
			;

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

			-- Création d'une table de contrats avec dates traitées.
			DROP TABLE IF EXISTS w_pycontrat
			;

			CREATE TEMP TABLE w_pycontrat AS
				SELECT
					cnt_datedeb::date AS date_debut,
					coalesce(cnt_datefin::date, '20991231'::date) AS date_fin,
                    pycontrat.eta_id::text||'-'||pysalarie.sal_matricule::text||'-'||pycontrat.cnt_id::text AS numero_contrat,
                    pycontrat.eta_id::text||'|'||pysalarie.sal_matricule::text||'|'||pycontrat.cnt_id::text AS code_original,
					pycontrat.*
				FROM prod_cegi.pycontrat
                    JOIN prod_cegi.pysalarie ON pysalarie.per_id = pycontrat.per_id
                    JOIN w_ets ON w_ets.eta_id = pycontrat.eta_id
				WHERE 1=1
                    -- AND pycontrat.per_id||'-'||pycontrat.cnt_id IN (SELECT per_id||'-'||cnt_id FROM prod_cegi.pybulletin GROUP BY 1) -- On conserve UNIQUEMENT les contrats ayant servi à produire une bulletin...
					-- AND pycontrat.per_id IN (SELECT per_id FROM prod_cegi.pybulletin GROUP BY 1) -- Alors qu'avant on prenait un contrat si son salarié avait eu au moins une paie.
					AND pycontrat.per_id > 0
			;

			CREATE INDEX w_pycontrat_1 ON w_pycontrat USING btree (per_id)
			;
			CREATE INDEX w_pycontrat_2 ON w_pycontrat USING btree (cnt_id)
			;
			CREATE INDEX w_pycontrat_3 ON w_pycontrat USING btree (date_debut)
			;
			CREATE INDEX w_pycontrat_4 ON w_pycontrat USING btree (date_fin)
			;

			-- Création d'une table de bulletins avec dates traitées.
			DROP TABLE IF EXISTS w_pybulletin
			;

			CREATE TEMP TABLE w_pybulletin AS
				SELECT
                    case when to_char(bul_debutrem, 'YYYYMM')::int = (cal_an::int::text||lpad(cal_nperiode, 2, '0'))::int
                        then bul_debutrem::date
                        else base.cti_last_day((cal_an::int::text||lpad(cal_nperiode, 2, '0')||'01')::date)
					end AS date_debut,
                    case when to_char(bul_debutrem, 'YYYYMM')::int = (cal_an::int::text||lpad(cal_nperiode, 2, '0'))::int
                        then coalesce(bul_finrem::date, '20991231'::date)
                        else base.cti_last_day((cal_an::int::text||lpad(cal_nperiode, 2, '0')||'01')::date)
                    end AS date_fin,
                    (cal_an::int::text||lpad(cal_nperiode, 2, '0'))::int as mois_paie,
                    w_pycontrat.eta_id,
					pybulletin.*
				FROM prod_cegi.pybulletin
                    JOIN w_pycontrat ON 1=1
                        and w_pycontrat.per_id = pybulletin.per_id
                        and w_pycontrat.cnt_id = pybulletin.cnt_id
				WHERE 1=1
                    and pybulletin.per_id > 0
                    -- and pybulletin.bul_apayer = 1
			;

			CREATE INDEX w_pybulletin_1 ON w_pybulletin USING btree (per_id)
			;
			CREATE INDEX w_pybulletin_2 ON w_pybulletin USING btree (bul_id)
			;
			CREATE INDEX w_pybulletin_3 ON w_pybulletin USING btree (date_debut)
			;
			CREATE INDEX w_pybulletin_4 ON w_pybulletin USING btree (date_fin)
			;

			-- Création d'une table d'échelons avec dates traitées.
			DROP TABLE IF EXISTS w_pyech_cnt
			;

			CREATE TEMP TABLE w_pyech_cnt AS
                with w_temp as (
                    select
                        ech_id,
                        per_id,
                        cnt_id,
                        cnt_ech_deb::date as date_debut
                    from prod_cegi.pyech_cnt
                    group by 1,2,3,4
                    )
                select
                    ech_id,
                    per_id,
                    cnt_id,
                    date_debut,
                    coalesce(lead(date_debut) over (partition by per_id, cnt_id order by date_debut) - 1, '20991231'::date) as date_fin
                from w_temp
			;

			CREATE INDEX w_pyech_cnt_1 ON w_pyech_cnt USING btree (per_id)
			;
			CREATE INDEX w_pyech_cnt_2 ON w_pyech_cnt USING btree (ech_id)
			;
			CREATE INDEX w_pyech_cnt_3 ON w_pyech_cnt USING btree (date_debut)
			;
			CREATE INDEX w_pyech_cnt_4 ON w_pyech_cnt USING btree (date_fin)
			;
            CREATE INDEX w_pyech_cnt_5 ON w_pyech_cnt USING btree (cnt_id)
            ;

            DROP TABLE IF EXISTS w_pyvalechelon
            ;

            CREATE TEMP TABLE w_pyvalechelon AS
                select
                    ech_id,
                    ech_coefficient,
                    ech_deb::date as date_debut,
                    coalesce(lead(ech_deb::date) over (partition by ech_id order by ech_deb) - 1, '20991231'::date) as date_fin
                from prod_cegi.pyvalechelon
            ;
            CREATE INDEX w_pyvalechelon_1 ON w_pyvalechelon USING btree (ech_id)
            ;
            CREATE INDEX w_pyvalechelon_2 ON w_pyvalechelon USING btree (date_debut)
            ;
            CREATE INDEX w_pyvalechelon_3 ON w_pyvalechelon USING btree (date_fin)
            ;

            -- Création d'une table de types de temps de travail.
            DROP TABLE IF EXISTS w_ttt
            ;

            CREATE TEMP TABLE w_ttt AS
                select
                    pycst_cnt.per_id,
                    pycst_cnt.cnt_id,
                    replace(cst_cnt_valeur, ',', '.') as ttt_code_original,
                    replace(cst_cnt_valeur, ',', '.')::numeric as heures_theoriques, -- heures théoriques de la constante Cegi AAAAC.
                    cst_cnt_deb::date as ttt_cnt_deb,
                    row_number() OVER w as ttt_id,
                    cst_cnt_deb::date AS date_debut,
                    coalesce(lead(cst_cnt_deb::date) over w - 1, '20991231'::date) as date_fin
                from prod_cegi.pycst_cnt
                    JOIN prod_cegi.pyconstante on pyconstante.cst_id = pycst_cnt.cst_id
                WHERE 1=1
                    AND cst_code = (select valeur from rh.t_divers where code = 'CEGI_CODE_TTT') -- Par défaut 'AAAAC', 'AARM' pour M. LGF.
                    AND trim(cst_cnt_valeur) != ''
                WINDOW w as (partition by pycst_cnt.per_id, pycst_cnt.cnt_id order by cst_cnt_deb)
            ;

            CREATE INDEX w_ttt_1 ON w_ttt USING btree (per_id)
            ;
            CREATE INDEX w_ttt_2 ON w_ttt USING btree (cnt_id)
            ;
            CREATE INDEX w_ttt_3 ON w_ttt USING btree (ttt_code_original)
            ;
            CREATE INDEX w_ttt_4 ON w_ttt USING btree (date_debut)
            ;
            CREATE INDEX w_ttt_5 ON w_ttt USING btree (date_fin)
            ;

            -- Création d'une table des qualifications conventionelles.
            DROP TABLE IF EXISTS w_qualconv
            ;

            CREATE TEMP TABLE w_qualconv AS
                    select
                        per_id,
                        cnt_id,
                        cnt_qcv_effet::date as date_debut,
                        lag(cnt_qcv_effet::date - 1, -1, '2099-12-31'::date) over w as date_fin,
                        qcv_code,
                        pcs_code_2003
                    from prod_cegi.pyqconv_cnt
                        JOIN prod_cegi.pyqualconv ON pyqualconv.qcv_id = pyqconv_cnt.qcv_id
                    window w as (partition by per_id, cnt_id order by cnt_qcv_effet)
            ;

            CREATE INDEX w_quaconv_1 ON w_qualconv USING btree (per_id)
            ;
            CREATE INDEX w_quaconv_2 ON w_qualconv USING btree (cnt_id)
            ;
            CREATE INDEX w_quaconv_3 ON w_qualconv USING btree (qcv_code)
            ;

            -- Création d'une table des qualifications.
            DROP TABLE IF EXISTS w_qualification
            ;

            CREATE TEMP TABLE w_qualification AS
                    select
                        per_id,
                        cnt_id,
                        cnt_qual_effet::date as date_debut,
                        lag(cnt_qual_effet::date - 1, -1, '2099-12-31'::date) over w as date_fin,
                        qual_id::text
                    from prod_cegi.pyqual_cnt
                    window w as (partition by per_id, cnt_id order by cnt_qual_effet)
            ;

            CREATE INDEX w_qualification_1 ON w_qualification USING btree (per_id)
            ;
            CREATE INDEX w_qualification_2 ON w_qualification USING btree (cnt_id)
            ;
            CREATE INDEX w_qualification_3 ON w_qualification USING btree (qual_id)
            ;

            -- Création d'une table des ventilations analytiques.
            DROP TABLE IF EXISTS w_ana
            ;

            CREATE TEMP TABLE w_ana AS
                with pyperioderep as (
                    select
                        per_id,
                        cnt_id,
                        prep_id,
                        prep_debut::date as date_debut,
                        coalesce(lead(prep_debut) over (partition by per_id, cnt_id order by prep_debut) - '1 day'::interval, '2099-12-31'::date)::date as date_fin
                    from prod_cegi.pyperioderep)
                , pyrepcnt_compta as (
                    select
                        vent_id,
                        rep_id,
                        ana_id,
                        sum(repcompta_taux) as repcompta_taux
                    from prod_cegi.pyrepcnt_compta
                    group by 1,2,3)
                , ana as (
                    select
                        pyperioderep.per_id,
                        pyperioderep.cnt_id,
                        pyperioderep.date_debut,
                        pyperioderep.date_fin,
                        pyrepcnt_compta.ana_id,
                        pyrepcnt_compta.vent_id,
                        -- #correction des taux qui ne font pas 100%...
                        coalesce(base.cti_division(coalesce(repana_taux, repcompta_taux, 1)::numeric , sum(coalesce(repana_taux, repcompta_taux, 1)) over (partition by pyperioderep.per_id, pyperioderep.cnt_id, pyperioderep.date_debut, pyrepartition.rep_id)::numeric), 1) * (pyrepartition.rep_taux / 100.0) as ratio
                    from pyperioderep
                        LEFT JOIN prod_cegi.pyrepartition ON 1=1
                            and pyrepartition.prep_id = pyperioderep.prep_id
                            and pyrepartition.rep_taux > 0
                        LEFT JOIN prod_cegi.pyrepcnt_ana ON pyrepcnt_ana.rep_id = pyrepartition.rep_id
                        LEFT JOIN pyrepcnt_compta ON pyrepcnt_compta.rep_id = pyrepartition.rep_id)
                select
                    per_id,
                    cnt_id,
                    date_debut,
                    date_fin,
                    ana_id,
                    vent_id,
                    sum(ratio) as ratio
                from ana
                GROUP BY 1,2,3,4,5,6
            ;

            CREATE INDEX w_ana_1 ON w_ana USING btree (per_id)
            ;
            CREATE INDEX w_ana_2 ON w_ana USING btree (cnt_id)
            ;
            CREATE INDEX w_ana_3 ON w_ana USING btree (ana_id)
            ;
            CREATE INDEX w_ana_4 ON w_ana USING btree (vent_id)
            ;

            DROP TABLE IF EXISTS w_rhcatscnt
            ;

            CREATE TEMP TABLE w_rhcatscnt AS
                select
                    rhcatsoc_code,
                    per_id,
                    cnt_id,
                    rhcatscnt_datdeb::date as date_debut,
                    coalesce(lead(rhcatscnt_datdeb::date) over (partition by per_id, cnt_id order by rhcatscnt_datdeb) - 1, '20991231'::date) as date_fin
                from prod_cegi.rhcatscnt
                    join prod_cegi.rhcatsoc on rhcatsoc.rhcatsoc_id = rhcatscnt.rhcatsoc_id
            ;
            CREATE INDEX w_rhcatscnt_1 ON w_rhcatscnt USING btree (per_id)
            ;
            CREATE INDEX w_rhcatscnt_2 ON w_rhcatscnt USING btree (date_debut)
            ;
            CREATE INDEX w_rhcatscnt_3 ON w_rhcatscnt USING btree (date_fin)
            ;
            CREATE INDEX w_rhcatscnt_4 ON w_rhcatscnt USING btree (cnt_id)
            ;

			-- Etape 0 : identifier les salariés qui ont eu au moins 1 bulletin ET 1 contrat.

			-- Etape 1 : se créer une ventilation "maître" des événements salariés basée sur les contrats et/ou les bulletins.
			--           Elle doit identifier les bulletins hors période de contrat (est_hors_periode).
			--           Elle doit aussi être corrigée (les bulletins sans contrat doivent être associés d'abord au contrat le plus en amont et à défaut en aval s'il y en a)

			-- Etape 2 : Cette ventilation maître servira à rattacher les autres dimensions.

			-- Ventilation journalière ? mensuelle ?
			-- Comment fait-on quand changement de dimension en cours de route (sans changement de contrat/bulletin)
			-- => la ventilation "maître" ne sert à rien dans ce cas alors ... => SI : à cadrer les historiques des autres dimensions.


			-- Etape 0 : création d'une table de salariés ayant eu au moins une paie ET un contrat.
			DROP TABLE IF EXISTS w_sal_paye
			;

			CREATE TEMP TABLE w_sal_paye AS
				SELECT
					pysalarie.per_id,
					pysalarie.sal_matricule,
                    min(greatest('2015-01-01'::date, least(w_pycontrat.date_debut, w_pybulletin.date_debut))) AS min_date, -- FIXME Optimiser la requete car on part de 2015 pour l'instant...
					max(least(base.cti_last_day(current_date), greatest(w_pycontrat.date_fin, w_pybulletin.date_fin, w_pybulletin.bul_datepaie::date))) AS max_date
				FROM prod_cegi.pysalarie
					LEFT JOIN w_pycontrat ON w_pycontrat.per_id = pysalarie.per_id
					LEFT JOIN w_pybulletin ON w_pybulletin.per_id = pysalarie.per_id
				WHERE pysalarie.per_id > 0
				GROUP BY 1, 2, w_pycontrat.per_id, w_pybulletin.per_id
				HAVING 1!=1
					OR w_pycontrat.per_id IS NOT NULL
					OR w_pybulletin.per_id IS NOT NULL
			;

			CREATE INDEX w_sal_paye_1 ON w_sal_paye USING btree (per_id)
			;

			-- Etape 1
			DROP TABLE IF EXISTS w_tmp_1
			;

			CREATE TEMP TABLE w_tmp_1 AS
                with raw as (
                       select
                            w_sal_paye.sal_matricule,
                            w_sal_paye.per_id,
                            cnt_id,
                            false as est_hors_periode,
                            eta_id,
                            p_calendrier.date,
                            p_calendrier.mois
                        FROM base.p_calendrier
                            join w_sal_paye ON date BETWEEN w_sal_paye.min_date AND w_sal_paye.max_date
                            JOIN w_pycontrat ON 1=1
                                AND w_pycontrat.per_id = w_sal_paye.per_id
                                AND date BETWEEN w_pycontrat.date_debut AND w_pycontrat.date_fin
                        -- where w_sal_paye.per_id = 11868
                        group by 1,2,3,4,5,6,7
                    union all
                        select
                                w_sal_paye.sal_matricule,
                                w_sal_paye.per_id,
                                cnt_id as cnt_id,
                                true as est_hors_periode,
                                eta_id,
                                p_calendrier.date,
                                p_calendrier.mois
                            FROM base.p_calendrier
                                join w_sal_paye ON date BETWEEN w_sal_paye.min_date AND w_sal_paye.max_date
                                JOIN w_pybulletin ON 1=1
                                    AND w_pybulletin.per_id = w_sal_paye.per_id
                                    AND date BETWEEN w_pybulletin.date_debut AND w_pybulletin.date_fin
                            -- where w_sal_paye.per_id = 11868
                            group by 1,2,3,4,5,6)
                    , trame_cnt as (
                        select
                            sal_matricule,
                            per_id,
                            cnt_id,
                            bool_and(est_hors_periode) as est_hors_periode,
                            max(eta_id) as eta_id,
                            date,
                            mois
                            from raw
                         group by 1,2,3, 6,7)
                select
                    trame_cnt.date,
                    trame_cnt.mois,
                    trame_cnt.sal_matricule,
                    trame_cnt.per_id,
                    trame_cnt.eta_id,
                    trame_cnt.est_hors_periode,
                    trame_cnt.cnt_id,
                    -- trame_cnt.cnt_id_all,
                    w_pybulletin.bul_id,
                    w_pyech_cnt.ech_id,
                    w_rhcatscnt.rhcatsoc_code,
                    coalesce(w_ttt.ttt_code_original, '151.67'::text) as ttt_code_original, -- Par défaut temps complet.
                    coalesce(w_ttt.heures_theoriques, 151.67) as heures_theoriques -- Par défaut temps complet.
                FROM trame_cnt
                    -- LEFT JOIN w_pycontrat ON 1=1
                    --  AND w_pycontrat.per_id = trame_cnt.per_id
                    --  AND date BETWEEN w_pycontrat.date_debut AND w_pycontrat.date_fin
                    LEFT JOIN w_pybulletin ON 1=1
                        AND w_pybulletin.per_id = trame_cnt.per_id
                        AND w_pybulletin.cnt_id = trame_cnt.cnt_id -- rajout du lien technique Cegi obligatoire pour ne plus avoir de pdt cartésien lorsque multi-contrats.
                        AND date BETWEEN w_pybulletin.date_debut AND w_pybulletin.date_fin
                    LEFT JOIN w_pyech_cnt ON 1=1
                        AND w_pyech_cnt.per_id = trame_cnt.per_id
                        AND w_pyech_cnt.cnt_id = trame_cnt.cnt_id -- rajout du lien technique Cegi obligatoire pour ne plus avoir de pdt cartésien lorsque multi-contrats.
                        AND date BETWEEN w_pyech_cnt.date_debut AND w_pyech_cnt.date_fin
                    LEFT JOIN w_ttt on 1=1
                        AND w_ttt.per_id = trame_cnt.per_id
                        AND w_ttt.cnt_id = trame_cnt.cnt_id -- rajout du lien technique Cegi obligatoire pour ne plus avoir de pdt cartésien lorsque multi-contrats.
                        AND date BETWEEN w_ttt.date_debut AND w_ttt.date_fin
                    LEFT JOIN w_rhcatscnt on 1=1
                        AND w_rhcatscnt.per_id = trame_cnt.per_id
                        AND w_rhcatscnt.cnt_id = trame_cnt.cnt_id -- rajout du lien technique Cegi obligatoire pour ne plus avoir de pdt cartésien lorsque multi-contrats.
                        AND date BETWEEN w_rhcatscnt.date_debut AND w_rhcatscnt.date_fin
			;

			DROP TABLE IF EXISTS w_profils
			;

			CREATE TEMP TABLE w_profils AS
				SELECT
					coalesce(case when mitemb_code = 'TC' then 'CDI' else typcnt_code end,chr(1)||'*') 									AS type_contrat_code_original,
					chr(1)||'*' 														AS type_horaire_code_original,
					coalesce(mitemb_code,chr(1)||'*') 									AS motif_debut_code_original,
					coalesce(mtfcnt_code, case when pycontrat.date_fin = '20991231' then 'CTI_EC' else mtfcnt_code end, chr(1)||'*') AS motif_fin_code_original,
					coalesce(CASE WHEN (select valeur = 'QUALIFICATION' FROM rh.t_divers WHERE code = 'CEGI_QUALIFICATION') THEN w_qualification.qual_id ELSE w_qualconv.qcv_code END, chr(1)||'*') AS qualification_code_original,
					coalesce(pyservice.svc_code,chr(1)||'*') 							AS service_code_original,
					coalesce(w_qualconv.qcv_code, chr(1)||'*') 							AS specialite_code_original,
					coalesce(ttt_code_original, chr(1)||'*')                            AS type_temps_travail_code_original,
					coalesce(lower(w_qualconv.pcs_code_2003),chr(1)||'*') 				AS categorie_socio_professionnelle_code_original,
					coalesce(CASE WHEN (select valeur = 'GRILLE' FROM rh.t_divers WHERE code = 'CEGI_STATUT') THEN gri_code ELSE w_tmp_1.rhcatsoc_code END, chr(1)||'*') AS statut_code_original,
					coalesce(CASE WHEN (select valeur = 'QUALIFICATION' FROM rh.t_divers WHERE code = 'CEGI_CODE_EMPLOI') THEN w_qualification.qual_id ELSE pymodelcnt.modcnt_code END, chr(1)||'*') AS code_emploi_code_original,
					chr(1)||'*' 														AS societe_interim_code_original,
					coalesce(w_ana.ana_id::text,chr(1)||'*')						    AS section_analytique_paie_code_original,
					coalesce(w_ana.vent_id::text,chr(1)||'*') 				            AS section_analytique_code_original,
                    coalesce(rpad(gri_code, 5, '0')||ech_ordre, chr(1)||'*')            AS grille_groupe_code_original,
                    coalesce(case when (select valeur = 'GRILLE' from rh.t_divers where code = 'CEGI_GRILLE') then gri_code else ech_coefficient::text end, chr(1)||'*') AS grille_code_original,
					coalesce(pytypecotisant.typcot_code,chr(1)||'*') 					AS groupe_cotisant_code_original,
					chr(1)||'*' 														AS cadre_emploi_code_original,
					chr(1)||'*' 														AS categorie_conge_code_original,
					chr(1)||'*' 														AS categorie_statutaire_code_original,
					chr(1)||'*' 														AS commission_paritaire_code_original,
					chr(1)||'*' 														AS compte_salarie_code_original,
					chr(1)||'*' 														AS filiere_code_original,
					chr(1)||'*' 														AS lettre_budgetaire_code_original,
					chr(1)||'*' 														AS unite_fonctionnelle_code_original,
					pycontrat.date_debut												AS date_debut_contrat,
					pycontrat.date_fin 													AS date_fin_contrat,
					coalesce(pycontrat.cnt_id,0) 										AS cnt_id,
                    -- w_tmp_1.cnt_id_all                                                  AS cnt_id_all,
                    w_tmp_1.est_hors_periode                                            AS est_hors_periode,
					w_tmp_1.per_id              										AS per_id,
					w_tmp_1.eta_id                 										AS eta_id,
					coalesce(w_tmp_1.bul_id,0) 											AS bul_id,
					w_tmp_1.eta_id::text||'|'||w_tmp_1.sal_matricule::text||'|'||pycontrat.cnt_id::text AS code_original_cnt,
                    -- w_tmp_1.eta_id::text||'|'||w_tmp_1.sal_matricule::text||'|'||w_tmp_1.cnt_id_all::text AS code_original_cnt_all,
                    w_tmp_1.heures_theoriques / 151.67 as ratio_temps_travail,
					0 AS profil_id,
                    w_tmp_1.mois,
                    coalesce(w_ana.ratio, 1) as ratio,
					min(w_tmp_1.date) AS date_debut,
					max(w_tmp_1.date) AS date_fin
				FROM w_tmp_1
					LEFT JOIN w_pycontrat AS pycontrat ON 1=1
						AND pycontrat.per_id = w_tmp_1.per_id
						AND pycontrat.cnt_id = w_tmp_1.cnt_id
                    LEFT JOIN prod_cegi.pymodelcnt on pymodelcnt.modcnt_id = pycontrat.modcnt_id
					LEFT JOIN prod_cegi.pytypecnt_cnt ON 1=1
						AND pytypecnt_cnt.per_id = w_tmp_1.per_id
						AND pytypecnt_cnt.cnt_id = w_tmp_1.cnt_id
                        AND date between cnt_typecnt_deb and case when cnt_typecnt_fin is null then '20991231'::date else cnt_typecnt_fin end
					LEFT JOIN prod_cegi.pytypecontrat ON pytypecontrat.typcnt_id = pytypecnt_cnt.typcnt_id
					LEFT JOIN prod_cegi.pytypecotisant ON pytypecotisant.typcot_code = pycontrat.typcot_code
					LEFT JOIN prod_cegi.pymtembauche ON pymtembauche.mitemb_id = pycontrat.mitemb_id
					LEFT JOIN prod_cegi.pymtfcnt ON pymtfcnt.mtfcnt_id = pycontrat.mtfcnt_id
					LEFT JOIN prod_cegi.pygrilleind ON pygrilleind.gri_id = pycontrat.gri_id
					LEFT JOIN prod_cegi.pyechelon ON pyechelon.ech_id = w_tmp_1.ech_id
                    LEFT JOIN w_pyvalechelon ON 1=1
                        AND w_pyvalechelon.ech_id = w_tmp_1.ech_id
                        AND date BETWEEN w_pyvalechelon.date_debut AND w_pyvalechelon.date_fin
					LEFT JOIN w_qualconv ON 1=1
						AND w_qualconv.cnt_id = w_tmp_1.cnt_id
						AND w_qualconv.per_id = w_tmp_1.per_id
                        AND date between w_qualconv.date_debut and w_qualconv.date_fin
                    LEFT JOIN w_qualification ON 1=1
                        AND w_qualification.cnt_id = w_tmp_1.cnt_id
                        AND w_qualification.per_id = w_tmp_1.per_id
                        AND date between w_qualification.date_debut and w_qualification.date_fin
					LEFT JOIN prod_cegi.pyservice ON pyservice.svc_code = pycontrat.svc_code
                    LEFT JOIN w_ana ON 1=1
						AND w_ana.per_id = w_tmp_1.per_id
						AND w_ana.cnt_id = w_tmp_1.cnt_id
                        AND date between w_ana.date_debut and w_ana.date_fin
					JOIN w_ets ON w_ets.eta_id = w_tmp_1.eta_id
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37
			;

			]]></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,
					per_nom 			AS nom,
					per_prenom 			AS prenom,
					per_naissance 		AS date_naissance,
					CASE WHEN titp_code = (select valeur FROM rh.t_divers WHERE code = 'CEGI_SEXE')
						THEN 'M'
						ELSE 'F'
					END 				AS sexe,
					sal_matricule 		AS matricule,
					sal_matricule 		AS code,
					w_ets.ent_id::text||'|'||sal_matricule AS code_original,
					w_ets.entreprise_id,
					t_nationalites.oid 	AS nationalite_id,
					t_codes_postaux.oid AS code_postal_id,
					per_nomjf 			AS nom_naissance,
					coalesce(((max(ARRAY[extract(epoch from pyvaleur_attribut.valatt_deb), t_situations_famille.oid]))[2]), 0) AS situation_famille_id,
					((max(ARRAY[w_profils.date_fin_contrat::text,w_profils.profil_id::text]))[2])::bigint AS profil_id,
					((max(ARRAY[w_profils.date_fin_contrat, w_profils.date_debut_contrat]))[2]) AS date_debut,
					((max(ARRAY[w_profils.date_fin_contrat, w_profils.date_fin_contrat]))[2]) AS date_fin,
					min(coalesce(sal_dateentree::date, date_debut_contrat)) AS date_entree_ets, -- #correction date entrée ets. non renseignée = date de début de 1er contrat.
					max(date_fin_contrat) AS date_sortie_ets,
					-- Champs dédiés au public.
					sal_dateentree::date AS date_entree_fp,
					sal_dateentree::date AS date_entree_fph,
					0 AS no_adeli,
					0 AS code_cotisation_id,
					0 AS matricule_retraite,
					per_nir||lpad(per_clenir, 2, '0') AS nir
				FROM prod_cegi.pysalarie
					JOIN w_profils 				ON w_profils.per_id             = pysalarie.per_id
					JOIN w_ets					ON w_ets.eta_id 				= w_profils.eta_id
					JOIN base.t_codes_postaux 	ON t_codes_postaux.code 		= pysalarie.per_cp
                    LEFT JOIN rh.t_nationalites ON t_nationalites.code_original = pysalarie.nat_code
                    LEFT JOIN prod_cegi.pyvaleur_attribut ON 1=1
                        AND pyvaleur_attribut.att_code = 'SITUA'
                        AND pyvaleur_attribut.per_id = pysalarie.per_id
                    LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = upper(substr(pyvaleur_attribut.att_val,1,3))||lpad(length(pyvaleur_attribut.att_val), 3, '0')
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,19,20,21,22,23,24
			;

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

			TRUNCATE rh.p_contrats
			;

			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

			INSERT INTO rh.p_contrats(
				salarie_id,
				date_debut,
				date_fin,
				numero_contrat,
				code_original,
				etablissement_id,
				profil_id)
				SELECT
					max(coalesce(p_salaries.oid,0)) 							 	  AS salarie_id,
					max(pycontrat.date_debut) 									 	  AS date_debut,
					max(pycontrat.date_fin)							 			 	  AS date_fin,
                    pycontrat.numero_contrat,
                    pycontrat.code_original,
					max(coalesce(t_etablissements.oid,0)) 							  AS etablissement_id,
					max(coalesce(w_profils.profil_id,0))							  AS profil_id
				FROM w_pycontrat AS pycontrat
                    JOIN prod_cegi.pysalarie ON pysalarie.per_id = pycontrat.per_id
					JOIN rh.p_salaries ON p_salaries.matricule = pysalarie.sal_matricule
					LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = pycontrat.eta_id
					JOIN w_profils ON w_profils.code_original_cnt = pycontrat.code_original
					JOIN w_ets ON w_ets.eta_id = pycontrat.eta_id
				GROUP BY pycontrat.eta_id, pycontrat.numero_contrat, pycontrat.code_original
			;

			-- #correction
			-- <strike>Si les dates d'entrée/sortie d'établissement semblent incohérentes par rapports aux dates des contrats, les corriger.</strike>
			UPDATE rh.p_salaries
			SET date_entree_ets = date_debut_contrat
			FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) subview
			WHERE 1=1
				AND p_salaries.oid = subview.salarie_id
				-- AND	date_debut_contrat < date_entree_ets -- On corrige désormais TOUTES les dates d'entrées ets. car cela pose des soucis de calcul
                -- des TOPs entrée/sortie ets. dans p_contrats_mois.
			;

			UPDATE rh.p_salaries
			SET date_sortie_ets = date_fin_contrat
			FROM (SELECT salarie_id, max(date_fin) AS date_fin_contrat from rh.p_contrats group by 1) subview
			WHERE 1=1
				AND p_salaries.oid = subview.salarie_id
				AND date_fin_contrat > date_sortie_ets
			;

			-- Calcul ancienneté au début de contrat
			UPDATE rh.p_contrats SET
				anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
				anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_jours / 30
			FROM (
                select
                    pycontrat.code_original,
                    case when row_number() OVER w = 1
                        then 0
                        else lag(cnt_datefin::date, 1, '2099-12-31'::date) over w - min(cnt_datedeb::date) over w + 1
                    end as anciennete_anterieure_jours
                FROM w_pycontrat as pycontrat
                WINDOW w AS (partition by per_id order by cnt_datedeb)) AS subq
			WHERE 1=1
				AND p_contrats.code_original = subq.code_original
			;

			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
                est_hors_periode,
                ratio_temps_travail,
                profil_id)
				SELECT
					p_contrats.salarie_id,
					p_contrats.oid AS contrat_id,
					w_profils.mois AS mois,
					w_profils.date_debut AS date_debut,
					w_profils.date_fin AS date_fin,
                    case when w_profils.cnt_id = 0 then 1 else 0 end as est_hors_periode,
                    w_profils.ratio_temps_travail,
                    max(coalesce(w_profils.profil_id, 0)) as profil_id -- si pas de max(), peut dédoubler les contrats mois à cause de prod_cegi.pyrepcnt_ana lors de la création de w_profils.
				FROM w_profils
					JOIN rh.p_contrats ON 1=1
                        AND w_profils.code_original_cnt = p_contrats.code_original
                        -- AND base.cti_overlaps(p_contrats.date_debut, p_contrats.date_fin, w_profils.date_debut, w_profils.date_fin)
                    JOIN rh.p_salaries ON p_contrats.salarie_id = p_salaries.oid
					JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
					JOIN rh.t_entreprises ON t_etablissements.entreprise_id = t_entreprises.oid
				WHERE 1=1
					--AND p_calendrier_mois.mois >= 201601
					AND w_profils.date_debut <= base.cti_last_day(current_date)
				GROUP BY 1,2,3,4,5,6,7
			;

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

			DROP TABLE IF EXISTS w_hp
			;

			CREATE TEMP TABLE w_hp AS
				SELECT
					pysalarie.sal_matricule,
                    w_ets.ent_id::text||'|'||pysalarie.sal_matricule as salarie_code_original,
					pycontrat.eta_id::text||'|'||pysalarie.sal_matricule::text||'|'||pycontrat.cnt_id::text AS cti_cnt_id,
					(cal_an::int::text||lpad(cal_nperiode, 2, '0'))::numeric AS mois_paie,
                    (cal_an::int::text||lpad(cal_nperiode, 2, '0'))::numeric AS mois_activite,
                    pybulletin.bul_id,
					pybulletin.date_debut,
					pybulletin.date_fin,
					cal_nperiode AS cal_nperiode,
                    base.cti_last_day((cal_an::int::text||lpad(cal_nperiode, 2, '0')||'01'::text)::date) as date_paie, --  bul_datepaie,
					pybulletin.bul_datepaie::date AS bul_datepaie,
					pycontrat.per_id,
					pycontrat.cnt_id,
                    w_ets.etablissement_id,
                    t_rubriques.p_detail,
                    t_rubriques.p_cumul,
					pylignebulletin.rub_id,
                    pylignebulletin.ruv_id,
                    pylignebulletin.cot_id,
                    pylignebulletin.ctid as plb_ctid,
					sum(CASE WHEN p_base THEN (CASE s_base
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN to_number(coalesce(nullif(lbu_valeur2, ''), '0'), '999999999999.9999')
                        END) ELSE 0 END * c_base)::numeric AS base,
                    sum(CASE WHEN p_nombre THEN (CASE s_nombre
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN to_number(coalesce(nullif(lbu_valeur2, ''), '0'), '999999999999.9999')
                        END) ELSE 0 END * c_nombre)::numeric AS nombre,
                    sum(CASE WHEN p_heures_contrat THEN (CASE s_heures_contrat
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN to_number(coalesce(nullif(lbu_valeur2, ''), '0'), '999999999999.9999')
                        END) ELSE 0 END * c_heures_contrat)::numeric AS heures_contrat,
                    sum(CASE WHEN p_heures_payees THEN (CASE s_heures_payees
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN to_number(coalesce(nullif(lbu_valeur2, ''), '0'), '999999999999.9999')
                        END) ELSE 0 END * c_heures_payees)::numeric AS heures_payees,
                    sum(CASE WHEN p_heures_travaillees THEN (CASE s_heures_travaillees
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp
                            WHEN 6 THEN to_number(coalesce(nullif(lbu_valeur2, ''), '0'), '999999999999.9999')
                        END) ELSE 0 END * c_heures_travaillees)::numeric AS heures_travaillees,
                    sum(CASE WHEN p_masse_salariale THEN (CASE s_masse_salariale
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_masse_salariale)::numeric AS montant_masse_salariale,
					sum(CASE WHEN p_brut THEN (CASE s_brut
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_brut)::numeric AS montant_brut,
					sum(CASE WHEN p_avantage_nature THEN (CASE s_avantage_nature
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_avantage_nature)::numeric AS montant_avantage_nature,
					sum(CASE WHEN p_frais_imposables THEN (CASE s_frais_imposables
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_frais_imposables)::numeric AS montant_frais_imposables,
					sum(lbu_tauxs * coefficient_txs) AS taux_cotisation_salarie,
					sum(CASE WHEN p_cotisation_salarie THEN (CASE s_cotisation_salarie
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_cotisation_salarie)::numeric AS montant_cotisation_salarie,
					sum(lbu_tauxp * coefficient_txp) AS taux_cotisation_patronale,
					sum(CASE WHEN p_cotisation_patronale THEN (CASE s_cotisation_patronale
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_cotisation_patronale)::numeric AS montant_cotisation_patronale,
					sum(CASE WHEN p_od_net_salarie THEN (CASE s_od_net_salarie
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_od_net_salarie)::numeric AS montant_od_net_salarie,
                    sum(CASE WHEN p_od_net_patronale THEN (CASE s_od_net_patronale
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_od_net_patronale)::numeric AS montant_od_net_patronale,
					sum(CASE WHEN p_net_imposable THEN (CASE s_net_imposable
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_net_imposable)::numeric AS montant_net_imposable_salarie,
					sum(CASE WHEN p_net_a_payer THEN (CASE s_net_a_payer
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_net_a_payer)::numeric AS montant_net_a_payer_salarie,
					sum(CASE WHEN p_nombre_provisions THEN (CASE s_nombre_provisions
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_nombre_provisions)::numeric AS nombre_provisions,
					sum(CASE WHEN p_montant_provisions THEN (CASE s_montant_provisions
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_montant_provisions)::numeric AS montant_provisions,
					sum(CASE WHEN p_masse_salariale_provisionnee THEN (CASE s_masse_salariale_provisionnee
                            WHEN 0 THEN to_number(coalesce(nullif(lbu_valeur1, ''), '0'), '999999999999.9999')
                            WHEN 1 THEN lbu_base
                            WHEN 2 THEN lbu_tauxs
                            WHEN 3 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END)
                            WHEN 4 THEN lbu_tauxp
                            WHEN 5 THEN lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 6 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 7 THEN lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) - lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                            WHEN 8 THEN -lbu_montants * (CASE WHEN rub_gain = 1 THEN -1 ELSE 1 END) + lbu_montantp * (CASE WHEN rub_gain = 1 THEN 1 ELSE -1 END)
                        END) ELSE 0 END * c_masse_salariale_provisionnee)::numeric AS montant_masse_salariale_provisionnee
				FROM w_pybulletin as pybulletin
					JOIN prod_cegi.pylignebulletin          ON pylignebulletin.bul_id = pybulletin.bul_id
                    JOIN prod_cegi.pycontrat                ON pybulletin.per_id = pycontrat.per_id AND pybulletin.cnt_id = pycontrat.cnt_id
                    JOIN prod_cegi.pysalarie                ON pysalarie.per_id = pycontrat.per_id
                    JOIN w_ets                              ON w_ets.eta_id = pycontrat.eta_id
                    JOIN prod_cegi.pyrubrique               ON pyrubrique.rub_id = pylignebulletin.rub_id
                    JOIN rh.t_rubriques                     ON t_rubriques.code_original = pyrubrique.rub_id
                WHERE 1=1
                    AND cal_an::int >= 2016
                    AND (1!=1
                        OR t_rubriques.p_detail
                        OR t_rubriques.p_cumul)
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
			;

			DROP TABLE IF EXISTS w_hp_1
            ;

            CREATE TEMP TABLE w_hp_1 AS
                with ruv as (
                    select
                        ruv_id,
                        ruvjs_signed,
                        plc_compte as ruv_plc_compte
                    from prod_cegi.pyrubjsal
                        join prod_cegi.pyljsalaireent on pyljsalaireent.ljs_id = PYRUBJSAL.ljs_id
                        where ruvjs_signed = 1)
                ,cot as (
                    select
                        cot_id,
                        cotjs_signed,
                        plc_compte as cot_plc_compte
                    from prod_cegi.pycotjsal
                        join prod_cegi.pyljsalaireent as cotcot on cotcot.ljs_id = PYcotJSAL.ljs_id)
                ,hp as (
                    select 
                        pylignebulletin.ctid as plb_ctid,
                        pylignebulletin.bul_id,
                        pylignebulletin.rub_id,
                        max(coalesce(ruv_plc_compte, cot_plc_compte)::text) as plc_compte
                    from prod_cegi.pylignebulletin 
                        join prod_cegi.pybulletin on pybulletin.bul_id = pylignebulletin.bul_id 
                        left join ruv on ruv.ruv_id = pylignebulletin.ruv_id
                        left join cot on cot.cot_id = pylignebulletin.cot_id
                    group by 1,2,3)
                , hp2 as (
				SELECT
                    w_hp.plb_ctid,
                    cti_cnt_id,
                    w_hp.bul_id,
                    w_hp.date_debut,
                    w_hp.date_fin,
                    bul_datepaie,
					p_salaries.oid as salarie_id,
					(max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
                    (max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id,
					w_hp.mois_activite,
                    w_hp.mois_paie,
                    w_hp.date_paie,
					t_rubriques.oid as rubrique_id,
                    max(coalesce(t_compte.oid, 0)) as compte_id,
                    t_rubriques.p_detail,
                    t_rubriques.p_cumul,
					0 as organisme_cotisation_id,
                    w_hp.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
					LEFT JOIN rh.p_contrats on p_contrats.code_original = w_hp.cti_cnt_id
					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_activite
					JOIN rh.p_salaries on p_salaries.code_original = w_hp.salarie_code_original
					JOIN rh.t_rubriques on t_rubriques.code_original = w_hp.RUB_ID
                    left join hp on hp.plb_ctid = w_hp.plb_ctid
                    left join hp as hp2 on hp2.bul_id = w_hp.bul_id and hp2.rub_id in (10000, 10001)
                    LEFT JOIN rh.t_compte on t_compte.code_original = coalesce(hp.plc_compte, case when w_hp.rub_id < 10000 then hp2.plc_compte else null end)
                GROUP BY 1,2,3,4,5,6,7, 10,11,12,13 ,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,w_hp.ctid)
                SELECT
                    nextval('rh.s_historique_paie') as hp_oid,
                    plb_ctid,
                    cti_cnt_id,
                    bul_id,
                    date_debut,
                    date_fin,
                    bul_datepaie,
					salarie_id,
					contrat_id,
                    contrat_mois_id,
					mois_activite,
                    mois_paie,
                    date_paie,
					rubrique_id,
                    compte_id,
                    p_detail,
                    p_cumul,
					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 hp2
			;

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

            TRUNCATE rh.p_historique_paie
            ;

            INSERT INTO rh.p_historique_paie(
                oid,
                code_original,
                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
					hp_oid,
					bul_id,
					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,
					CASE WHEN base  > 99999999  THEN 99999999.99 ELSE round(base::numeric,2) END ,
					nombre,
					heures_contrat,
					heures_payees,
					heures_travaillees,
					montant_masse_salariale,
					montant_brut,
					montant_avantage_nature,
					montant_frais_imposables,
					CASE WHEN taux_cotisation_salarie > 999999 THEN 999999.9999999 ELSE round(taux_cotisation_salarie::numeric,7) END,
					montant_cotisation_salarie,
					CASE WHEN taux_cotisation_salarie > 999999 THEN 999999.9999999 ELSE round(taux_cotisation_patronale::numeric,7) END,
					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
					where p_detail;

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

            update rh.p_historique_paie set
                nombre = nombre * ratio_temps_travail
            from rh.p_contrats_mois
            where 1=1
                and p_historique_paie.contrat_mois_id = p_contrats_mois.oid
                and rubrique_id in (select oid from rh.t_rubriques where @c_nombre != 1)
                and ratio_temps_travail != 1
            ;

            -- Alimentation de la base de la rubrique 1052 forfait jour à partir de la constante AAAAC.
            DROP TABLE IF EXISTS w_forfait_jour
			;

			CREATE TEMP TABLE w_forfait_jour AS
                with fj2 as (
                    select pycontrat.eta_id::text||'|'||pysalarie.sal_matricule::text||'|'||pycontrat.cnt_id::text as ncnt
                    from prod_cegi.pyconstante
                        join prod_cegi.pycst_cnt on pycst_cnt.cst_id = pyconstante.cst_id
                        join prod_cegi.pysalarie on pysalarie.per_id = pycst_cnt.per_id
                        JOIN prod_cegi.pycontrat ON 1=1
                            and pycontrat.per_id = pycst_cnt.per_id
                            and pycontrat.cnt_id = pycst_cnt.cnt_id
                    where cst_code = (select valeur FROM rh.t_divers WHERE code = 'CEGI_CST_FJ')
                )
                select
                    php.oid as f_id,
                    ratio_temps_travail -- ratio du temps de travail (constance AAAAC).
                    -- ratio du nombre de jours du bulletin vs. nombre de jour sur le mois
                    * (php.date_fin - php.date_debut + 1)::numeric / (base.cti_last_day((php.mois_paie||'01')::date) - base.cti_first_day((php.mois_paie||'01')::date) + 1)::numeric
                    -- temps de travail réglementaire 35h.
                    * 151.67 as heures_forfait
                from rh.p_historique_paie as php
                    join rh.p_contrats_mois on p_contrats_mois.oid = php.contrat_mois_id
                where 1=1
                    and rubrique_id = (select oid from rh.t_rubriques where code = '01052')
                    and (select valeur = '1' FROM rh.t_divers WHERE code = 'CEGI_FORFAIT_JOUR')

                UNION ALL

                select
                    hp_oid as f_id,
                    ratio_temps_travail -- ratio du temps de travail (constante AAAAC ou AARM).
                    -- ratio du nombre de jours du bulletin vs. nombre de jour sur le mois
                    * (php.date_fin - php.date_debut + 1)::numeric / (base.cti_last_day((php.mois_paie||'01')::date) - base.cti_first_day((php.mois_paie||'01')::date) + 1)::numeric
                    -- temps de travail réglementaire 35h.
                    * 151.67 as heures_forfait
                from w_hp_1 as php
                    join rh.p_contrats_mois on p_contrats_mois.oid = php.contrat_mois_id
                    join rh.p_contrats on p_contrats.oid = p_contrats_mois.contrat_id
                    join fj2 on fj2.ncnt = p_contrats.code_original
                where 1=1
                    and rubrique_id IN (select oid from rh.t_rubriques where code IN ('01050', '10000'))
                    and (select valeur = '2' FROM rh.t_divers WHERE code = 'CEGI_FORFAIT_JOUR')
            ;

            update rh.p_historique_paie as php set
                base = heures_forfait,
                heure_contrat = heures_forfait,
                heure_payee = heures_forfait,
                heure_travaillee =
                    case (select valeur FROM rh.t_divers WHERE code = 'CEGI_FORFAIT_JOUR')
                        when '1' then heures_forfait
                        when '2' then 0.0
                        else 0.0
                    end
            from w_forfait_jour
            where w_forfait_jour.f_id = php.oid
            ;

            update w_hp_1 as php set
                heures_contrat = heures_forfait,
                heures_payees = heures_forfait,
                heures_travaillees =
                    case (select valeur FROM rh.t_divers WHERE code = 'CEGI_FORFAIT_JOUR')
                        when '1' then heures_forfait
                        when '2' then 0.0
                        else 0.0
                    end
            from w_forfait_jour
            where w_forfait_jour.f_id = php.hp_oid
            ;

			DROP TABLE IF EXISTS w_tmp
			;

			CREATE TEMP TABLE w_tmp AS
				SELECT
					cti_cnt_id,
                    bul_id,
                    salarie_id,
                    contrat_id,
                    contrat_mois_id,
                    etablissement_id,
					mois_activite,
                    mois_paie,
					date_debut,
					date_fin,
					date_paie,
                    round(sum(heures_contrat), 2) as heures_contrat,
                    round(sum(heures_payees), 2) as heures_payees,
                    round(sum(heures_travaillees), 2) as heures_travaillees,
                    round(sum(montant_masse_salariale), 2) as montant_masse_salariale,
                    round(sum(montant_brut), 2) AS montant_brut,
                    round(sum(montant_avantage_nature), 2) as montant_avantage_nature,
                    round(sum(montant_frais_imposables), 2) as montant_frais_imposables,
                    round(sum(montant_cotisation_salarie), 2) AS montant_cotisation_salarie,
                    round(sum(montant_cotisation_patronale), 2) AS montant_cotisation_patronale,
                    round(sum(montant_od_net_salarie), 2) as montant_od_net_salarie,
                    round(sum(montant_od_net_patronale), 2) as montant_od_net_patronale,
                    round(sum(montant_net_imposable_salarie), 2) as montant_net_imposable_salarie,
                    round(sum(montant_net_a_payer_salarie), 2) as montant_net_a_payer_salarie,
                    round(sum(nombre_provisions), 2) as nombre_provisions,
                    round(sum(montant_provisions), 2) as montant_provisions,
                    round(sum(montant_masse_salariale_provisionnee), 2) as montant_masse_salariale_provisionnee
				FROM w_hp_1
                where p_detail
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11
			;

            DROP TABLE IF EXISTS w_cible
            ;

            CREATE TEMP TABLE w_cible AS
                SELECT
                    cti_cnt_id,
                    bul_id,
                    salarie_id,
                    contrat_id,
                    contrat_mois_id,
                    etablissement_id,
                    mois_activite,
                    mois_paie,
                    date_debut,
                    date_fin,
                    date_paie,
                    round(sum(case when p_cumul then heures_contrat else 0 end), 2) as heures_contrat,
                    round(sum(case when p_cumul then heures_payees else 0 end), 2) as heures_payees,
                    round(sum(case when p_cumul then heures_travaillees else 0 end), 2) as heures_travaillees,
                    round(sum(case when p_cumul then montant_masse_salariale else 0 end), 2) as montant_masse_salariale,
                    round(sum(case when p_cumul then montant_brut else 0 end), 2) AS montant_brut,
                    round(sum(case when p_cumul then montant_avantage_nature else 0 end), 2) as montant_avantage_nature,
                    round(sum(case when p_cumul then montant_frais_imposables else 0 end), 2) as montant_frais_imposables,
                    round(sum(case when p_cumul then montant_cotisation_salarie else 0 end), 2) AS montant_cotisation_salarie,
                    round(sum(case when p_cumul then montant_cotisation_patronale else 0 end), 2) AS montant_cotisation_patronale,
                    round(sum(case when p_cumul then montant_od_net_salarie else 0 end), 2) as montant_od_net_salarie,
                    round(sum(case when p_cumul then montant_od_net_patronale else 0 end), 2) as montant_od_net_patronale,
                    round(sum(case when p_cumul then montant_net_imposable_salarie else 0 end), 2) as montant_net_imposable_salarie,
                    round(sum(case when p_cumul then montant_net_a_payer_salarie else 0 end), 2) as montant_net_a_payer_salarie,
                    round(sum(case when p_cumul then nombre_provisions else 0 end), 2) as nombre_provisions,
                    round(sum(case when p_cumul then montant_provisions else 0 end), 2) as montant_provisions,
                    round(sum(case when p_cumul then montant_masse_salariale_provisionnee else 0 end), 2) as montant_masse_salariale_provisionnee
                FROM w_hp_1
                where p_cumul
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11
            ;

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

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

			-- Inserer pour chaque bulletin une ligne 'Ecart cumulé' qui va faire le compte avec le total
			INSERT INTO rh.p_historique_paie(
                salarie_id,
                code_original,
                contrat_id,
                contrat_mois_id,
                mois_activite,
                date_debut,
                date_fin,
                mois_paie,
                date_paie,
                rubrique_id,
                compte_id,
                organisme_cotisation_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
                    subq.salarie_id,
                    subq.bul_id,
                    subq.contrat_id,
                    subq.contrat_mois_id,
                    subq.mois_activite,
                    subq.date_debut,
                    subq.date_fin,
                    subq.mois_paie,
                    subq.date_paie,
                    (select oid from rh.t_rubriques where code_original = 'C000'),
                    subq.compte_id,
                    0 as organisme_cotisation_id,
                    0 as base,
                    0 as nombre,
                    subq.heures_contrat,
                    subq.heures_payees,
                    subq.heures_travaillees,
                    subq.montant_masse_salariale,
                    subq.montant_brut,
                    subq.montant_avantage_nature,
                    subq.montant_frais_imposables,
                    0 as taux_cotisation_salarie,
                    subq.montant_cotisation_salarie,
                    0 as taux_cotisation_patronale,
                    subq.montant_cotisation_patronale,
                    subq.montant_od_net_salarie,
                    subq.montant_od_net_patronale,
                    subq.montant_net_imposable_salarie,
                    subq.montant_net_a_payer_salarie,
                    subq.nombre_provisions,
                    subq.montant_provisions,
                    subq.montant_masse_salariale_provisionnee
                FROM (
                    SELECT
                        coalesce(w_cible.salarie_id, w_tmp.salarie_id) as salarie_id,
                        coalesce(w_cible.contrat_id, w_tmp.contrat_id) as contrat_id,
                        coalesce(w_cible.contrat_mois_id, w_tmp.contrat_mois_id) as contrat_mois_id,
                        0 as compte_id,
                        coalesce(w_cible.bul_id, w_tmp.bul_id) as bul_id,
                        coalesce(w_cible.mois_activite, w_tmp.mois_activite) as mois_activite,
                        coalesce(w_cible.date_debut, w_tmp.date_debut) as date_debut,
                        coalesce(w_cible.date_fin, w_tmp.date_fin) as date_fin,
                        coalesce(w_cible.mois_paie, w_tmp.mois_paie) as mois_paie,
                        coalesce(w_cible.date_paie, w_tmp.date_paie) as date_paie,
                        0 AS heures_contrat, -- Tant que sous Cegi aucune rubrique n'a ?t? identifi?e comme ?tant la totalisation des heures contrat/travaill?es, on ne calcul pas d'?cart cumul?.
                        sum(case when total_heures_payees then coalesce(w_cible.heures_payees, 0) - coalesce(w_tmp.heures_payees, 0) else 0 end) AS heures_payees,
                        0 AS heures_travaillees, -- Tant que sous Cegi aucune rubrique n'a ?t? identifi?e comme ?tant la totalisation des heures contrat/travaill?es, on ne calcul pas d'?cart cumul?.
                        sum(case when total_masse_salariale then coalesce(w_cible.montant_masse_salariale, 0) - coalesce(w_tmp.montant_masse_salariale, 0) else 0 end) AS montant_masse_salariale,
                        sum(case when total_brut then coalesce(w_cible.montant_brut, 0) - coalesce(w_tmp.montant_brut, 0) else 0 end) AS montant_brut,
                        sum(case when total_avantage_nature then coalesce(w_cible.montant_avantage_nature, 0) - coalesce(w_tmp.montant_avantage_nature, 0) else 0 end) AS montant_avantage_nature,
                        sum(case when total_frais_imposables then coalesce(w_cible.montant_frais_imposables, 0) - coalesce(w_tmp.montant_frais_imposables, 0) else 0 end) AS montant_frais_imposables,
                        sum(case when total_cotisation_salarie then coalesce(w_cible.montant_cotisation_salarie, 0) - coalesce(w_tmp.montant_cotisation_salarie, 0) else 0 end) AS montant_cotisation_salarie,
                        sum(case when total_cotisation_patronale then coalesce(w_cible.montant_cotisation_patronale, 0) - coalesce(w_tmp.montant_cotisation_patronale, 0) else 0 end) AS montant_cotisation_patronale,
                        sum(case when total_od_net_salarie then coalesce(w_cible.montant_od_net_salarie, 0) - coalesce(w_tmp.montant_od_net_salarie, 0) else 0 end) AS montant_od_net_salarie,
                        sum(case when total_od_net_patronale then coalesce(w_cible.montant_od_net_patronale, 0) - coalesce(w_tmp.montant_od_net_patronale, 0) else 0 end) AS montant_od_net_patronale,
                        sum(case when total_net_imposable then coalesce(w_cible.montant_net_imposable_salarie, 0) - coalesce(w_tmp.montant_net_imposable_salarie, 0) else 0 end) AS montant_net_imposable_salarie,
                        sum(case when total_net_a_payer then coalesce(w_cible.montant_net_a_payer_salarie, 0) - coalesce(w_tmp.montant_net_a_payer_salarie, 0) else 0 end) AS montant_net_a_payer_salarie,
                        sum(case when total_nombre_provisions then coalesce(w_cible.nombre_provisions, 0) - coalesce(w_tmp.nombre_provisions, 0) else 0 end) AS nombre_provisions,
                        sum(case when total_montant_provisions then coalesce(w_cible.montant_provisions, 0) - coalesce(w_tmp.montant_provisions, 0) else 0 end) AS montant_provisions,
                        sum(case when total_masse_salariale_provisionnee then coalesce(w_cible.montant_masse_salariale_provisionnee, 0) - coalesce(w_tmp.montant_masse_salariale_provisionnee, 0) else 0 end) AS montant_masse_salariale_provisionnee
                    FROM (select bul_id from w_tmp
                        union
                        select bul_id from w_cible) as all_buls
                        JOIN w_cumul ON true
                        left JOIN w_tmp ON w_tmp.bul_id = all_buls.bul_id
                        left JOIN w_cible ON w_cible.bul_id = all_buls.bul_id
                    GROUP BY 1,2,3,4,5,6,7,8,9,10) AS subq
                WHERE 1!=1
                    OR subq.heures_contrat != 0
                    OR subq.heures_payees != 0
                    OR subq.heures_travaillees != 0
                    OR subq.montant_masse_salariale != 0
                    OR subq.montant_brut != 0
                    OR subq.montant_avantage_nature != 0
                    OR subq.montant_frais_imposables != 0
                    OR subq.montant_cotisation_salarie != 0
                    OR subq.montant_cotisation_patronale != 0
                    OR subq.montant_od_net_salarie != 0
                    OR subq.montant_od_net_patronale != 0
                    OR subq.montant_net_imposable_salarie != 0
                    OR subq.montant_net_a_payer_salarie != 0
                    OR subq.nombre_provisions != 0
                    OR subq.montant_provisions != 0
                    OR 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 AS profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					SUM(w_profils.ratio),
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
                    JOIN rh.p_contrats ON p_contrats.oid = p_contrats_mois.contrat_id
                    JOIN w_profils ON 1=1
                        AND w_profils.code_original_cnt = p_contrats.code_original
                        AND base.cti_overlaps(p_contrats_mois.date_debut, p_contrats_mois.date_fin, w_profils.date_debut, w_profils.date_fin)
				GROUP BY 1,2,3,5
			;

			
            -- Calcul ETP théorique, Il faudra sans doute optimiser
            WITH maj_etp as (
                SELECT
                    contrat_mois_id, 
                    (CASE 
                        WHEN type_temps_travail_id = 0 THEN 100
                        WHEN type_temps_travail_code = 'TC' THEN 100
                        WHEN base.cti_to_number(substr(type_temps_travail_code, 3)) = 0 THEN 1
                        ELSE base.cti_to_number(substr(type_temps_travail_code, 3))
                    END)::numeric AS pct_temps_travail,
                    (p_contrats_mois.date_fin - p_contrats_mois.date_debut + 1)::numeric AS duree,
                    (p_calendrier_mois.date_fin - p_calendrier_mois.date_debut + 1)::numeric AS duree_mois
                FROM rh.p_contrats_mois
                    JOIN base.p_calendrier_mois ON p_calendrier_mois.mois = p_contrats_mois.mois_activite
                    JOIN rh.p_profil_contrat_mois ON p_profil_contrat_mois.contrat_mois_id = p_contrats_mois.oid
                    JOIN rh.p_profils ON p_profils.oid = p_profil_contrat_mois.profil_id)
            UPDATE rh.p_contrats_mois SET
                equivalent_temps_plein = round((duree / duree_mois) * (pct_temps_travail / 100), 7)
            FROM maj_etp
            WHERE 1=1
                AND p_contrats_mois.oid = maj_etp.contrat_mois_id
                AND equivalent_temps_plein IS DISTINCT FROM round((duree / duree_mois) * (pct_temps_travail / 100), 7)
            ;

			-- la somme des ration ne doit pas dépasser 1
			UPDATE rh.p_profil_contrat_mois 
			SET ratio = ratio/coef
			FROM (
				SELECT
					contrat_mois_id AS cm_id,array_agg(ratio),
					SUM(ratio) as coef 
				FROM
					rh.p_profil_contrat_mois  
				GROUP BY 1 
				HAVING SUM(ratio) != 1
			) sub
			WHERE contrat_mois_id = cm_id
			;
			]]></sqlcmd>
		</NODE>
		<NODE label="Arrêts de travail">
			<sqlcmd><![CDATA[

            -- Les absences au sens large sont remontées depuis Cegi.
			DROP TABLE IF EXISTS w_at
			;
			CREATE TEMP TABLE w_at 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)
                ,clustering as (
                    select
                        per_id,
                        pyabsence.abspar_id,
                        abs_id,
                        nullif(coalesce(lag(abs_fin::date) over (partition by per_id, pyabsence.abspar_id order by abs_deb)    + '1 day'::interval not between abs_deb and abs_fin, true), false) as new_cluster,
                        nullif(coalesce(lag(abs_deb::date) over (partition by per_id order by abs_deb desc)    - '1 day'::interval not between abs_deb and abs_fin, true), false) as new_cluster_reprise,
                        abs_deb::date,
                        abs_fin::date,
                        base.cti_division(abs_val::numeric, @abs_val::numeric) as signe
                    FROM prod_cegi.pyabsence
                        LEFT JOIN prod_cegi.ABSENCEPARAM ON pyabsence.abspar_id = ABSENCEPARAM.abspar_id
                        left join exc_mar_arr on ABSENCEPARAM.abspar_code ilike any (exc_mar_arr.codes)
                    WHERE 1=1
                        AND abs_deb::date <= base.cti_last_day(current_date)
                        and abs_valide = '1'
                        and exc_mar_arr.codes is null)
                ,assigned_clustering as (
                    select
                        *,
                        string_to_array(array_to_string(
                        array_agg(case when new_cluster then abs_id else null end)  over (
                        partition by per_id, abspar_id
                            order by per_id, abs_deb
                            rows unbounded preceding
                            ), ','), ',')::numeric[] as abs_ids,
                        string_to_array(array_to_string(
                        array_agg(case when new_cluster_reprise then abs_fin else null end)  over (
                            partition by per_id order by per_id, abs_deb desc
                            rows unbounded preceding
                            ), ','), ',')::date[] as reprises
                    from clustering)
                ,contrats AS (
                    SELECT 
                        assigned_clustering.abs_id,
                        MAX(pydetabsence.cnt_id) AS max_cnt_id
                    FROM assigned_clustering
                    JOIN prod_cegi.pydetabsence on pydetabsence.abs_id = assigned_clustering.abs_id
                    GROUP BY 1
                )
                select
                    assigned_clustering.per_id,
                    assigned_clustering.abspar_id,
                    assigned_clustering.abs_id,
                    assigned_clustering.abs_ids[array_upper(assigned_clustering.abs_ids, 1)] as unique_abs_id,
                    assigned_clustering.abs_ids,
                    assigned_clustering.abs_deb,
                    assigned_clustering.abs_fin,
                    assigned_clustering.signe,
                    case when bool_or(new_cluster_reprise) over (partition by assigned_clustering.per_id,assigned_clustering.abs_ids[array_upper(assigned_clustering.abs_ids, 1)]) then (reprises[array_upper(assigned_clustering.reprises, 1)] + '1 day'::interval)::date else null::date end as reprise,
                    contrats.max_cnt_id
                from assigned_clustering
                JOIN contrats ON contrats.abs_id = assigned_clustering.abs_id
            ;

            CREATE INDEX w_at_1 ON w_at USING btree (per_id)
            ;
            CREATE INDEX w_at_2 ON w_at USING btree (abs_id)
            ;
            CREATE INDEX w_at_3 ON w_at USING btree (unique_abs_id)
            ;

			TRUNCATE rh.p_arrets_travail
			;

			TRUNCATE rh.p_arrets_travail_mois
			;

			ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
			;

			INSERT INTO rh.p_arrets_travail(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				date_reprise,
				motif_arret_id,
				precision_motif_arret_id,
				nb_jours)
				SELECT
					p_salaries.oid,
					p_contrats.oid,
					to_char(max(w_at.abs_fin), 'YYYYMM')::numeric,
					min(w_at.abs_deb),
					max(w_at.abs_fin),
					max(w_at.reprise),
					t_motifs_arret.oid,
					0,
					(max(w_at.abs_fin) - min(w_at.abs_deb) + 1) * signe -- gérer la régul. d'absence.
				FROM w_at
					JOIN prod_cegi.pydetabsence on pydetabsence.abs_id = w_at.abs_id -- peut y avoir plusieurs lignes pour une même absence. On la garde car elle contient cnt_id.
					JOIN prod_cegi.pysalarie on pysalarie.per_id = w_at.per_id
					JOIN prod_cegi.pycontrat on 1=1
                        AND pycontrat.per_id = w_at.per_id
                        AND pycontrat.cnt_id = w_at.max_cnt_id
					JOIN prod_cegi.pyabsenceparam on pyabsenceparam.abspar_id = w_at.abspar_id
					JOIN prod_cegi.ABSENCEPARAM on ABSENCEPARAM.abspar_id=pyabsenceparam.abspar_id
					JOIN rh.p_salaries on p_salaries.matricule = pysalarie.sal_matricule
					JOIN rh.p_contrats on p_contrats.code_original = pycontrat.eta_id::text||'|'||pysalarie.sal_matricule::text||'|'||pycontrat.cnt_id::text
					JOIN rh.t_motifs_arret on t_motifs_arret.code_original = ABSENCEPARAM.abspar_code
				--WHERE date_part('year', detabs_fin) >= 2016
				GROUP BY w_at.unique_abs_id, w_at.signe, 1,2, 7, 8
			;

			INSERT INTO rh.p_arrets_travail_mois(
				arret_travail_id,
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				nb_debut_arret,
				nb_fin_arret,
				nb_reprise_apres_arret,
				date_debut,
				date_fin,
				nb_jours,
				nb_arret)
				SELECT
					arr.oid AS arret_travail_id,
					arr.salarie_id AS salarie_id,
					arr.contrat_id AS contrat_id,
					p_contrats_mois.oid AS contrat_mois_id,
					cal.mois,
					CASE WHEN arr.date_debut BETWEEN cal.date_debut AND cal.date_fin THEN 1 ELSE 0 END AS nombre_debut_arret,
					CASE WHEN arr.date_fin BETWEEN cal.date_debut AND cal.date_fin THEN 1 ELSE 0 END AS nombre_fin_arret,
					CASE WHEN arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin THEN 1 ELSE 0 END AS nombre_reprise_apres_arret,
					-- Lorsque la date de reprise est isolée sur un mois (l'arrêt de travail s'est terminé le mois précédent) :
					-- la date de début = date de reprise,
					CASE WHEN arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin AND arr.date_fin<cal.date_debut THEN arr.date_reprise ELSE GREATEST(cal.date_debut, arr.date_debut) END AS date_debut,
					-- la date de fin = date de reprise et
					CASE WHEN arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin AND arr.date_fin<cal.date_debut THEN arr.date_reprise ELSE LEAST(cal.date_fin, arr.date_fin) END AS date_fin,
					-- le nb de jours est toujours = 0.
					(CASE WHEN arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin AND arr.date_fin<cal.date_debut THEN 0 ELSE LEAST(cal.date_fin, arr.date_fin)::date - GREATEST(cal.date_debut, arr.date_debut)::date + 1 END) * base.cti_division(arr.nb_jours, @arr.nb_jours) AS nb_jours,
					base.cti_division(arr.nb_jours, @arr.nb_jours) as nb_arret
				FROM base.p_calendrier_mois AS cal
					JOIN rh.p_arrets_travail AS arr ON base.cti_overlaps(arr.date_debut, case when arr.date_reprise = (arr.date_fin + '1 day'::interval)::date then arr.date_reprise else arr.date_fin end, cal.date_debut, cal.date_fin)
					JOIN rh.p_contrats_mois ON 1=1  -- Pas LEFT JOIN car les rares cas où l'arrêt serait hors contrat correspond en fait à une date de reprise (créée par iCTI) sur le 1er jour du mois suivant et où la personne a quitté l'établissement.
													-- La ventilation mensuelle de reprise n'aurait pas du être générée par CTI car il n'y a pas eu de reprise en fait.
						AND p_contrats_mois.mois_activite = cal.mois
						AND p_contrats_mois.contrat_id = arr.contrat_id
				WHERE cal.date_debut <= base.cti_last_day(current_date)
			;
			
			-- Suppression des doublons de contrats
			DELETE FROM rh.p_arrets_travail_mois
			USING
			(		
			SELECT arret_travail_id, p_arrets_travail_mois.mois_activite, (MAX(ARRAY[CASE WHEN p_arrets_travail_mois.date_fin >= p_contrats_mois.date_debut AND p_arrets_travail_mois.date_debut <= p_contrats_mois.date_fin THEN 1 ELSE 0 END,contrat_mois_id]))[2] AS keep_contrat_mois_id
			FROM rh.p_arrets_travail_mois
			JOIN rh.p_contrats_mois ON contrat_mois_id = p_contrats_mois.oid
			GROUP BY 1,2
			HAVING count(*) > 1
			) subview
			WHERE p_arrets_travail_mois.arret_travail_id = subview.arret_travail_id AND
				p_arrets_travail_mois.mois_activite = subview.mois_activite AND
				p_arrets_travail_mois.contrat_mois_id <> keep_contrat_mois_id
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Compléments historique paie">
			<sqlcmd><![CDATA[

			-- Proratiser les conversions jours selon etp
			UPDATE rh.p_historique_paie SET
				heure_travaillee = CASE WHEN p_heures_travaillees AND ABS(c_heures_travaillees) BETWEEN 5 AND 8 THEN heure_travaillee * equivalent_temps_plein ELSE heure_travaillee END,
				heure_payee = CASE WHEN p_heures_payees AND ABS(c_heures_payees) BETWEEN 5 AND 8 THEN heure_payee * equivalent_temps_plein ELSE heure_payee END
			FROM rh.t_rubriques,
				rh.p_contrats_mois
			WHERE rubrique_id = t_rubriques.oid AND
				contrat_mois_id = p_contrats_mois.oid AND
				(
				p_heures_travaillees AND ABS(c_heures_travaillees) BETWEEN 5 AND 8 AND heure_travaillee <> 0 OR  
				p_heures_payees AND ABS(c_heures_payees) BETWEEN 5 AND 8 AND heure_payee <> 0
				) AND
				proratiser_conversion AND
				equivalent_temps_plein <> 1 AND
				equivalent_temps_plein > 0
			;

			]]></sqlcmd>
		</NODE>
        <NODE name="VENTILATION" label="Ventilation analytique Cegi">
                <condition><![CDATA[

                SELECT valeur > 0
                FROM rh.t_divers
                WHERE code = 'CEGI_VENTILATION'
                ;

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

                -- Insertion du Plan Analytique.
                INSERT INTO rh.t_plan_analytique(oid, code, texte)
                    SELECT t_divers.valeur::bigint, 'CEGI', 'Ventilation analytique Cegi'
                    FROM rh.t_divers
                    WHERE 1=1
                        and t_divers.code = 'CEGI_VENTILATION'
                        and t_divers.valeur::bigint not in (select oid from rh.t_plan_analytique)
                ;

                -- Màj des sections analytiques.
                INSERT INTO rh.t_section_analytique(oid, code_original, code, texte, texte_court)
                    SELECT ana_id, ana_id, ana_codana, ana_lib, substr(ana_lib,1,50)
                    FROM prod_cegi.rhp_cmcodesana
                        JOIN rh.t_divers on code = 'CEGI_TPA_ID'
                    where 1=1
                        and ana_id not in (select oid from rh.t_section_analytique group by 1)
                        and case when valeur = '0' then true else tpa_id = valeur end
                    group by 1,2,3,4,5
                ;

                -- Recencement de la ventilation ana.
                DROP TABLE IF EXISTS w_ven
                ;

                CREATE TEMP TABLE w_ven AS
                    with pyperioderep as (
                        select
                            per_id,
                            cnt_id,
                            prep_id,
                            prep_debut::date as date_debut,
                            coalesce(lead(prep_debut) over (partition by per_id, cnt_id order by prep_debut) - '1 day'::interval, '2099-12-31'::date)::date as date_fin
                        from prod_cegi.pyperioderep)
                    , pyrepcnt_x as (
                            select
                                repcompta_id,
                                vent_id,
                                rep_id,
                                pyrepcnt_compta.ana_id,
                                sum(repcompta_taux) as repx_taux
                            from prod_cegi.pyrepcnt_compta
                                join prod_cegi.rhp_cmcodesana on rhp_cmcodesana.ana_id = pyrepcnt_compta.ana_id
                                JOIN rh.t_divers on code = 'CEGI_TPA_ID'
                            where case when valeur = '0' then true else tpa_id = valeur end
                            group by 1,2,3,4
                        UNION ALL
                            select
                                0::bigint as repcompta_id,
                                0::bigint as vent_id,
                                rep_id,
                                pyrepcnt_ana.ana_id,
                                sum(repana_taux) as repx_taux
                            from prod_cegi.pyrepcnt_ana
                                join prod_cegi.rhp_cmcodesana on rhp_cmcodesana.ana_id = pyrepcnt_ana.ana_id
                                JOIN rh.t_divers on code = 'CEGI_TPA_ID'
                            where case when valeur = '0' then true else tpa_id = valeur end
                            group by 1,2,3,4
                        )
                        select 
                            pybulletin.bul_id,
                            t_section_analytique.code as section_analytique_code,
                            t_section_analytique.oid as section_analytique_id,
                            sum(pyreppla_compta.rplacpta_taux / 100.0 * pyrepartition.rep_taux / 100.0) as ratio
                        from pyperioderep
                            join prod_cegi.pycontrat on 1=1
                                and pycontrat.cnt_id = pyperioderep.cnt_id
                                and pycontrat.per_id = pyperioderep.per_id
                            JOIN prod_cegi.pyrepartition ON 1=1
                                AND pyrepartition.prep_id = pyperioderep.prep_id
                                and pyrepartition.rep_taux > 0
                            JOIN pyrepcnt_x ON pyrepcnt_x.rep_id = pyrepartition.rep_id
                            join prod_cegi.pyreppla_compta on pyreppla_compta.repcompta_id = pyrepcnt_x.repcompta_id
                            join prod_cegi.pybulletin on 1=1
                                and pybulletin.cnt_id = pyperioderep.cnt_id
                                and pybulletin.per_id = pyperioderep.per_id
                                and pybulletin.cal_an = pyreppla_compta.cal_an
                                and pybulletin.cal_nperiode = pyreppla_compta.cal_nperiode
                            join rh.t_section_analytique on t_section_analytique.oid = pyreppla_compta.ana_id
                        where pycontrat.cnt_repplanning = 1 -- Case "Autoriser les imapcts de répartition de l'application Planning" cochée.
                        group by 1,2,3
                    UNION
                        select 
                            pybulletin.bul_id,
                            t_section_analytique.code as section_analytique_code,
                            t_section_analytique.oid as section_analytique_id,
                            sum(pyrepcnt_x.repx_taux / 100.0 * pyrepartition.rep_taux / 100.0) as ratio
                        from pyperioderep
                            join prod_cegi.pycontrat on 1=1
                                and pycontrat.cnt_id = pyperioderep.cnt_id
                                and pycontrat.per_id = pyperioderep.per_id
                            JOIN prod_cegi.pyrepartition ON 1=1
                                and pyrepartition.prep_id = pyperioderep.prep_id
                                and pyrepartition.rep_taux > 0
                            JOIN pyrepcnt_x ON pyrepcnt_x.rep_id = pyrepartition.rep_id
                            join prod_cegi.pybulletin on 1=1
                                and pybulletin.cnt_id = pyperioderep.cnt_id
                                and pybulletin.per_id = pyperioderep.per_id
                                and base.cti_overlaps(pybulletin.bul_debutrem::date, pybulletin.bul_finrem::date, pyperioderep.date_debut, pyperioderep.date_fin)
                            join rh.t_section_analytique on t_section_analytique.oid = pyrepcnt_x.ana_id
                        where pycontrat.cnt_repplanning = 0 -- Case "Autoriser les imapcts de répartition de l'application Planning" NON cochée.
                        group by 1,2,3
                ;

                DROP TABLE IF EXISTS w_ven_agg
                ;

                CREATE TEMP TABLE w_ven_agg AS
                    select
                        bul_id,
                        dense_rank() over (order by array_agg(section_analytique_id order by section_analytique_id), array_agg(ratio order by section_analytique_id)) as ventilation_id,
                        array_to_string(array_agg(section_analytique_code||'@'||(round(ratio*100)) order by section_analytique_code), ', ') as ventilation_texte
                    FROM w_ven
                    group by 1
                ;

                -- Récupération des différents schémas/modèles de ventilation.
                TRUNCATE rh.p_ventilation
                ;

                INSERT INTO rh.p_ventilation(oid, code, texte, plan_analytique_id)
                        select
                            ventilation_id,
                            ventilation_id::text,
                            ventilation_texte,
                            (SELECT valeur::bigint FROM rh.t_divers WHERE code = 'CEGI_VENTILATION')
                        FROM w_ven_agg
                        group by 1,2,3,4
                    UNION ALL
                        SELECT
                            0,
                            'N/R',
                            'Non renseignée',
                            (SELECT valeur::bigint FROM rh.t_divers WHERE code = 'CEGI_VENTILATION')
                ;

                TRUNCATE rh.p_ventilation_section
                ;
                INSERT INTO rh.p_ventilation_section(
                    ventilation_id,
                    section_analytique_id,
                    section_analytique_code,
                    section_analytique_texte,
                    ratio)
                        SELECT
                            ventilation_id,
                            t_section_analytique.oid,
                            t_section_analytique.code,
                            t_section_analytique.texte,
                            ratio
                        from w_ven
                            join w_ven_agg on w_ven_agg.bul_id = w_ven.bul_id
                            JOIN rh.t_section_analytique on t_section_analytique.oid = w_ven.section_analytique_id
                        group by 1,2,3,4,5
                    UNION ALL
                        SELECT
                            0,
                            oid,
                            code,
                            texte,
                            1
                        FROM rh.t_section_analytique
                        WHERE oid = 0
                ;

                UPDATE rh.p_historique_paie SET
                    ventilation_1_id = subq.ventilation_id
                FROM (
                    select
                        p_historique_paie.oid,
                        coalesce(ventilation_id, 0) as ventilation_id
                    from rh.p_historique_paie
                        left join w_ven_agg on w_ven_agg.bul_id = p_historique_paie.code_original
                    group by 1,2) as subq
                WHERE p_historique_paie.oid = subq.oid
                ;
				
				-- Dans certains cas, le ratio n'est pas égal à 1, on ajuste
				UPDATE rh.p_ventilation_section
				SET ratio = ratio*ratio_coef
				FROM
				(
				SELECT ventilation_id, 1/sum(ratio) AS ratio_coef
				FROM rh.p_ventilation_section
				GROUP BY 1
				HAVING round(sum(ratio),0) <> 1 AND SUM(ratio) > 0
				) subview
				WHERE p_ventilation_section.ventilation_id = subview.ventilation_id
				;

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