<?xml version="1.0" encoding="ISO-8859-15"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
	
		<NODE label="Complément prod_adp">
			<condition><![CDATA[
            ]]></condition>
			<sqlcmd><![CDATA[
			
				-- Cas ADP Charmilles dans lequel il manque des champs / ELSAN ( periode de paie, numero contrat, dates et nombres mal formes)
				UPDATE prod_adp.etablissement SET
					CODEETAB = VALTABCODEARGUMENT,
					SOCJURID = CODEETAB
				WHERE CODEETAB IS DISTINCT FROM VALTABCODEARGUMENT
				;

				ALTER TABLE prod_adp.etaciv ADD COLUMN IF NOT EXISTS ETCDNA date;

				UPDATE prod_adp.etaciv SET
					ETCDNA = COALESCE(ETCDNA,base.cti_to_date(IN_ETCDNA))
				;
					
				ALTER TABLE prod_adp.contrat ADD COLUMN IF NOT EXISTS H1DDEB date;
				ALTER TABLE prod_adp.contrat ADD COLUMN IF NOT EXISTS H1DFIN date;
				ALTER TABLE prod_adp.contrat ADD COLUMN IF NOT EXISTS CNHMENS numeric;
				ALTER TABLE prod_adp.contrat ADD COLUMN IF NOT EXISTS ACT_MOTIF_DEBUT text;
				ALTER TABLE prod_adp.contrat ADD COLUMN IF NOT EXISTS ACT_MOTIF_FIN text;

				UPDATE prod_adp.contrat SET
					IN_CNHMENS = replace(IN_CNHMENS,'Â ','')
				;

				UPDATE prod_adp.contrat SET
					H1DDEB = COALESCE(H1DDEB,base.cti_to_date(IN_H1DDEB)),
					H1DFIN = COALESCE(H1DFIN,base.cti_to_date(IN_H1DFIN)),
					CNHMENS = COALESCE(CNHMENS,base.cti_to_number(IN_CNHMENS))
				;


				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS PERPAIE integer;
				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS H1DDEB date;
				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS H1DFIN date;
				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS RESBRU numeric;
				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS REHPAY numeric;
				ALTER TABLE prod_adp.gremme ADD COLUMN IF NOT EXISTS REHTRA numeric;

				UPDATE prod_adp.gremme SET
					IN_RESBRU = replace(IN_RESBRU,'Â ','')
				;

				UPDATE prod_adp.gremme SET
					H1DDEB = COALESCE(H1DDEB,base.cti_to_date(IN_H1DDEB)),
					H1DFIN = COALESCE(H1DFIN,base.cti_to_date(IN_H1DFIN)),
					RESBRU = COALESCE(RESBRU,base.cti_to_number(IN_RESBRU)),
					REHPAY = COALESCE(REHPAY,base.cti_to_number(IN_REHPAY)),
					REHTRA = COALESCE(REHTRA,base.cti_to_number(IN_REHTRA))
				;

				UPDATE prod_adp.gremme
				SET PERPAIE = to_char(H1DDEB,'YYYYMM')::numeric
				WHERE PERPAIE IS NULL
				;

				ALTER TABLE prod_adp.admchs ADD COLUMN IF NOT EXISTS ADC_ADDDEB date;
				ALTER TABLE prod_adp.admchs ADD COLUMN IF NOT EXISTS ADC_ADDCOT date;
				ALTER TABLE prod_adp.admchs ADD COLUMN IF NOT EXISTS ADC_ADDEC date;
				ALTER TABLE prod_adp.admchs ADD COLUMN IF NOT EXISTS ADC_ADDDEBPENS date;

				UPDATE prod_adp.admchs SET
					ADC_ADDDEB = COALESCE(ADC_ADDDEB,base.cti_to_date(IN_ADC_ADDDEB)),
					ADC_ADDCOT = COALESCE(ADC_ADDCOT,base.cti_to_date(IN_ADC_ADDCOT)),
					ADC_ADDDEBPENS = COALESCE(ADC_ADDDEBPENS,base.cti_to_date(IN_ADC_ADDDEBPENS))
				;

				ALTER TABLE prod_adp.positp ADD COLUMN IF NOT EXISTS H1DDEB date;
				ALTER TABLE prod_adp.positp ADD COLUMN IF NOT EXISTS H1DFIN date;

				UPDATE prod_adp.positp SET
					H1DDEB = COALESCE(H1DDEB,base.cti_to_date(IN_H1DDEB)),
					H1DFIN = COALESCE(H1DFIN,base.cti_to_date(IN_H1DFIN))
				;


				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS PERPAIE integer;
				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS RUBDATE date;
				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS PERIODE_AFFECTATION date;
				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS RUBMNT00 numeric;
				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS RUBNB00 numeric;
				ALTER TABLE prod_adp.rubrique ADD COLUMN IF NOT EXISTS RUBTAUX00 numeric;


				UPDATE prod_adp.rubrique SET
					IN_RUBMNT00 = replace(IN_RUBMNT00,'Â ',''),
					IN_RUBNB00 = replace(IN_RUBNB00,'Â ',''),
					IN_RUBTAUX00 = replace(IN_RUBTAUX00,'Â ','')
				 ;

				UPDATE prod_adp.rubrique SET
					RUBDATE = COALESCE(RUBDATE,base.cti_to_date(IN_RUBDATE)),
					PERIODE_AFFECTATION = COALESCE(PERIODE_AFFECTATION,base.cti_to_date(IN_PERIODE_AFFECTATION)),
					RUBMNT00 = COALESCE(RUBMNT00,base.cti_to_number(IN_RUBMNT00)),
					RUBNB00 = COALESCE(RUBNB00,base.cti_to_number(IN_RUBNB00)),
					RUBTAUX00 = COALESCE(RUBTAUX00,base.cti_to_number(IN_RUBTAUX00))
				;

				UPDATE prod_adp.rubrique
				SET PERPAIE = to_char(RUBDATE,'YYYYMM')::numeric
				WHERE PERPAIE IS NULL
				;

				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS H1DDEB date;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS H1DFIN date;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS DEBH2 date;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS FINH2 date;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS FINH2 date;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SACAFFEC03 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SALAFFEC03 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SACAFFEC04 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SALAFFEC04 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SACAFFEC05 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SALAFFEC05 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SACAFFEC06 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SALAFFEC06 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SACAFFEC07 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SALAFFEC07 text;
				ALTER TABLE prod_adp.sadmin ADD COLUMN IF NOT EXISTS SAD_LIB35 text;

				UPDATE prod_adp.sadmin SET
					H1DDEB = COALESCE(H1DDEB,base.cti_to_date(IN_H1DDEB)),
					H1DFIN = COALESCE(H1DFIN,base.cti_to_date(IN_H1DFIN)),
					DEBH2 = COALESCE(DEBH2,base.cti_to_date(IN_DEBH2)),
					FINH2 = COALESCE(FINH2,base.cti_to_date(IN_FINH2))
				;

				ALTER TABLE prod_adp.rgl_pp_tabrub ADD COLUMN IF NOT EXISTS NOORDRE numeric;


				UPDATE prod_adp.rgl_pp_tabrub SET
					IN_NOORDRE = replace(IN_NOORDRE,'Â ','')
				;

				UPDATE prod_adp.rgl_pp_tabrub SET
					NOORDRE = COALESCE(NOORDRE,base.cti_to_number(IN_NOORDRE))
				;
			
			]]></sqlcmd>
		</NODE>

        <NODE label="Complément prod_adp - Almaviva">
			<condition><![CDATA[

				SELECT current_database() = 'icti_528'
				;

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

				UPDATE prod_adp.gremme
				SET GRMCOD06 = '03301' 
				WHERE GRMCOD06 = '01101'
				;
			
            ]]></sqlcmd>
        </NODE>
			

        <NODE label="Pré-traitements">
			<sqlcmd><![CDATA[
			
            DROP TABLE IF EXISTS w_ets
            ;

            CREATE TEMP TABLE w_ets AS
                SELECT
                    socjurid as ent_code,
                    max(name) as ent_texte,
                    codeetab as ets_code,
                    max(name) as ets_texte,
					siret  as ets_siret
                FROM prod_adp.etablissement
                WHERE 1!=1
                    OR codeetab			IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs codes établissment.
					OR SIRET			IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs codes établissment.
                    OR left(SIRET,9)	IN (SELECT rhp_in('siren')) -- et/ou soit un ou plusieurs codes établissment.
                GROUP BY 1,3,5
            ;

            -- Màj des Entreprises.
			INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court, siren)
                select
                    ent_code,
                    ent_code,
                    ent_texte, 
					substr(ent_texte, 1, 50),
					substr(ets_siret, 1, 9)
                from w_ets
                where ent_code NOT IN (SELECT code_original FROM rh.t_entreprises WHERE code_original IS NOT NULL)
                group by 1,2,3,4,5
			;
			
			with ent as (
                SELECT
                    t_entreprises.oid,
                    substr(ets_siret, 1, 9) AS siren
                FROM rh.t_entreprises
                    JOIN w_ets on w_ets.ent_code = t_entreprises.code_original)
            UPDATE rh.t_entreprises
			SET siren = ent.siren
			FROM ent
            WHERE 1=1
                and t_entreprises.oid = ent.oid
                and t_entreprises.siren IS DISTINCT FROM ent.siren
			;

			-- Màj des Etablissements.
			INSERT INTO rh.t_etablissements(code_original, code, texte, texte_court, entreprise_id, siret)
                SELECT
					ets_code,
                    ets_code,
                    ets_texte, 
					substr(ets_texte, 1, 50),
					t_entreprises.oid,
					ets_siret
				FROM w_ets
                    JOIN rh.t_entreprises ON t_entreprises.code_original = w_ets.ent_code
				where ets_code NOT IN (SELECT code_original FROM rh.t_etablissements WHERE code_original IS NOT NULL)
                group by 1,2,3,4,5,6
			;
			
			 with eta as (
				SELECT
                    t_etablissements.oid,
                    ets_siret as siret
                FROM rh.t_etablissements
                    JOIN w_ets on ets_code = t_etablissements.code_original)
            UPDATE rh.t_etablissements
			SET siret = eta.siret
			FROM eta
            WHERE 1=1
                and t_etablissements.oid = eta.oid
                and t_etablissements.siret IS DISTINCT FROM eta.siret 
			;

            DROP TABLE IF EXISTS w_sal_ets
            ;

            CREATE TEMP TABLE w_sal_ets AS
                SELECT
                    etcmat as etcmat,
                    grmcod06 as ets
                FROM prod_adp.gremme
                    join w_ets on w_ets.ets_code = grmcod06
                WHERE COALESCE(H1DFIN, '2099-12-31') >= rhp('rhprovider_start')::date
                group by 1,2
            ;

			]]></sqlcmd>
		</NODE>
		<NODE name="INIT" type="common" />
	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
		<NODE label="Récupération des bulletins">
			<sqlcmd><![CDATA[

            DROP SEQUENCE IF EXISTS s_bulletins
            ;

            CREATE SEQUENCE s_bulletins
            ;

            ALTER SEQUENCE s_bulletins RESTART WITH 1
            ;

            -- Récupération des bulletins. Ne semble servir uniquement pour trouver l'affectation de l'établissement
            DROP TABLE IF EXISTS w_bulletins
            ;

            CREATE TEMP TABLE w_bulletins AS (
                with gestion_multi_bulletins AS (
                -- Gestion des cas de plusieurs bulletins sur le même mois
                SELECT 
                    etcmat AS matricule,
                    gremme.perpaie::int AS mois,
                    MIN(gremme.h1ddeb::date) AS date_debut,
                    MAX(coalesce(gremme.h1dfin::date, base.cti_last_day(gremme.h1ddeb))) AS date_fin,
                    (MIN(array[to_char(gremme.h1ddeb::date, 'YYYYMMDD')::int, t_etablissements.entreprise_id::int]))[2] AS entreprise_id,
                    (MIN(array[to_char(gremme.h1ddeb::date, 'YYYYMMDD')::int, t_etablissements.oid::int]))[2] AS etablissement_id,
                    SUM(gremme.resbru) AS resbru,
                    SUM(gremme.rehpay) AS rehpay,
                    SUM(gremme.rehtra) AS rehtra
                FROM prod_adp.gremme
                JOIN rh.t_etablissements ON t_etablissements.code_original = gremme.grmcod06
                WHERE 
                    COALESCE(H1DFIN, '2099-12-31') >= rhp('rhprovider_start')::date
                    AND t_etablissements.oid != 0
                GROUP BY 1,2
                )
                SELECT
                    nextval('s_bulletins'::regclass) AS bulletin_id,
                    entreprise_id,
                    etablissement_id,
		            'BULLETIN' || '-' || matricule || '-' || mois  AS numero_bulletin,
                    date_debut,
                    date_fin,
                    mois,
                    matricule,
                    resbru,
                    rehpay,
                    rehtra,
                    0::bigint AS affectation_contrat_mois_id,
                    0::int AS est_hors_periode_contrat
                FROM gestion_multi_bulletins
            )
            ;

			]]></sqlcmd>
		</NODE>
        <NODE label="Récupération des contrats">
			<sqlcmd><![CDATA[

            DROP SEQUENCE IF EXISTS s_contrats
            ;

            CREATE SEQUENCE s_contrats;

            ALTER SEQUENCE s_contrats RESTART WITH 1
            ;

            -- Récupération des contrats
            DROP TABLE IF EXISTS w_contrats
            ;

            CREATE TEMP TABLE w_contrats AS (
                with dernier_bulletin_salaries AS (
                    SELECT 
                        matricule,
                        MAX(date_fin) AS date_fin_dernier_bulletin
                    FROM w_bulletins
                    GROUP BY 1
                )
                SELECT 
                    nextval('s_contrats'::regclass) AS contrat_id,
                    contrat.etcmat AS matricule,
                    0::bigint AS salarie_id,
                    H1DDEB AS date_debut_contrat,
                    COALESCE(H1DFIN, '2099-12-31') AS date_fin_contrat,
                    'CONTRAT' || '-' || contrat.ETCMAT || '-' || to_char(row_number() OVER (PARTITION BY contrat.ETCMAT ORDER BY H1DDEB), 'FM99900') AS numero_contrat,
                    'CONTRAT' || '-' || contrat.ETCMAT || '-' || to_char(row_number() OVER (PARTITION BY contrat.ETCMAT ORDER BY H1DDEB),'FM99900') AS code_original,
                    CASE 
                        WHEN t_divers.valeur = '0' THEN cnlcnt -- Nature du contrat
                        WHEN t_divers.valeur = '1' THEN lnmcnt -- Type du contrat
                    END AS type_contrat,
                    0::bigint AS etablissement_id,
                    0::bigint AS entreprise_id,
                    0::bigint AS profil_id,
                    cnhmens AS heures_theoriques,
                    coalesce(case when cnhmens >= 151.67 then 'TC' else 'TP' end||round(cnhmens::numeric, 2)::text, chr(1)||'*') AS type_temps_travail,
                    coalesce(nullif(cnhmens / 151.67, 0), 1.0) AS etp_theorique,
                    0::int AS est_hors_periode,
                    dernier_bulletin_salaries.date_fin_dernier_bulletin
                FROM prod_adp.contrat
                JOIN w_sal_ets ON w_sal_ets.etcmat = contrat.etcmat -- Limiter la remontée des contrats aux seuls salariés ayant un bulletin
                JOIN rh.t_divers ON code = 'ADP_TYPE_CONTRAT'
                LEFT JOIN dernier_bulletin_salaries ON dernier_bulletin_salaries.matricule = contrat.etcmat
                WHERE (cnlcnt != '' OR lnmcnt != '') -- exclu les contrats "en erreur".
                ORDER BY H1DDEB
            )
            ;

        ]]></sqlcmd>
		</NODE>
        <NODE label="Attribution de l'établissement aux contrats">
			<sqlcmd><![CDATA[

            -- Mise à jour de l'établissement dans les contrats
            -- Si plusieurs contrats sur le même mois.
            UPDATE w_contrats
            SET 
                etablissement_id = w_bulletins.etablissement_id,
                entreprise_id = w_bulletins.entreprise_id
            FROM w_bulletins
            WHERE 
                w_bulletins.matricule = w_contrats.matricule
                AND w_bulletins.date_debut >= w_contrats.date_debut_contrat
                AND w_bulletins.date_fin <= w_contrats.date_fin_contrat
            ;

            -- Si etablissement_id restant à 0, on renseigne le dernier id connu dans les contrats
            UPDATE w_contrats
            SET 
                etablissement_id = subview.etablissement_id,
                entreprise_id = subview.entreprise_id
            FROM 
				(
					SELECT 
						matricule,
						(MAX(array[w_contrats.date_fin_contrat::text, w_contrats.etablissement_id::text]))[2]::int AS etablissement_id,
						(MAX(array[w_contrats.date_fin_contrat::text, w_contrats.entreprise_id::text]))[2]::int AS entreprise_id
					FROM w_contrats
					WHERE etablissement_id <> 0
					GROUP BY 1
				) AS subview
            WHERE
                w_contrats.etablissement_id = 0
                AND w_contrats.matricule = subview.matricule
            ;

			-- Si etablissement_id restant à 0, on renseigne l'établissement le plus récent
            UPDATE w_contrats
            SET 
                etablissement_id = subview.etablissement_id,
                entreprise_id = subview.entreprise_id
            FROM 
				(
					SELECT 
						matricule,
						(MAX(array[w_bulletins.date_fin::text, w_bulletins.etablissement_id::text]))[2]::int AS etablissement_id,
						(MAX(array[w_bulletins.date_fin::text, w_bulletins.entreprise_id::text]))[2]::int AS entreprise_id
					FROM w_bulletins
					GROUP BY 1
				) AS subview
            WHERE
                w_contrats.etablissement_id = 0
                AND w_contrats.matricule = subview.matricule
            ;

            ANALYZE w_contrats
            ;

            -- Mise à jours des bulletins hors période de contrat
            UPDATE w_bulletins
            SET est_hors_periode_contrat = 1
            FROM 
                (
                    SELECT 
                        w_bulletins.matricule,
                        w_bulletins.bulletin_id
                    FROM w_bulletins
                    LEFT JOIN w_contrats ON w_contrats.matricule = w_bulletins.matricule AND w_bulletins.date_debut BETWEEN w_contrats.date_debut_contrat AND w_contrats.date_fin_contrat
                    WHERE w_contrats.contrat_id IS NULL
                ) AS subview
            WHERE 
                w_bulletins.matricule = subview.matricule
                AND w_bulletins.bulletin_id = subview.bulletin_id
            ;

            ANALYZE w_bulletins
            ;

            ]]></sqlcmd>
		</NODE>
        <NODE label="Création des contrats mois">
			<sqlcmd><![CDATA[

            DROP SEQUENCE IF EXISTS s_contrats_mois
            ;

            CREATE SEQUENCE s_contrats_mois;

            ALTER SEQUENCE s_contrats_mois RESTART WITH 1
            ;

            -- Ventilation (découpage) des contrats par mois
            DROP TABLE IF EXISTS w_contrats_mois
            ;

            CREATE TEMP TABLE w_contrats_mois AS (
                with date_debut_mois AS (
                    SELECT
                        *,
                        generate_series(
                            date_trunc('month', date_debut_contrat),
                            CASE 
                                WHEN date_fin_contrat = '2099-12-31' AND w_contrats.date_fin_dernier_bulletin IS NOT NULL THEN w_contrats.date_fin_dernier_bulletin
                                WHEN date_fin_contrat = '2099-12-31' AND w_contrats.date_fin_dernier_bulletin IS NULL THEN NOW() 
                                ELSE date_fin_contrat END, 
                            '1 month'
                        )::date AS date_debut_mois
                    FROM w_contrats
                    WINDOW w AS (PARTITION BY matricule ORDER BY date_debut_contrat DESC)
                )
                SELECT
                    nextval('s_contrats_mois'::regclass) AS contrat_mois_id,
                    row_number() over (PARTITION BY matricule, date_debut_mois) AS nombre_contrats_mois,
                    *,
                    CASE 
                        WHEN to_char(date_debut_mois,'YYYYMM')::numeric = to_char(date_debut_contrat,'YYYYMM')::numeric
                        THEN date_debut_contrat
                        ELSE date_debut_mois
                    END AS date_debut_contrat_mois,
                    CASE
                        WHEN to_char(base.cti_last_day(date_debut_mois),'YYYYMM')::numeric = to_char(date_fin_contrat,'YYYYMM')::numeric
                        THEN date_fin_contrat
                        ELSE base.cti_last_day(date_debut_mois)
                    END AS date_fin_contrat_mois,
                    CASE 
                        WHEN to_char(date_debut_mois,'YYYYMM')::numeric = to_char(date_debut_contrat,'YYYYMM')::numeric
                        THEN to_char(date_debut_contrat,'YYYYMM')::numeric 
                        ELSE to_char(date_debut_mois,'YYYYMM')::numeric  
                    END AS mois_activite,
                    chr(1)||'*' AS motif_debut_code,
                    chr(1)||'*' AS motif_debut_texte,
                    chr(1)||'*' AS motif_fin_code,
                    chr(1)||'*' AS motif_fin_texte,
                    chr(1)||'*' AS categorie_socio_professionnelle_code,
                    chr(1)||'*' AS categorie_socio_professionnelle_texte,
                    chr(1)||'*' AS qualification_code,
                    chr(1)||'*' AS qualification_texte,
                    chr(1)||'*' AS service_code,
                    chr(1)||'*' AS service_texte,
                    chr(1)||'*' AS code_emploi_code,
                    chr(1)||'*' AS code_emploi_texte,
                    chr(1)||'*' AS grille_code,
                    chr(1)||'*' AS grille_texte,
                    chr(1)||'*' AS grille_groupe_code,
                    chr(1)||'*' AS grille_groupe_texte,
                    chr(1)||'*' AS statut_code,
                    chr(1)||'*' AS statut_texte,
                    COALESCE(type_contrat, chr(1)||'*') AS type_contrat_code,
                    COALESCE(type_contrat, chr(1)||'*') AS type_contrat_texte,
                    COALESCE(type_temps_travail, chr(1)||'*') AS type_temps_travail_code,
                    COALESCE(type_temps_travail, chr(1)||'*') AS type_temps_travail_texte,
                    chr(1)||'*' AS specialite_code,
                    chr(1)||'*' AS groupe_cotisant_code,
                    chr(1)||'*' AS section_analytique_code,
                    chr(1)||'*' AS section_analytique_paie_code,
                    chr(1)||'*' AS societe_interim_code,
                    chr(1)||'*' AS type_horaire_code,
                    chr(1)||'*' AS cadre_emploi_code,         -- public
                    chr(1)||'*' AS categorie_conge_code,      -- public
                    chr(1)||'*' AS categorie_statutaire_code, -- public
                    chr(1)||'*' AS commission_paritaire_code, -- public
                    chr(1)||'*' AS compte_salarie_code,       -- public
                    chr(1)||'*' AS filiere_code,              -- public
                    chr(1)||'*' AS lettre_budgetaire_code,    -- public
                    chr(1)||'*' AS unite_fonctionnelle_code   -- public
                FROM date_debut_mois
                WHERE date_debut_mois >= (rhp('rhprovider_start')::date - interval '2 YEAR')
            )
            ;

            ]]></sqlcmd>
		</NODE>
        <NODE label="Récupération des informations administratives des salariés">
			<sqlcmd><![CDATA[

            -- Récupération des informations positp des salariés
            DROP TABLE IF EXISTS w_infos_positp
            ;

            CREATE TEMP TABLE w_infos_positp AS (
                SELECT 
                    row_number() OVER() AS id,
                    w_contrats_mois.contrat_mois_id,
                    positp.h1ddeb AS date_debut,
                    positp.h1dfin AS date_fin,
                    LOWER(positp.pocins) AS categorie_socio_professionnelle_code,
                    positp.pocemp AS qualification_code,
                    positp.polemp AS qualification_texte,
                    positp.pocatp AS statut_code,
                    positp.polcatp AS statut_texte,
                    COALESCE(positp.pocemp,'') AS code_emploi_code,
                    COALESCE(positp.polemp,'') AS code_emploi_texte
                FROM w_contrats_mois
                JOIN prod_adp.positp ON positp.etcmat = w_contrats_mois.matricule 
                    AND base.cti_overlaps(w_contrats_mois.date_debut_contrat_mois, w_contrats_mois.date_fin_contrat_mois, positp.h1ddeb, COALESCE(positp.h1dfin, '2099-12-31'::date))
            )
            ;

            -- Récupération des informations administratives des salariés
            DROP TABLE IF EXISTS w_infos_administratives
            ;

            CREATE TEMP TABLE w_infos_administratives AS (
                SELECT 
                    row_number() OVER() AS id,
                    w_contrats_mois.contrat_mois_id,
                    sadmin.h1ddeb AS date_debut,
                    sadmin.h1dfin AS date_fin,
                    sadmin.sadcfinctr AS motif_fin_code,
                    sadmin.sadlfinctr AS motif_fin_texte,
                    CASE 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFF' THEN sadmin.SACAFF 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFFEC01' THEN sadmin.SACAFFEC01 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFFEC02' THEN sadmin.SACAFFEC02
                        ELSE COALESCE(sadmin.sacaffec05,'') 
                    END AS service_code,
                    CASE 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFF' THEN sadmin.SALAFF 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFFEC01' THEN sadmin.SALAFFEC01 
                        WHEN UPPER(COALESCE(t_divers.valeur,'')) = 'SACAFFEC02' THEN sadmin.SALAFFEC02
                        ELSE COALESCE(sadmin.salaffec05,'') 
                    END AS service_texte,
                    COALESCE(sadmin.sacaffec04,'') AS grille_groupe_code,
                    COALESCE(sadmin.salaffec04,'') AS grille_groupe_texte
                FROM w_contrats_mois
                JOIN prod_adp.sadmin ON sadmin.etcmat = w_contrats_mois.matricule 
                    AND base.cti_overlaps(w_contrats_mois.date_debut_contrat_mois, w_contrats_mois.date_fin_contrat_mois, sadmin.h1ddeb, COALESCE(sadmin.h1dfin, '2099-12-31'::date))
                JOIN rh.t_divers ON t_divers.code = 'ADP_SERVICE_COLUMN'
            )
            ;

            -- Récupération pour chaque contrat_mois des informations les plus récentes du salarié
            DROP TABLE IF EXISTS dernieres_infos_contrat_mois
            ;

            CREATE TEMP TABLE dernieres_infos_contrat_mois AS 
                with dernieres_infos_par_contrat_mois AS (
                    SELECT
                        w_contrats_mois.contrat_mois_id,
                        (MAX(ARRAY[EXTRACT(EPOCH FROM w_infos_positp.date_debut), w_infos_positp.id]))[2] AS dernier_infos_positp_id,
                        (MAX(ARRAY[EXTRACT(EPOCH FROM w_infos_administratives.date_debut), w_infos_administratives.id]))[2] AS dernier_infos_administratives_id
                    FROM w_contrats_mois
                    LEFT JOIN w_infos_positp ON w_infos_positp.contrat_mois_id = w_contrats_mois.contrat_mois_id
                    LEFT JOIN w_infos_administratives ON w_infos_administratives.contrat_mois_id = w_contrats_mois.contrat_mois_id
                    GROUP BY 1
                )
                SELECT 
                    w_contrats_mois.contrat_mois_id,
                    w_infos_positp.categorie_socio_professionnelle_code,
                    w_infos_administratives.motif_fin_code,
                    w_infos_administratives.motif_fin_texte,
                    w_infos_positp.qualification_code,
                    w_infos_positp.qualification_texte,
                    w_infos_positp.statut_code,
                    w_infos_positp.statut_texte,
                    w_infos_administratives.service_code,
                    w_infos_administratives.service_texte,
                    w_infos_administratives.grille_groupe_code,
                    w_infos_administratives.grille_groupe_texte,
                    w_infos_positp.code_emploi_code,
                    w_infos_positp.code_emploi_texte
                FROM w_contrats_mois
                LEFT JOIN dernieres_infos_par_contrat_mois ON dernieres_infos_par_contrat_mois.contrat_mois_id = w_contrats_mois.contrat_mois_id
                LEFT JOIN w_infos_positp ON w_infos_positp.contrat_mois_id = w_contrats_mois.contrat_mois_id 
                    AND w_infos_positp.id = dernieres_infos_par_contrat_mois.dernier_infos_positp_id
                LEFT JOIN w_infos_administratives ON w_infos_administratives.contrat_mois_id = w_infos_administratives.contrat_mois_id 
                    AND w_infos_administratives.id = dernieres_infos_par_contrat_mois.dernier_infos_administratives_id
            ;

            -- Mise à jour des éléments de positp et sadmin sur les contrats_mois
            UPDATE w_contrats_mois
            SET 
                motif_debut_code = COALESCE(chr(1)||'*', chr(1)||'*'),
                motif_debut_texte = COALESCE(chr(1)||'*', chr(1)||'*'),
                motif_fin_code = COALESCE(dernieres_infos_contrat_mois.motif_fin_code, chr(1)||'*'),
                motif_fin_texte = COALESCE(dernieres_infos_contrat_mois.motif_fin_texte, chr(1)||'*'),
                categorie_socio_professionnelle_code = COALESCE(dernieres_infos_contrat_mois.categorie_socio_professionnelle_code, chr(1)||'*'),
                categorie_socio_professionnelle_texte = COALESCE(dernieres_infos_contrat_mois.categorie_socio_professionnelle_code, chr(1)||'*'),
                qualification_code = COALESCE(dernieres_infos_contrat_mois.qualification_code, chr(1)||'*'),
                qualification_texte = COALESCE(dernieres_infos_contrat_mois.qualification_texte, chr(1)||'*'),
                service_code = COALESCE(dernieres_infos_contrat_mois.service_code, chr(1)||'*'),
                service_texte = COALESCE(dernieres_infos_contrat_mois.service_texte, chr(1)||'*'),
                code_emploi_code = COALESCE(dernieres_infos_contrat_mois.code_emploi_code, chr(1)||'*'),
                code_emploi_texte = COALESCE(dernieres_infos_contrat_mois.code_emploi_texte, chr(1)||'*'),
                grille_groupe_code = COALESCE(dernieres_infos_contrat_mois.grille_groupe_code, chr(1)||'*'),
                grille_groupe_texte = COALESCE(dernieres_infos_contrat_mois.grille_groupe_texte, chr(1)||'*'),
                statut_code = COALESCE(dernieres_infos_contrat_mois.statut_code, chr(1)||'*'),
                statut_texte = COALESCE(dernieres_infos_contrat_mois.statut_texte, chr(1)||'*')
            FROM dernieres_infos_contrat_mois
            WHERE dernieres_infos_contrat_mois.contrat_mois_id = w_contrats_mois.contrat_mois_id
            ;

            ANALYZE w_contrats_mois
            ;

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

            -- Création des profils
            DROP TABLE IF EXISTS w_profils
            ;

            CREATE TEMP TABLE w_profils AS (
                SELECT 
                    0::bigint AS profil_id, -- Mis à jour dans le SHARE
                    motif_debut_code AS motif_debut_code_original,
                    motif_fin_code AS motif_fin_code_original,
                    categorie_socio_professionnelle_code AS categorie_socio_professionnelle_code_original,
                    qualification_code AS qualification_code_original,
                    service_code AS service_code_original,
                    code_emploi_code AS code_emploi_code_original,
                    grille_code AS grille_code_original,
                    grille_groupe_code AS grille_groupe_code_original,
                    specialite_code AS specialite_code_original,
                    groupe_cotisant_code AS groupe_cotisant_code_original,
                    section_analytique_code AS section_analytique_code_original,
                    section_analytique_paie_code AS section_analytique_paie_code_original,
                    societe_interim_code AS societe_interim_code_original,
                    type_horaire_code AS type_horaire_code_original,
                    statut_code AS statut_code_original,
                    type_contrat_code AS type_contrat_code_original,
                    type_temps_travail_code AS type_temps_travail_code_original,
                    cadre_emploi_code AS cadre_emploi_code_original,
                    categorie_conge_code AS categorie_conge_code_original,
                    categorie_conge_code AS categorie_statutaire_code_original,
                    commission_paritaire_code AS commission_paritaire_code_original,
                    compte_salarie_code AS compte_salarie_code_original,
                    filiere_code AS filiere_code_original,
                    lettre_budgetaire_code AS lettre_budgetaire_code_original,
                    unite_fonctionnelle_code AS unite_fonctionnelle_code_original
                FROM w_contrats_mois
                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
            )	
            ;

            ]]></sqlcmd>
		</NODE>
        <NODE name="PROFIL" type="common" />
        <NODE label="Attribution profil_id aux contrats_mois">
			<sqlcmd><![CDATA[

            -- Mise à jour du profil_id dans w_contrats_mois
            UPDATE w_contrats_mois
            SET profil_id = p_profils.oid
            FROM rh.p_profils
            WHERE 1=1
                AND p_profils.cadre_emploi_code_original                    = w_contrats_mois.cadre_emploi_code
                AND p_profils.categorie_conge_code_original                 = w_contrats_mois.categorie_conge_code
                AND p_profils.categorie_socio_professionnelle_code_original = w_contrats_mois.categorie_socio_professionnelle_code
                AND p_profils.categorie_statutaire_code_original            = w_contrats_mois.categorie_statutaire_code
                AND p_profils.code_emploi_code_original                     = w_contrats_mois.code_emploi_code
                AND p_profils.commission_paritaire_code_original            = w_contrats_mois.commission_paritaire_code
                AND p_profils.compte_salarie_code_original                  = w_contrats_mois.compte_salarie_code
                AND p_profils.filiere_code_original                         = w_contrats_mois.filiere_code
                AND p_profils.grille_code_original                          = w_contrats_mois.grille_code
                AND p_profils.grille_groupe_code_original                   = w_contrats_mois.grille_groupe_code
                AND p_profils.groupe_cotisant_code_original                 = w_contrats_mois.groupe_cotisant_code
                AND p_profils.lettre_budgetaire_code_original               = w_contrats_mois.lettre_budgetaire_code
                AND p_profils.motif_debut_code_original                     = w_contrats_mois.motif_debut_code
                AND p_profils.motif_fin_code_original                       = w_contrats_mois.motif_fin_code
                AND p_profils.qualification_code_original                   = w_contrats_mois.qualification_code
                AND p_profils.section_analytique_code_original              = w_contrats_mois.section_analytique_code
                AND p_profils.section_analytique_paie_code_original         = w_contrats_mois.section_analytique_paie_code
                AND p_profils.service_code_original                         = w_contrats_mois.service_code
                AND p_profils.societe_interim_code_original                 = w_contrats_mois.societe_interim_code
                AND p_profils.specialite_code_original                      = w_contrats_mois.specialite_code
                AND p_profils.statut_code_original                          = w_contrats_mois.statut_code
                AND p_profils.type_contrat_code_original                    = w_contrats_mois.type_contrat_code
                AND p_profils.type_horaire_code_original                    = w_contrats_mois.type_horaire_code
                AND p_profils.type_temps_travail_code_original              = w_contrats_mois.type_temps_travail_code
                AND p_profils.unite_fonctionnelle_code_original             = w_contrats_mois.unite_fonctionnelle_code
            ;
            ]]></sqlcmd>
		</NODE>
        <NODE label="Gestion des bulletins hors période de contrat">
			<sqlcmd><![CDATA[

            -- Création de contrats_mois fictifs avec les données de profil du plus proche contrat_mois existant
            INSERT INTO w_contrats_mois  (matricule, date_debut_contrat_mois, date_fin_contrat_mois, mois_activite, contrat_mois_id, nombre_contrats_mois, contrat_id, etablissement_id, entreprise_id, profil_id, est_hors_periode)
                SELECT
                    w_bulletins.matricule,
                    w_bulletins.date_debut,
                    w_bulletins.date_fin,
                    to_char(w_bulletins.date_debut,'YYYYMM')::numeric AS mois_activite,
                    nextval('s_contrats_mois'::regclass) AS contrat_mois_id,
                    row_number() over (PARTITION BY w_bulletins.matricule, to_char(w_bulletins.date_debut,'YYYYMM')) AS nombre_contrats_mois,
                    (MAX(array[to_char(w_contrats_mois.date_fin_contrat_mois, 'YYYYMMDD')::int, w_contrats_mois.contrat_id::int]))[2] AS contrat_id,
                    (MAX(array[to_char(w_contrats_mois.date_fin_contrat_mois, 'YYYYMMDD')::int, w_contrats_mois.etablissement_id::int]))[2] AS etablissement_id,
                    (MAX(array[to_char(w_contrats_mois.date_fin_contrat_mois, 'YYYYMMDD')::int, w_contrats_mois.entreprise_id::int]))[2] AS entreprise_id,
                    (MAX(array[to_char(w_contrats_mois.date_fin_contrat_mois, 'YYYYMMDD')::int, w_contrats_mois.profil_id::int]))[2] AS profil_id,
                    1 AS est_hors_periode
                FROM w_bulletins
                JOIN w_contrats_mois AS w_contrats_mois ON w_contrats_mois.matricule = w_bulletins.matricule AND w_contrats_mois.date_fin_contrat_mois < w_bulletins.date_debut
                WHERE w_bulletins.est_hors_periode_contrat = 1
                GROUP BY 1,2,3,4
            ;

            -- Affectation au premier contrat_mois_id sur le mois au bulletin concerné
			UPDATE w_bulletins
			SET affectation_contrat_mois_id = w_contrats_mois.contrat_mois_id
			FROM w_contrats_mois
			WHERE 
				w_contrats_mois.matricule = w_bulletins.matricule 
				AND w_contrats_mois.mois_activite = w_bulletins.mois 
				AND w_contrats_mois.nombre_contrats_mois = 1
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Salariés">
			<sqlcmd><![CDATA[

			DROP TABLE IF EXISTS w_salaries
			;

			CREATE TEMP TABLE w_salaries AS
				SELECT
                    rhp('finess') AS finess,
                    etaciv.etcmat AS matricule,
                    etaciv.etcmat AS matricule_planning,
                    etaciv.etcmat AS code,
                    etaciv.etcmat AS code_original,
                    etaciv.etnss AS nir,
                    COALESCE(w_contrats_mois.entreprise_id, 0) AS entreprise_id,
                    etaciv.etcnom AS nom,
                    etaciv.etcnjf AS nom_naissance,
                    etaciv.etcpre AS prenom,
                    etaciv.etcdna::date AS date_naissance,
                    etaciv.etcsex AS sexe,
                    coalesce(t_nationalites.oid, 0) AS nationalite_id, -- etcnat, etlnat
                    coalesce(t_codes_postaux.oid,0) AS code_postal_id,
                    coalesce(t_situations_famille.oid, 0) AS situation_famille_id, -- etlsfa, etcsfa
                    etaciv.nvoie AS adresse1,
                    etaciv.lvoie AS adresse2,
                    COALESCE((MAX(ARRAY[EXTRACT(EPOCH FROM w_contrats_mois.date_debut_contrat_mois), w_contrats_mois.profil_id]))[2], 0) AS profil_id,
                    MAX(w_contrats_mois.date_debut_contrat) AS date_debut,
                    MAX(w_contrats_mois.date_fin_contrat) AS date_fin,
                    MIN(w_contrats_mois.date_debut_contrat) AS date_entree_ets,
                    MAX(w_contrats_mois.date_fin_contrat) AS date_sortie_ets,
                    -- Champs dédiés au public.
                    null::date AS date_entree_fp,
                    null::date AS date_entree_fph,
                    0 AS no_adeli,
                    0 AS code_cotisation_id,
                    0 AS matricule_retraite
                FROM prod_adp.etaciv
                    LEFT JOIN w_contrats_mois ON w_contrats_mois.matricule = etaciv.etcmat
                    LEFT join rh.t_nationalites ON t_nationalites.code_original = etaciv.etcnat
                    LEFT join rh.t_situations_famille ON t_situations_famille.code_original = etaciv.etcsfa
                    LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = etaciv.etcpst
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
			;

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

            UPDATE w_contrats_mois SET
                salarie_id = p_salaries.oid
            FROM rh.p_salaries
            WHERE w_contrats_mois.matricule = p_salaries.matricule
            ;

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

            TRUNCATE rh.p_contrats
            ;
			
			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

            WITH dernier_profil_id AS (
                SELECT
                    contrat_id,
                    (MAX(ARRAY[EXTRACT(EPOCH FROM date_fin_contrat_mois), profil_id]))[2] AS profil_id
                FROM w_contrats_mois
                GROUP BY 1
            )
			INSERT INTO rh.p_contrats(
                oid,
                salarie_id,
                date_debut,
                date_fin,
                numero_contrat,
                code_original,
                etablissement_id,
                profil_id)
				SELECT
                    w_contrats.contrat_id,
					p_salaries.oid AS salarie_id,
					w_contrats.date_debut_contrat,
					w_contrats.date_fin_contrat,
					w_contrats.numero_contrat,
					w_contrats.code_original,
					w_contrats.etablissement_id,
                    dernier_profil_id.profil_id
				FROM w_contrats
                    JOIN rh.p_salaries ON p_salaries.code_original = w_contrats.matricule
                    JOIN dernier_profil_id on dernier_profil_id.contrat_id = w_contrats.contrat_id
			;

            TRUNCATE rh.p_contrats_mois
            ;
		
			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

            INSERT INTO rh.p_contrats_mois(
                oid,
                salarie_id,
                contrat_id,
                profil_id,
                code_original,
                mois_activite,
                date_debut,
                date_fin,
                nombre_entrees,
                nombre_departs,
                nombre_debut_contrat,
                nombre_fin_contrat,
                present_debut_mois,
                present_fin_mois,
                equivalent_temps_plein,
                age_jours,
                etablissement_id)
                SELECT
                    w_contrats_mois.contrat_mois_id,
                    w_contrats_mois.salarie_id,
                    w_contrats_mois.contrat_id,
                    w_contrats_mois.profil_id,
                    w_contrats_mois.salarie_id || ' - ' || w_contrats_mois.contrat_mois_id,
                    w_contrats_mois.mois_activite,
                    w_contrats_mois.date_debut_contrat_mois,
                    w_contrats_mois.date_fin_contrat_mois,
                    CASE WHEN p_salaries.date_entree_ets BETWEEN w_contrats_mois.date_debut_contrat_mois AND w_contrats_mois.date_fin_contrat_mois THEN 1 ELSE 0 END AS nombre_entrees,
					CASE WHEN p_salaries.date_sortie_ets BETWEEN w_contrats_mois.date_debut_contrat_mois AND w_contrats_mois.date_fin_contrat_mois THEN 1 ELSE 0 END AS nombre_departs,
                    CASE WHEN p_contrats.date_debut BETWEEN date_debut_contrat_mois AND w_contrats_mois.date_fin_contrat_mois THEN 1 ELSE 0 END AS nombre_debut_contrat,
					CASE WHEN p_contrats.date_fin BETWEEN date_debut_contrat_mois AND w_contrats_mois.date_fin_contrat_mois THEN 1 ELSE 0 END AS nombre_fin_contrat,
                    case when w_contrats_mois.date_debut_contrat > base.cti_first_day(w_contrats_mois.date_debut_contrat_mois) then 0 else 1 end AS present_debut_mois,
                    case when w_contrats_mois.date_fin_contrat < base.cti_last_day(w_contrats_mois.date_debut_contrat_mois) then 0 else 1 end AS present_fin_mois,
                    w_contrats_mois.etp_theorique AS equivalent_temps_plein,
                    w_contrats_mois.date_fin_contrat_mois - coalesce(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
                    w_contrats_mois.etablissement_id
                FROM rh.p_contrats
                    JOIN w_contrats_mois on w_contrats_mois.contrat_id = p_contrats.oid
                    JOIN rh.p_salaries on p_salaries.oid = w_contrats_mois.salarie_id
            ;

			]]></sqlcmd>
		</NODE>
        <NODE label="Mise à jour des informations permanentes">
			<sqlcmd><![CDATA[

			-- Màj des catégories socio-professionnelles
			INSERT INTO rh.t_categories_socio_professionnelle (code_original, code, texte, texte_court)
				SELECT categorie_socio_professionnelle_code, categorie_socio_professionnelle_code, categorie_socio_professionnelle_code, substr(categorie_socio_professionnelle_code, 1, 50)
				FROM w_contrats_mois
				WHERE 
                    categorie_socio_professionnelle_code <> chr(1)||'*'
					AND categorie_socio_professionnelle_code NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des motifs de début de contrat.
			INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
				SELECT substr(md5(act_motif_debut), 1, 5), substr(md5(act_motif_debut), 1, 5), act_motif_debut, substr(max(act_motif_debut),1,50)
				FROM prod_adp.contrat
				WHERE substr(md5(act_motif_debut), 1, 5) NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3
				ORDER BY 2
			;

			-- Màj des motifs de fin de contrat.
			INSERT INTO rh.t_motifs_fin_contrat(code_original, code, texte, texte_court)
				SELECT motif_fin_code, motif_fin_code, MAX(motif_fin_texte), substr(MAX(motif_fin_texte), 1, 50) 
				FROM w_contrats_mois
				WHERE 
                    motif_fin_code <> chr(1)||'*'
                    AND motif_fin_code NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat WHERE code_original IS NOT NULL)
				GROUP BY 1,2
			;

			-- Màj des nationalités.
			INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
				SELECT etcnat, max(etlnat), max(substr(etlnat,1,50)), etcnat
				FROM prod_adp.etaciv
				WHERE etcnat NOT IN (SELECT code_original FROM rh.t_nationalites WHERE code_original IS NOT NULL)
				GROUP BY 1,4
			;

			-- Màj des qualifications
			INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
				SELECT qualification_code, qualification_code, max(qualification_texte), substr(max(qualification_texte), 1, 50)
                FROM w_contrats_mois
                WHERE 
                    qualification_code <> chr(1)||'*'
                    AND qualification_code NOT IN (SELECT code_original FROM rh.t_qualifications WHERE code_original IS NOT NULL)
                GROUP BY 1,2
			;

            -- Màj des rubriques
            INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
                select rubid, rubid, libelle, substr(libelle, 1, 50), noordre
                from prod_adp.rgl_pp_tabrub
                WHERE rubid NOT IN (SELECT code_original FROM rh.t_rubriques WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4,5
            ;

			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(code_original, code, texte_court, texte)
				SELECT etcsfa, etcsfa, MAX(substr(etlsfa,1,50)), MAX(etlsfa)
				FROM prod_adp.etaciv
				WHERE etcsfa NOT IN (SELECT code_original FROM rh.t_situations_famille WHERE code_original IS NOT NULL)
				GROUP BY 1,2
			;

			-- Màj des types de contrat
			INSERT INTO rh.t_types_contrat(code_original, code, texte, texte_court)
				SELECT type_contrat_code, type_contrat_code, type_contrat_texte, substr(type_contrat_texte, 1, 50)
				FROM w_contrats_mois
				WHERE 
                    type_contrat_code <> chr(1)||'*'
                    AND type_contrat_code NOT IN (SELECT code_original FROM rh.t_types_contrat WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des statuts
			INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
				SELECT statut_code, statut_code, statut_texte, substr(statut_texte, 1, 50)
				FROM w_contrats_mois
				WHERE 
                    statut_code <> chr(1)||'*'
                    AND statut_code NOT IN (SELECT code_original FROM rh.t_statuts WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
			;

			-- Màj des types de temps de travail
			INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
                SELECT
                    CASE WHEN heures_theoriques >= 151.67 THEN 'TC' ELSE 'TP' END||ROUND(heures_theoriques::numeric, 2)::text,
                    CASE WHEN heures_theoriques >= 151.67 THEN 'TC' ELSE 'TP' END||ROUND(heures_theoriques::numeric, 2)::text,
                    CASE WHEN heures_theoriques >= 151.67 THEN 'Temps Complet ' ELSE 'Temps Partiel ' end||round(heures_theoriques::numeric, 2)::text,
                    CASE WHEN heures_theoriques >= 151.67 THEN 'TC ' ELSE 'TP ' END||ROUND(heures_theoriques::numeric, 2)::text
                FROM w_contrats_mois
                WHERE CASE WHEN heures_theoriques >= 151.67 THEN 'TC' ELSE 'TP' END||ROUND(heures_theoriques::numeric, 2)::text NOT IN (SELECT code_original FROM rh.t_types_temps_travail WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4
			;

			-- Màj des services
			INSERT INTO rh.t_services(code_original, code, texte, texte_court)
				SELECT service_code, service_code, max(service_texte), max(substr(service_texte, 1, 50))
                FROM w_contrats_mois
                WHERE 
                    service_code <> chr(1)||'*'
                    AND service_code NOT IN (SELECT code_original FROM rh.t_services WHERE code_original IS NOT NULL)
                GROUP BY 1,2
			;

			-- Màj des codes emploi. avec LTR ADP ELSAN.
            INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
                SELECT code_emploi_code, code_emploi_code, max(code_emploi_texte), max(substr(code_emploi_texte, 1, 50))
                FROM w_contrats_mois
                WHERE 
                    code_emploi_code <> chr(1)||'*'
                    AND code_emploi_code NOT IN (SELECT code_original FROM rh.t_codes_emploi WHERE code_original IS NOT NULL)
                GROUP BY 1,2
            ;

            -- Màj des groupes de grilles
            INSERT INTO rh.t_grilles_groupes(code_original, code, texte, texte_court)
                SELECT grille_groupe_code, grille_groupe_code, max(grille_groupe_texte), max(substr(grille_groupe_texte, 1, 50))
                FROM w_contrats_mois
                WHERE
                    grille_groupe_code <> chr(1)||'*' 
                    AND grille_groupe_code NOT IN (SELECT code_original FROM rh.t_grilles_groupes WHERE code_original IS NOT NULL)
                GROUP BY 1,2
            ;

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

            -- Pré-paramétrage automatique des rubriques (au mieux).
            -- Cette requéte n'intervient pas sur les rubriques paramétrées à la main.
            -- s_* (source_) :
            --   - 0 = nombre
            --   - 1 = base
            --   - 2 = taux salarial
            --   - 3 = montant salarial
            --   - 4 = taux patronal
            --   - 5 = montant patronal
            --   - 6 = montant salarial + montant patronal
            update rh.t_rubriques set
                p_detail = subq.p_detail,
                p_nombre = subq.p_nombre,
                s_nombre = 0,
                c_nombre = 1,
                p_base = subq.p_base,
                s_base = 1,
                c_base = 1,
                p_heures_contrat = subq.p_heures_contrat,
                s_heures_contrat = 0,
                c_heures_contrat = 1,
                p_heures_payees = subq.p_heures_payees,
                s_heures_payees = 0,
                c_heures_payees = 1,
                p_heures_travaillees = subq.p_heures_travaillees,
                s_heures_travaillees = 0,
                c_heures_travaillees = 1,
                p_masse_salariale = subq.p_masse_salariale,
                s_masse_salariale = case when subq.p_cotisation_patronale or subq.p_od_net_patronale then 5 else 3 end,
                c_masse_salariale = 1,
                p_brut = subq.p_brut,
                s_brut = 3,
                c_brut = 1,
                p_avantage_nature = subq.p_avantage_nature,
                s_avantage_nature = 3,
                c_avantage_nature = 1,
                p_frais_imposables = subq.p_frais_imposables,
                s_frais_imposables = 3,
                c_frais_imposables = 1,
                p_cotisation_salarie = subq.p_cotisation_salarie,
                s_cotisation_salarie = 3,
                c_cotisation_salarie = 1,
                p_cotisation_patronale = subq.p_cotisation_patronale,
                s_cotisation_patronale = 5,
                c_cotisation_patronale = 1,
                p_od_net_salarie = subq.p_od_net_salarie,
                s_od_net_salarie = 3,
                c_od_net_salarie = 1,
                p_od_net_patronale = subq.p_od_net_patronale,
                s_od_net_patronale = 5,
                c_od_net_patronale = 1,
                p_net_imposable = subq.p_net_imposable,
                s_net_imposable = 3,
                c_net_imposable = 1,
                p_net_a_payer = subq.p_net_a_payer,
                s_net_a_payer = 3,
                c_net_a_payer = 1
            from (
                select
                    oid,
                    code,
                    typerub = 'P' or (typerub = 'G' AND plage = 'P' and nullif(trim(cvcg), '') is not null and interditdvdr is distinct from 'O') AS p_detail,
                    typerub = 'G' AS p_nombre,
                    typerub in ('P', 'G') AS p_base,
                    false AS p_heures_contrat,
                    false AS p_heures_payees,
                    false AS p_heures_travaillees,
                    (typerub = 'P' AND plage = 'B') OR (typerub = 'G' AND plage = 'P' and nullif(trim(cvcg), '') is not null and interditdvdr is distinct from 'O') AS p_masse_salariale,
                    typerub = 'P' AND plage = 'B' AS p_brut,
                    false AS p_avantage_nature,
                    false AS p_frais_imposables,
                    -- typerub = 'P' AND plage in ('C', 'D', 'R', 'S') as p_cotisation_salarie,
                    typerub = 'P' AND plage||cotisation in ('C1', 'S1') as p_cotisation_salarie,
                    typerub = 'G' AND plage = 'P' and nullif(trim(cvcg), '') is not null and interditdvdr is distinct from 'O' as p_cotisation_patronale,
                    --typerub = 'P' AND plage = 'I' as p_od_net_salarie,
                    typerub = 'P' AND plage||cotisation in ('C0', 'I0', 'D0', 'R0', 'R1') as p_od_net_salarie,
                    false AS p_od_net_patronale,
                    typerub = 'P' AND plage||cotisation in ('B0', 'C1', 'S1') AS p_net_imposable,
                    typerub = 'P' AND plage in ('B', 'C', 'D', 'I', 'R', 'S') AS p_net_a_payer
                from prod_adp.rgl_pp_tabrub
                    join rh.t_rubriques on t_rubriques.code_original = rgl_pp_tabrub.rubid
                where 1=1
                    and t_rubriques.oid != 0
                    and t_rubriques.code not ilike 'C%'
                ) as subq
            where 1=1
                and t_rubriques.oid = subq.oid
                and NOT t_rubriques.user_modified
            ;

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

            DROP TABLE IF EXISTS w_hp
            ;

            CREATE TEMP TABLE w_hp AS
                SELECT
                    w_contrats_mois.contrat_mois_id AS bul_code,
                    w_contrats_mois.contrat_mois_id,
                    w_contrats_mois.contrat_id,
                    w_contrats_mois.salarie_id,
                    w_bulletins.date_debut,
                    w_bulletins.date_fin,
                    0 AS profil_id,
                    rubrique.etcmat AS matricule,
                    rubrique.rubdate::date AS date_paie,
                    rubrique.perpaie::int AS mois_paie,
                    t_rubriques.oid AS rubrique_id,
                    t_rubriques.p_detail,
                    t_rubriques.p_cumul,
                    t_rubriques.c_base
                        * case when @t_rubriques.c_base != 1 then coalesce(case when proratiser_conversion then etp_theorique else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_base THEN (CASE s_base
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                            END) else 0 end AS base,
                    t_rubriques.c_nombre
                        * case when @t_rubriques.c_nombre != 1 then coalesce(case when proratiser_conversion then etp_theorique else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_nombre THEN (CASE s_nombre
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                            END) else 0 end AS nombre,
                    t_rubriques.c_heures_contrat
                        * case when @t_rubriques.c_heures_contrat != 1 then coalesce(case when proratiser_conversion then etp_theorique else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_contrat
                            then (CASE s_heures_contrat
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                            END)
                            else 0 end
                        AS heure_contrat,
                    t_rubriques.c_heures_payees
                        * case when @t_rubriques.c_heures_payees != 1 then coalesce(case when proratiser_conversion then etp_theorique else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_payees
                            then (CASE s_heures_payees
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                            END) else 0 end AS heure_payee,
                    t_rubriques.c_heures_travaillees
                        * case when @t_rubriques.c_heures_travaillees != 1 then coalesce(case when proratiser_conversion then etp_theorique else 1.0 end, 1.0) else 1.0 end
                        * CASE WHEN p_heures_travaillees
                            then (CASE s_heures_travaillees
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END) else 0 end AS heure_travaillee,
                    t_rubriques.c_masse_salariale
                        * (CASE WHEN p_masse_salariale      THEN
                            (CASE s_masse_salariale
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            else 0 end) AS masse_salariale,
                    t_rubriques.c_brut
                        * (CASE WHEN p_brut                 THEN
                            (CASE s_brut
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            else 0 end) AS montant_brut,
                    t_rubriques.c_frais_imposables
                        * (case when p_frais_imposables     then
                            (CASE s_frais_imposables
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            else 0 end) AS montant_frais_imposables,
                    t_rubriques.coefficient_txs * (case when p_cotisation_salarie then rubrique.rubtaux00 else 0 end) AS taux_sal,
                    t_rubriques.c_cotisation_salarie
                        * (case when p_cotisation_salarie   then
                            (CASE s_cotisation_salarie
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_salWHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            else 0 end) AS montant_cot_sal,
                    t_rubriques.coefficient_txp * (case when p_cotisation_patronale then rubrique.rubtaux00 else 0 end) AS taux_pat,
                    t_rubriques.c_cotisation_patronale
                        * (case when p_cotisation_patronale then
                            (CASE s_cotisation_patronale
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_salWHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            else 0 end) AS montant_cot_pat,
                    t_rubriques.c_od_net_salarie
                        * (CASE WHEN p_od_net_salarie       THEN
                            (CASE s_od_net_salarie
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_salWHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS od_net,
                    t_rubriques.c_od_net_patronale
                        * (CASE WHEN p_od_net_patronale     THEN
                            (CASE s_od_net_patronale
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_salWHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS od_net_p,
                    t_rubriques.c_avantage_nature
                        * (CASE WHEN p_avantage_nature      THEN
                            (CASE s_avantage_nature
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_salWHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS avt_nat,
                    t_rubriques.c_net_imposable
                        * (CASE WHEN p_net_imposable        THEN
                            (CASE s_net_imposable
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS net_imposable,
                    t_rubriques.c_net_a_payer
                        * (CASE WHEN p_net_a_payer          THEN
                            (CASE s_net_a_payer
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS net_a_payer,
                        t_rubriques.c_nombre_provisions
                        * (CASE WHEN p_nombre_provisions THEN
                            (CASE s_nombre_provisions
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS nombre_provisions,
                        t_rubriques.c_montant_provisions
                        * (CASE WHEN p_montant_provisions THEN
                            (CASE s_montant_provisions
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS montant_provisions,
                        t_rubriques.c_masse_salariale_provisionnee
                        * (CASE WHEN p_masse_salariale_provisionnee THEN
                            (CASE s_masse_salariale_provisionnee
                                WHEN 0 THEN rubrique.rubmnt00
                                WHEN 1 THEN rubrique.rubnb00
                                WHEN 2 THEN rubrique.rubtaux00
                                WHEN 3 THEN rubrique.rubmnt00
                                --WHEN 4 THEN rubrique.tx_pat
                                WHEN 5 THEN rubrique.rubmnt00
                                --WHEN 6 THEN rubrique.mt_sal + rubrique.mt_pat
                                --WHEN 7 THEN rubrique.mt_sal - rubrique.mt_pat
                                --WHEN 8 THEN rubrique.mt_pat - rubrique.mt_sal
                                END)
                            ELSE 0 END) AS masse_salariale_provisionnee
                FROM prod_adp.rubrique
                    JOIN rh.t_rubriques ON t_rubriques.code_original = rubrique.rubcode
                    JOIN w_bulletins ON w_bulletins.matricule = rubrique.etcmat AND w_bulletins.mois = rubrique.PERPAIE
                    JOIN w_contrats_mois ON w_contrats_mois.contrat_mois_id = w_bulletins.affectation_contrat_mois_id
                WHERE 1=1
                    AND rubrique.perpaie::int >= rhp('rhprovider_start')::date
                    -- Filtrer les lignes générées systématiquement tous les mois par Sage pour chaque salarié méme s'il n'y a rien.
                    AND (false
                        OR p_nombre
                        OR p_base
                        OR p_heures_contrat
                        OR p_heures_payees
                        OR p_heures_travaillees
                        OR p_masse_salariale
                        OR p_brut
                        OR p_avantage_nature
                        OR p_frais_imposables
                        OR p_cotisation_salarie
                        OR p_cotisation_patronale
                        OR p_od_net_salarie
                        OR p_od_net_patronale
                        OR p_net_imposable
                        OR p_net_a_payer
                        OR p_nombre_provisions
                        OR p_montant_provisions
                        OR p_masse_salariale_provisionnee)
            ;

			]]></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
                    entreprise_id,
                    etablissement_id,
                    mois,
                    count(DISTINCT matricule),
                    sum(resbru),
                    sum(rehpay)
                FROM w_bulletins
                group by 1,2,3
            ;

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

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

            TRUNCATE rh.p_historique_paie
            ;
			
			ALTER SEQUENCE rh.s_historique_paie RESTART WITH 1
			;

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

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

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

            CREATE TEMP TABLE w_cumul AS
                SELECT
                    bool_or(p_cumul and p_heures_contrat) as total_h_contrat,
                    bool_or(p_cumul and p_heures_travaillees) as total_h_travaillees,
                    bool_or(p_cumul and p_heures_payees) as total_h_payees,
                    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_cotisation_salarie) as total_cot_sal,
                    bool_or(p_cumul and p_cotisation_patronale) as total_cot_pat,
                    bool_or(p_cumul and p_od_net_salarie) as total_od_net,
                    bool_or(p_cumul and p_net_imposable) as total_imposable,
                    bool_or(p_cumul and p_net_a_payer) as total_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
            ;

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

            CREATE TEMP TABLE w_totaux AS
                WITH all_buls as ( -- Permet de s'assurer que l'on a bien TOUS les totaux même ceux qui n'existent pas (cas des suspensions de contrat rub. 0595)
                    SELECT
                        w_hp.bul_code,
                        w_hp.matricule,
                        w_hp.date_paie,
                        w_hp.mois_paie
                    FROM w_hp
                    WHERE p_detail
                    GROUP BY 1,2,3,4
                )
                SELECT
                    all_buls.bul_code as code_original,
                    all_buls.matricule,
                    all_buls.date_paie as date,
                    all_buls.mois_paie,
                    coalesce(sum(case when p_cumul then heure_contrat else 0 end), 0) AS hcum_heures_contrat,
                    coalesce(sum(case when p_cumul then heure_payee else 0 end), 0) AS hcum_heures_payees,
                    coalesce(sum(case when p_cumul then heure_travaillee else 0 end), 0) AS hcum_heures_travaillees,
                    coalesce(round(sum(case when p_cumul then masse_salariale else 0 end), 2), 0) AS hcum_masse_salariale,
                    coalesce(round(sum(case when p_cumul then montant_brut else 0 end), 2), 0) AS hcum_brut,
                    coalesce(round(sum(case when p_cumul then avt_nat else 0 end), 2), 0) AS hcum_avantage_nature,
                    0::numeric AS hcum_frais_imposables,
                    coalesce(round(sum(case when p_cumul then montant_cot_sal else 0 end), 2), 0) AS hcum_cotisation_salarie,
                    coalesce(round(sum(case when p_cumul then montant_cot_pat else 0 end), 2), 0) AS hcum_cotisation_patronale,
                    coalesce(round(sum(case when p_cumul then od_net else 0 end), 2), 0) AS hcum_od_net_salarie,
                    coalesce(round(sum(case when p_cumul then net_imposable else 0 end), 2), 0) AS hcum_net_imposable_salarie,
                    coalesce(round(sum(case when p_cumul then net_a_payer else 0 end), 2), 0) AS hcum_net_a_payer_salarie,
                    coalesce(round(sum(case when p_cumul then nombre_provisions else 0 end), 2), 0) AS hcum_nombre_provisions,
                    coalesce(round(sum(case when p_cumul then montant_provisions else 0 end), 2), 0) AS hcum_montant_provisions,
                    coalesce(round(sum(case when p_cumul then masse_salariale_provisionnee else 0 end), 2), 0) AS hcum_masse_salariale_provisionnee
                FROM all_buls
                    left join w_hp on true
                        and w_hp.bul_code = all_buls.bul_code
                        and w_hp.p_cumul
                GROUP BY 1,2,3,4
            ;

            -- Insérer pour chaque bulletin une ligne qui va faire le compte avec le total (rubrique 'C000' nommée 'Ecart cumulé')
            INSERT INTO rh.p_historique_paie (
                code_original,
                age_id,
                contrat_id,
                contrat_mois_id,
                date_debut,
                date_fin,
                date_paie,
                mois_activite,
                mois_paie,
                base,
                nombre,
                heure_contrat,
                heure_payee,
                heure_travaillee,
                montant_avantage_nature,
                montant_brut,
                montant_masse_salariale,
                montant_cotisation_patronale,
                montant_cotisation_salarie,
                montant_frais_imposables,
                montant_net_a_payer_salarie,
                montant_net_imposable_salarie,
                montant_od_net_salarie,
                organisme_cotisation_id,
                profil_id,
                rubrique_id,
                compte_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie,
                nombre_provisions,
                montant_provisions,
                montant_masse_salariale_provisionnee)
                SELECT
                    subq.code_original,
                    subq.age_id,
                    subq.contrat_id,
                    subq.contrat_mois_id,
                    subq.date_debut,
                    subq.date_fin,
                    subq.date_paie,
                    subq.mois_activite,
                    subq.mois_paie,
                    0 AS base,
                    0 AS nombre,
                    case when total_h_contrat then COALESCE(hcum_heures_contrat, 0) - subq.heure_contrat else 0.0 end AS heure_contrat,
                    case when total_h_payees then COALESCE(hcum_heures_payees,0) - subq.heure_payee else 0.0 end AS heure_payee,
                    case when total_h_travaillees then COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee else 0.0 end AS heure_travaillee,
                    case when total_avantage_nature then COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature else 0.0 end AS montant_avantage_nature,
                    case when total_brut then COALESCE(hcum_brut,0) - subq.montant_brut else 0.0 end AS montant_brut,
                    case when total_masse_salariale then COALESCE(hcum_masse_salariale, 0) - subq.montant_masse_salariale else 0.0 end AS montant_masse_salariale,
                    case when total_cot_pat then COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale else 0.0 end AS montant_cotisation_patronale,
                    case when total_cot_sal then COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie else 0.0 end AS montant_cotisation_salarie,
                    0 AS montant_frais_imposables,
                    case when total_payer then COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie else 0.0 end AS montant_net_a_payer_salarie,
                    case when total_imposable then COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie else 0.0 end AS montant_net_imposable_salarie,
                    case when total_imposable then COALESCE(hcum_od_net_salarie,0) - subq.montant_od_net_salarie else 0.0 end AS montant_od_net_salarie,
                    subq.organisme_cotisation_id AS organisme_cotisation_id,
                    subq.profil_id AS profil_id,
                    (SELECT oid FROM rh.t_rubriques WHERE code = 'C000') AS rubrique_id,
                    0 AS compte_id,
                    subq.salarie_id AS salarie_id,
                    0 AS taux_cotisation_patronale,
                    0 AS taux_cotisation_salarie,
                    case when total_nombre_provisions then COALESCE(hcum_nombre_provisions, 0) - subq.nombre_provisions else 0.0 end AS nombre_provisions,
                    case when total_montant_provisions then COALESCE(hcum_montant_provisions, 0) - subq.montant_provisions else 0.0 end AS montant_provisions,
                    case when total_masse_salariale_provisionnee then COALESCE(hcum_masse_salariale_provisionnee, 0) - subq.montant_masse_salariale_provisionnee else 0.0 end AS montant_masse_salariale_provisionnee
                FROM (
                    SELECT
                        p_historique_paie.code_original,
                        p_historique_paie.age_id,
                        p_historique_paie.contrat_id,
                        p_historique_paie.contrat_mois_id,
                        p_historique_paie.date_debut,
                        p_historique_paie.date_fin,
                        p_historique_paie.date_paie,
                        p_historique_paie.mois_activite,
                        p_historique_paie.mois_paie,
                        0 AS base,
                        0 AS nombre,
                        sum(heure_contrat) AS heure_contrat,
                        sum(heure_payee) AS heure_payee,
                        sum(heure_travaillee) AS heure_travaillee,
                        sum(montant_avantage_nature) AS montant_avantage_nature,
                        sum(montant_brut) AS montant_brut,
                        sum(montant_masse_salariale) AS montant_masse_salariale,
                        sum(montant_cotisation_patronale) AS montant_cotisation_patronale,
                        sum(montant_cotisation_salarie) AS montant_cotisation_salarie,
                        0 AS montant_frais_imposables,
                        sum(montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
                        sum(montant_net_imposable_salarie) AS montant_net_imposable_salarie,
                        sum(montant_od_net_salarie) AS montant_od_net_salarie,
                        p_historique_paie.organisme_cotisation_id,
                        p_historique_paie.profil_id,
                        (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                        p_historique_paie.salarie_id,
                        0 AS taux_cotisation_patronale,
                        0 AS taux_cotisation_salarie,
                        sum(nombre_provisions) AS nombre_provisions,
                        sum(montant_provisions) AS montant_provisions,
                        sum(montant_masse_salariale_provisionnee) AS montant_masse_salariale_provisionnee
                    FROM rh.p_historique_paie
                        JOIN rh.p_salaries ON p_salaries.oid = p_historique_paie.salarie_id
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11, 24,25,26,27,28,29) AS subq
                JOIN w_totaux ON w_totaux.code_original = subq.code_original
                JOIN w_cumul ON true
            WHERE 1!=1
                OR case when total_avantage_nature then COALESCE(hcum_avantage_nature,0) - subq.montant_avantage_nature != 0 else false end
                OR case when total_brut            then COALESCE(hcum_brut,0) - subq.montant_brut != 0 else false end
                OR case when total_masse_salariale then COALESCE(hcum_masse_salariale,0) - subq.montant_masse_salariale != 0 else false end
                OR case when total_payer           then COALESCE(hcum_net_a_payer_salarie,0) - subq.montant_net_a_payer_salarie != 0 else false end
                OR case when total_imposable       then COALESCE(hcum_net_imposable_salarie,0) - subq.montant_net_imposable_salarie != 0 else false end
                OR case when total_od_net          then COALESCE(hcum_od_net_salarie,0) - subq.montant_od_net_salarie != 0 else false end
                OR case when total_cot_pat         then COALESCE(hcum_cotisation_patronale,0) - subq.montant_cotisation_patronale != 0 else false end
                OR case when total_cot_sal         then COALESCE(hcum_cotisation_salarie,0) - subq.montant_cotisation_salarie != 0 else false end
                OR case when total_h_contrat       then COALESCE(hcum_heures_contrat, 0) - subq.heure_contrat != 0 else false end
                OR case when total_h_payees        then COALESCE(hcum_heures_payees,0) - subq.heure_payee != 0 else false end
                OR case when total_h_travaillees   then COALESCE(hcum_heures_travaillees,0) - subq.heure_travaillee != 0 else false end
                OR case when total_nombre_provisions   then COALESCE(hcum_nombre_provisions,0) - subq.heure_travaillee != 0 else false end
                OR case when total_montant_provisions   then COALESCE(hcum_montant_provisions,0) - subq.heure_travaillee != 0 else false end
                OR case when total_masse_salariale_provisionnee   then COALESCE(hcum_masse_salariale_provisionnee,0) - subq.montant_masse_salariale_provisionnee != 0 else false end
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Ventilation des profils">
			<sqlcmd><![CDATA[

			-- Alimentation des profils simultanés.
			TRUNCATE rh.p_profil_contrat_mois
			;
			
			ALTER SEQUENCE rh.s_profil_contrat_mois RESTART WITH 1
            ;
			
			INSERT INTO rh.p_profil_contrat_mois (
				profil_id,
				contrat_mois_id,
				salarie_id,
				ratio,
				mois)
				SELECT
					p_contrats_mois.profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					1 AS ratio,
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
				GROUP BY 1,2,3,4,5
			;

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

			TRUNCATE rh.p_handicap2
			;
 
			INSERT INTO rh.p_handicap2(
					salarie_id,
					statut_boeth,
					lib_boeth,
					type_reco,
					lib_reco,
					taux_ipp,
					deb_validite,
					fin_validite,
					cat_invalide_pension,
					deb_pension,
					lourd_handicap,
					decision
				)
				SELECT  p_salaries.oid,
					admchs.adc_statutboeth,
					admchs.adc_boethlib1,
					admchs.adc_modcod01,
					admchs.adc_modlib01,
                    coalesce(nullif(replace(admchs.adc_adcipp, ',', '.'), '')::numeric,0),
					admchs.adc_adddeb,
					coalesce(admchs.adc_addcot, '20991231'::date),
					admchs.adc_adcatinvpens,
					admchs.adc_adddebpens,
					admchs.adc_adcotor,
					admchs.adc_addec
				FROM rh.p_salaries
					JOIN prod_adp.admchs ON p_salaries.matricule = admchs.etcmat
				WHERE 1 = 1
					and adc_modcod01 >= 1
				;
			
			]]></sqlcmd>
		</NODE>
        <NODE label="Arrêts de travail">
            <condition><![CDATA[
                    
                -- Si la table prod_adp.absences est présente
                SELECT COUNT(*) = 1
                FROM information_schema.tables
                WHERE table_schema = 'prod_adp' AND table_name = 'absences'
                ;

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

                -- Insertion des motifs d'arrêt de travail
                INSERT INTO rh.t_motifs_arret(code_original, code, texte, texte_court)
                    SELECT code, code, code, substr(code, 1, 50)
                    FROM prod_adp.absences
                    WHERE code NOT IN (SELECT code_original FROM rh.t_motifs_arret)
                    GROUP BY 1,2,3,4
                ;

                DROP TABLE IF EXISTS w_arrets
                ;

                CREATE TEMP TABLE w_arrets AS
                    SELECT 
                        absences.etcmat AS matricule,
                        to_char(absences.in_h1ddeb::date, 'YYYYMM')::numeric AS mois_activite,
                        absences.in_h1ddeb AS date_debut,
                        absences.in_h1dfin AS date_fin,
                        (absences.in_h1dfin::date + '1 day'::interval)::date AS date_reprise,
                        absences.code AS code_arret,
                        ((absences.in_h1dfin - absences.in_h1ddeb) + 1)::numeric AS nb_jours,
                        (((absences.in_h1dfin - absences.in_h1ddeb) + 1) *  7)::numeric AS nb_heures
                    FROM prod_adp.absences
                ;

                TRUNCATE rh.p_arrets_travail
                ;

                ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
                ;

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

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

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

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

            ]]></sqlcmd>
        </NODE>
	</NODE>
	<NODE name="POST" label="POST-TRAITEMENTS">
		<NODE name="DIVERS" type="common"/>
		<NODE label="Fusion salaries en double">
            <sqlcmd><![CDATA[

                DROP TABLE IF EXISTS w_map_doublons
                ;
                
                CREATE TEMP TABLE w_map_doublons AS
                SELECT 
                    p_salaries.oid AS from_oid, subview.to_oid
                FROM rh.p_salaries
                JOIN
                (
                    SELECT nir, 
                        (MAX(ARRAY[date_fin::text, oid::text]))[2]::bigint AS to_oid
                    FROM rh.p_salaries
                    JOIN rh.t_divers ON t_divers.code = 'ADP_FUSION_STRATEGIE'
                    WHERE t_divers.valeur = '2'
                    GROUP BY 1
                    HAVING count(*) > 1
                ) subview
                ON p_salaries.nir = subview.nir
                WHERE p_salaries.oid <> subview.to_oid
                ;

                ANALYSE w_map_doublons
                ;
                
                UPDATE rh.p_accident_travail
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;
                
                UPDATE rh.p_arrets_travail
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;
                
                UPDATE rh.p_arrets_travail_mois
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;

                UPDATE rh.p_contrats
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;

                UPDATE rh.p_contrats_mois
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;

                UPDATE rh.p_handicap
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;
                
                UPDATE rh.p_handicap2
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;
                
                UPDATE rh.p_historique_paie
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;

                UPDATE rh.p_profil_contrat_mois
                SET salarie_id = to_oid
                FROM w_map_doublons
                WHERE salarie_id = from_oid
                ;

                DELETE FROM rh.p_salaries
                USING w_map_doublons
                WHERE oid = from_oid
                ;
            
            ]]></sqlcmd>
        </NODE>
		<NODE name="POST" type="common"/>
	</NODE>
	<NODE name="VACUUM" label="REORGANISATION BASE DE DONNEES">
		<NODE name="VACUUM" type="common" />
	</NODE>
	<NODE name="RAZ" label="RAZ BASE">
		<NODE name="RAZ" type="common" />
	</NODE>
	<NODE name="RAZ_ALL" label="RAZ ALL">
		<NODE name="RAZ_ALL" type="common" />
	</NODE>
</ROOT>
