<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
		<NODE name="INIT" type="common" />
		<NODE label="Mise à jour des informations permanentes">
			<sqlcmd><![CDATA[
			
			-- Entreprises et etablissements 
			DROP TABLE IF EXISTS w_entreprises_select;
			CREATE TEMP TABLE w_entreprises_select AS
				SELECT J0CENT AS XXCENT
				FROM prod_shs.rhlibH_J0P01
				WHERE 1=1
					AND J0DFPA >= to_char(rhp('rhprovider_start')::date, 'YYYY')
					AND J0CENT IN (select substr(column2, 1, 3)::numeric from rhp where column1 = 'entreprise')
			GROUP BY 1;
			
			CREATE INDEX w_entreprises_select_i1 ON w_entreprises_select USING btree(XXCENT)
			;

			DROP TABLE IF EXISTS w_etablissements_select;
			CREATE TEMP TABLE w_etablissements_select AS
			SELECT J0CENT AS XXCENT, J0CETS AS XXCETS
			FROM prod_shs.rhlibH_J0P01
			WHERE 1=1
                AND J0DFPA >= to_char(rhp('rhprovider_start')::date, 'YYYY')
				AND (1!=1
					OR J0CENT IN (select column2::numeric from rhp where column1 = 'entreprise')
					OR to_char(J0CENT,'FM000') || to_char(J0CETS,'FM000') IN (select column2::numeric from rhp where column1 = 'entreprise'))
			GROUP BY 1,2;
			
			CREATE INDEX w_etablissements_select_i1 ON w_etablissements_select USING btree(XXCETS)
			;

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

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

			-- Màj des Depts.

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

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

			-- Màj des Entreprises
			INSERT INTO rh.t_entreprises(code, texte, texte_court, code_original, siren)
				SELECT 
					to_char(F0CENT,'FM000'), 
					F0RSOC, 
					F0NOM, 
					to_char(F0CENT,'FM000'),
					substring(f1csir,1,9)
				FROM prod_shs.rhlib_F0P01
					JOIN w_entreprises_select ON XXCENT = F0CENT
					LEFT JOIN rh.t_entreprises ON code_original = to_char(F0CENT,'FM000')
					JOIN prod_shs.rhlib_F1P01 ON to_char(F1CENT,'FM000') = to_char(F0CENT,'FM000')
				WHERE 1=1
					AND code_original IS NULL
				GROUP BY 1,2,3,4,5
			;
			
			UPDATE rh.t_entreprises
			SET code = code_original
			WHERE code <> code_original
			;
			
			with ent as (
                SELECT
                    t_entreprises.oid,
                    substring(f1csir,1,9) AS siren
                FROM rh.t_entreprises
					JOIN prod_shs.rhlib_F1P01 ON to_char(F1CENT,'FM000') = 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, texte, texte_court, code_original, entreprise_id,siret)
				SELECT 
					to_char(F1CETS,'FM000'),
					F1NOM,
					F1NOM,
					to_char(F1CENT,'FM000')||to_char(F1CETS,'FM000'),
					t_entreprises.oid,
					f1csir
				FROM prod_shs.rhlib_F1P01
					JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS
					JOIN rh.t_entreprises ON t_entreprises.code_original = lpad(F1CENT, 3, '0')
					LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = (to_char(F1CENT,'FM000')||to_char(F1CETS,'FM000'))
				WHERE 1=1
					AND t_etablissements.code_original IS NULL
			;

 			with eta as (
				SELECT
                    t_etablissements.oid,
                    f1csir as siret
                FROM rh.t_etablissements
                    JOIN prod_shs.rhlib_F1P01 on to_char(F1CENT,'FM000')||to_char(F1CETS,'FM000') = 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 
			;

			-- Code avec entreprise si plusieurs entreprises
			UPDATE rh.t_etablissements
			SET code = CASE WHEN (SELECT count(DISTINCT substr(code_original,1,3)) FROM rh.t_etablissements) > 1 THEN substr(code_original,1,3) || '-' ELSE '' END || substr(code_original,4,3)
			WHERE code <> (CASE WHEN (SELECT count(DISTINCT substr(code_original,1,3)) FROM rh.t_etablissements) > 1 THEN substr(code_original,1,3) || '-' ELSE '' END || substr(code_original,4,3))
			;
			
			-- Màj des nationalités
			INSERT INTO rh.t_nationalites(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F3CNAT, F3CNAT, F3CNAT, F3CNAT
				FROM prod_shs.rhlib_F3P01
					LEFT JOIN rh.t_nationalites ON (code_original = F3CNAT)
				WHERE 1=1
					AND F3CNAT <> ''
					AND code_original IS NULL
			;

			-- Màj des situations de famille
			INSERT INTO rh.t_situations_famille(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F3SFAM, F3SFAM, F3SFAM, F3SFAM
				FROM
					prod_shs.rhlib_F3P01
					LEFT JOIN rh.t_situations_famille ON (code_original = F3SFAM)
				WHERE
					F3SFAM <> '' AND code_original IS NULL
			;

			-- Màj des statuts
			DROP TABLE IF EXISTS w_SHS_statuts;
			CREATE TEMP TABLE w_SHS_statuts AS
			SELECT F1CENT AS XXCENT, F1CETS AS XXCETS, F1CST0 AS XXCODO, F1CST0 AS XXCODE, F1LST0 AS XXTEXT
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST0 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST1, F1CST1, F1LST1
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST1 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST2, F1CST2, F1LST2
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST2 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST3, F1CST3, F1LST3
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST3 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST4, F1CST4, F1LST4
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST4 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST5, F1CST5, F1LST5
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST5 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST6, F1CST6, F1LST6
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST6 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST7, F1CST7, F1LST7
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST7 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST8, F1CST8, F1LST8
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST8 <> ''
			UNION
			SELECT F1CENT, F1CETS, F1CST9, F1CST9, F1LST9
			FROM prod_shs.rhlib_F1P01 JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS WHERE F1CST9 <> ''
			;

			SELECT rh.cti_shs_multicode('w_shs_statuts', 'w_cti_statuts')
			;

			INSERT INTO rh.t_statuts(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code), MAX(in_texte), MAX(in_texte), in_code_original
			FROM w_cti_statuts
			LEFT JOIN rh.t_statuts ON t_statuts.code_original = in_code_original
			WHERE t_statuts.code_original IS NULL
			GROUP BY in_code_original
			ORDER BY 1
			;

			UPDATE rh.t_statuts SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_statuts
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;


			-- Màj des types de contrat
			INSERT INTO rh.t_types_contrat(code, texte, texte_court, code_original)
				SELECT
					N0CENR,
					MAX(N0LIBE),
					MAX(N0LIBE),
					N0CENR
				FROM
					prod_shs.rhlib_n0P01
					JOIN w_entreprises_select ON XXCENT = to_number('0' || N0ENTR, '0000')
					LEFT JOIN rh.t_types_contrat ON (code_original = N0CENR)
				WHERE n0ctab = 'TCNT'
				AND N0TYPE = 2
				AND code_original IS NULL
				AND N0CENR <> ''
				GROUP BY 1
			;

			-- Màj des motifs de début de contrat
			INSERT INTO rh.t_motifs_debut_contrat(code, texte, texte_court, code_original)
				SELECT
					N0CENR,
					MAX(N0LIBE),
					MAX(N0LIBE),
					N0CENR
				FROM
					prod_shs.rhlib_n0P01
					JOIN w_entreprises_select ON XXCENT = to_number('0' || N0ENTR, '0000')
					LEFT JOIN rh.t_motifs_debut_contrat ON (code_original = N0CENR)
				WHERE  N0CTAB = 'MOTD'
				AND N0TYPE = '2'
				AND code_original IS NULL
				AND N0CENR <> ''
				GROUP BY 1
			;

			-- Màj des motifs de fin de contrat
			INSERT INTO rh.t_motifs_fin_contrat(code, texte, texte_court, code_original)
				SELECT
					SUBSTR(N0CENR,4,2),
					MAX(N0LIBE),
					MAX(N0LIBE),
					SUBSTR(N0CENR,4,2)
				FROM
					prod_shs.rhlib_n0P01
					JOIN w_entreprises_select ON XXCENT = to_number('0' || N0ENTR, '0000')
					LEFT JOIN rh.t_motifs_fin_contrat ON (code_original = SUBSTR(N0CENR,4,2))
				WHERE  N0CTAB = 'MOTF'
					AND N0TYPE = '2'
					AND code_original IS NULL
					AND N0CENR <> ''
				GROUP BY 1
			;

			-- Màj des qualifications.
			-- Le code original est préfixé par les codes Ent. et Ets. car il peut y avoir collision de code d'un établissement à l'autre.
			DROP TABLE IF EXISTS w_shs_qualifications;
			CREATE TEMP TABLE w_shs_qualifications AS
			SELECT
				G1CENT AS XXCENT,
				G1CETS AS XXCETS,
				G1CQUA AS XXCODO,
				G1CQUA AS XXCODE,
				G1LPAR AS XXTEXT
			FROM prod_shs.rhlib_G1P01
			JOIN w_etablissements_select ON XXCENT = G1CENT AND XXCETS = G1CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_qualifications', 'w_cti_qualifications')
			;
				
			UPDATE w_cti_qualifications
			SET in_code_original = subview.new_in_code_original
			FROM
			(
				SELECT in_code_original,
					MIN(to_char(XXCENT, 'FM000') || to_char(XXCETS, 'FM000') || xxcodo) AS new_in_code_original
				FROM w_cti_qualifications
				GROUP BY 1
			) subview
			WHERE w_cti_qualifications.in_code_original = subview.in_code_original;

			INSERT INTO rh.t_qualifications(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_qualifications
			LEFT JOIN rh.t_qualifications ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_qualifications SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_qualifications
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

            -- Màj des types de temps de travail
            DROP TABLE IF EXISTS w_shs_types_temps_travail
            ;
            CREATE TEMP TABLE w_shs_types_temps_travail AS
                SELECT
                    XXCENT,
                    XXCETS,
                    coalesce(subq.code, N0CENR) AS XXCODO,
                    coalesce(subq.code, N0CENR) AS XXCODE,
                    MAX(N0LIBE)||coalesce(subq.libelle, ''::text) AS XXTEXT
                FROM prod_shs.rhlib_n0P01
                    JOIN w_etablissements_select ON 1=1
                    LEFT JOIN (select
                            F4CTPS,
                            case when F4CTPS IN ('I', 'P') then F4CTPS||trim(to_char(F4NHRE, '000.00')) else F4CTPS end as code,
                            ' ' || F4NHRE::text as libelle,
                            F4CENT,
                            F4CETS
                        from prod_shs.rhlib_F4P01
                            JOIN w_etablissements_select ON 1=1
                                AND XXCENT = F4CENT
                                AND XXCETS = F4CETS
                        WHERE F4CTPS IN ('I', 'P')
                        group by 1,2,3,4,5) as subq on 1=1
                            AND subq.F4CTPS = N0CENR
                            AND subq.F4CENT = XXCENT
                            AND subq.F4CETS = XXCETS
                WHERE 1=1
                    AND N0CTAB = 'TTPS'
                    AND N0TYPE = '2'
                GROUP BY 1,2,3,4, subq.libelle
            ;

            SELECT rh.cti_shs_multicode('w_shs_types_temps_travail', 'w_cti_types_temps_travail')
            ;

            INSERT INTO rh.t_types_temps_travail(code, texte, texte_court, code_original)
                SELECT
                    MAX(in_code),
                    MAX(in_texte),
                    MAX(in_texte),
                    in_code_original
                FROM w_cti_types_temps_travail
                LEFT JOIN rh.t_types_temps_travail ON (code_original = in_code_original)
                WHERE code_original IS NULL
                GROUP BY 4
            ;

            UPDATE rh.t_types_temps_travail SET
                code = in_code,
                texte = in_texte,
                texte_court = in_texte
            FROM w_cti_types_temps_travail
            WHERE 1=1
                AND in_code_original = code_original
                AND (1!=1
                    OR code IS DISTINCT FROM in_code
                    OR texte IS DISTINCT FROM in_texte
                    OR texte_court IS DISTINCT FROM in_texte)
            ;

			-- Màj des catégories socio-professionnelles
			DROP TABLE IF EXISTS w_shs_categories;
			CREATE TEMP TABLE w_shs_categories AS
			SELECT
				G4CENT AS XXCENT,
				G4CETS AS XXCETS,
				G4CCSP AS XXCODO,
				G4CCSP AS XXCODE,
				G4LPAR AS XXTEXT
			FROM prod_shs.rhlib_G4P01
			JOIN w_etablissements_select ON XXCENT = G4CENT AND XXCETS = G4CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_categories', 'w_cti_categories')
			;

			INSERT INTO rh.t_categories_socio_professionnelle(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_categories
			LEFT JOIN rh.t_categories_socio_professionnelle ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_categories_socio_professionnelle SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_categories
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des services
			DROP TABLE IF EXISTS w_shs_services;
			CREATE TEMP TABLE w_shs_services AS
			SELECT
				G2CENT AS XXCENT,
				G2CETS AS XXCETS,
				G2SRVC AS XXCODO,
				G2SRVC AS XXCODE,
				G2LPAR AS XXTEXT
			FROM prod_shs.rhlib_G2P01
			JOIN w_etablissements_select ON XXCENT = G2CENT AND XXCETS = G2CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_services', 'w_cti_services')
			;

			INSERT INTO rh.t_services(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_services
			LEFT JOIN rh.t_services ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_services SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_services
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des spécialités
			DROP TABLE IF EXISTS w_shs_specialites;
			CREATE TEMP TABLE w_shs_specialites AS
			SELECT
				G3CENT AS XXCENT,
				G3CETS AS XXCETS,
				G3SPEC AS XXCODO,
				G3SPEC AS XXCODE,
				G3LPAR AS XXTEXT
			FROM prod_shs.rhlib_G3P01
			JOIN w_etablissements_select ON XXCENT = G3CENT AND XXCETS = G3CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_specialites', 'w_cti_specialites')
			;

			INSERT INTO rh.t_specialites(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_specialites
			LEFT JOIN rh.t_specialites ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_specialites SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_specialites
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des Codes Emploi
			DROP TABLE IF EXISTS w_shs_codes_emploi;
			CREATE TEMP TABLE w_shs_codes_emploi AS
			SELECT
				G5CENT AS XXCENT,
				G5CETS AS XXCETS,
				G5CEMP AS XXCODO,
				G5CEMP AS XXCODE,
				G5LPAR AS XXTEXT
			FROM prod_shs.rhlib_G5P01
			JOIN w_etablissements_select ON XXCENT = G5CENT AND XXCETS = G5CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_codes_emploi', 'w_cti_codes_emploi')
			;

			INSERT INTO rh.t_codes_emploi(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_codes_emploi
			LEFT JOIN rh.t_codes_emploi ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_codes_emploi SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_codes_emploi
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des types d'horaire
			INSERT INTO rh.t_types_horaire(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F4CTJN,
					F4CTJN,
					F4CTJN,
					F4CTJN
				FROM prod_shs.rhlib_F4P01
					JOIN w_etablissements_select ON XXCENT = f4CENT AND XXCETS = f4CETS
					LEFT JOIN rh.t_types_horaire ON (code_original = F4CTJN)
				WHERE code_original IS NULL AND F4CTJN <> ''
			;

			-- Màj des sociétés d'interim
			INSERT INTO rh.t_societes_interim(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F4CSOC,
					F4CSOC,
					F4CSOC,
					F4CSOC
				FROM prod_shs.rhlib_F4P01
					JOIN w_etablissements_select ON XXCENT = f4CENT AND XXCETS = f4CETS
					LEFT JOIN rh.t_societes_interim ON (code_original = F4CSOC)
				WHERE F4CSOC <> ''
					AND code_original IS NULL
			;

			-- Màj des groupes cotisants.
			DROP TABLE IF EXISTS w_shs_groupes_cotisant;
			CREATE TEMP TABLE w_shs_groupes_cotisant AS
			SELECT
				G9CENT AS XXCENT,
				G9CETS AS XXCETS,
				G9GCOT AS XXCODO,
				G9GCOT AS XXCODE,
				G9LPAR AS XXTEXT
			FROM prod_shs.rhlib_G9P01
			JOIN w_etablissements_select ON XXCENT = G9CENT AND XXCETS = G9CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_groupes_cotisant', 'w_cti_groupes_cotisant')
			;
			
			INSERT INTO rh.t_groupes_cotisant(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_groupes_cotisant
			LEFT JOIN rh.t_groupes_cotisant ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_groupes_cotisant SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_groupes_cotisant
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des grilles
			INSERT INTO rh.t_grilles(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F4GRIE,
					F4GRIE,
					F4GRIE,
					F4GRIE
				FROM prod_shs.rhlib_F4P01
					JOIN w_etablissements_select ON XXCENT = f4CENT AND XXCETS = f4CETS
					LEFT JOIN rh.t_grilles ON (code_original = F4GRIE)
				WHERE code_original IS NULL
					AND F4GRIE <> ''
			;

			-- Màj des groupes de grilles
			INSERT INTO rh.t_grilles_groupes(code, texte, texte_court, code_original)
				SELECT DISTINCT
					F4GRPE,
					F4GRPE,
					F4GRPE,
					F4GRPE
				FROM prod_shs.rhlib_F4P01
					JOIN w_etablissements_select ON XXCENT = f4CENT AND XXCETS = f4CETS
					LEFT JOIN rh.t_grilles_groupes ON (code_original = F4GRPE)
				WHERE code_original IS NULL
				AND F4GRPE <> ''
			;

			-- Màj des sections analytiques de paie
			DROP TABLE IF EXISTS w_shs_sections_analytiques_paie;
			CREATE TEMP TABLE w_shs_sections_analytiques_paie AS
			SELECT
				G0CENT AS XXCENT,
				G0CETS AS XXCETS,
				G0SANA AS XXCODO,
				G0SANA AS XXCODE,
				G0LPAR AS XXTEXT
			FROM prod_shs.rhlib_G0P01
				JOIN w_etablissements_select ON XXCENT = G0CENT AND XXCETS = G0CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_sections_analytiques_paie', 'w_cti_sections_analytiques_paie')
			;
			
			INSERT INTO rh.t_sections_analytiques_paie(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_sections_analytiques_paie
			LEFT JOIN rh.t_sections_analytiques_paie ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_sections_analytiques_paie SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_sections_analytiques_paie
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;

			-- Màj des sections analytiques (une partie est conditionné à l'existence de ANP01PR).
			INSERT INTO rh.t_sections_analytiques(code, texte, texte_court, code_original)
				SELECT DISTINCT
					G0SCPA,
					G0SCPA,
					G0SCPA,
					G0SCPA
				FROM prod_shs.rhlib_G0p01
					JOIN w_etablissements_select ON XXCENT = G0CENT AND XXCETS = G0CETS
					LEFT JOIN rh.t_sections_analytiques ON (code_original = G0SCPA)
				WHERE  code_original IS NULL
			;

			-- Màj des rubriques
			DROP TABLE IF EXISTS w_shs_rubriques;
			CREATE TEMP TABLE w_shs_rubriques AS
                with rubs as (
                        select G6CRUB as xxcrub
                        from prod_shs.rhlib_G6P01
                    union 
                        select H0CCOT as xxcrub
                        from prod_shs.rhlib_H0P01),
                cartesian as (
                    select
                        xxcrub,
                        xxcent,
                        xxcets
                    from rubs, w_etablissements_select),
                libs_0 as (
                        select
                            g6crub as libcrub,
                            g6lpar as liblpar
                        from prod_shs.rhlib_G6P01
                    union
                        select
                            H0CCOT,
                            H0lpar
                        from prod_shs.rhlib_H0P01),
                libs as (
                    select
                        libcrub,
                        max(liblpar) as liblpar
                    from libs_0
                    group by 1)
                select
                    XXCENT,
                    XXCETS,
                    xxcrub::text as XXCODO,
                    to_char(xxcrub,'FM0000') AS XXCODE,
                    coalesce(G6P01.G6LPAR, H0P01.H0LPAR, libLPAR) AS XXTEXT
                from cartesian
                    left join prod_shs.rhlib_G6P01 as G6P01 ON 1=1
                        and XXCENT = G6P01.G6CENT
                        AND XXCETS = G6P01.G6CETS
                        and xxcrub = G6P01.G6CRUB
                    left join prod_shs.rhlib_H0P01 as H0P01 ON 1=1
                        and XXCENT = H0P01.H0CENT
                        AND XXCETS = H0P01.H0CETS
                        and xxcrub = H0P01.H0CCOT
                    left join libs ON  xxcrub = libcrub
			;

			SELECT rh.cti_shs_multicode('w_shs_rubriques', 'w_cti_rubriques')
			;
			
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_rubriques
			LEFT JOIN rh.t_rubriques ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_rubriques SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_rubriques
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;
			
			UPDATE w_cti_rubriques
			SET in_id = t_rubriques.oid
			FROM rh.t_rubriques
			WHERE code_original = in_code_original;

			
			
			-- Màj des organismes de cotisation
			DROP TABLE IF EXISTS w_shs_organismes_cotisation;
			CREATE TEMP TABLE w_shs_organismes_cotisation AS
			SELECT
				I3CENT AS XXCENT,
				I3CETS AS XXCETS,
				I3NORG::text AS XXCODO,
				I3NORG::text AS XXCODE,
				I3NOM AS XXTEXT
			FROM prod_shs.rhlib_I3P01
				JOIN w_etablissements_select ON XXCENT = I3CENT AND XXCETS = I3CETS
			;

			SELECT rh.cti_shs_multicode('w_shs_organismes_cotisation', 'w_cti_organismes_cotisation')
			;
			
			INSERT INTO rh.t_organismes_cotisation(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				MAX(in_texte),
				in_code_original
			FROM w_cti_organismes_cotisation
			LEFT JOIN rh.t_organismes_cotisation ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_organismes_cotisation SET
				code = in_code,
				texte = in_texte,
				texte_court = in_texte
			FROM w_cti_organismes_cotisation
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM in_texte
				)
			;
			
			UPDATE w_cti_organismes_cotisation
			SET in_id = t_organismes_cotisation.oid
			FROM rh.t_organismes_cotisation
			WHERE code_original = in_code_original;

			-- Màj des listes
			
			-- Ancienne codification supprimée
			DELETE FROM rh.t_listes
			WHERE code LIKE 'G8P01%' AND
				length(code) <= 10;
			
			DELETE from rh.t_listes_contenu 
			WHERE liste_id NOT IN (SELECT oid FROM rh.t_listes)
			;

			
			INSERT INTO rh.t_listes(
				code,
				texte,
				table_id,
				is_cti,
				show_omit,
				utilisateur_createur,
				est_partagee_modification,
				chapitre
			)
			SELECT
				'G8P01_' || G8CGRP || '-' || to_char(G8CENT,'FM000') || to_char(G8CETS,'FM000') AS code,
				G8LPAR || ' - ' || F1NOM AS texte,
				(SELECT oid FROM rh.t_listes_tables WHERE code ='RUP') AS table_id,
				'0' AS is_cti,
				'0' AS show_omit,
				'cti' AS utilisateur_createur,
				'0' AS est_partagee_modification,
				'Listes SHS ' || F1NOM
			FROM prod_shs.rhlib_G8P01
				JOIN prod_shs.rhlib_F1P01 ON G8CENT = F1CENT AND G8CETS = F1CETS
				JOIN w_etablissements_select ON XXCENT = G8CENT AND XXCETS = G8CETS
			WHERE  ('G8P01_' || G8CGRP || '-' || to_char(G8CENT,'FM000') || to_char(G8CETS,'FM000') ) NOT IN (SELECT code FROM rh.t_listes);
			
			UPDATE rh.t_listes SET
				texte = G8LPAR || ' - ' || F1NOM,
				chapitre = 'Listes SHS ' || F1NOM
			FROM prod_shs.rhlib_G8P01
			JOIN prod_shs.rhlib_F1P01 ON G8CENT = F1CENT AND G8CETS = F1CETS
			WHERE t_listes.code = ('G8P01_' || G8CGRP || '-' || to_char(G8CENT,'FM000') || to_char(G8CETS,'FM000')) AND
				(
					texte IS DISTINCT FROM (G8LPAR || ' - ' || F1NOM) OR
					chapitre IS DISTINCT FROM ('Listes SHS ' || F1NOM)
				)
			;

			DROP TABLE IF EXISTS w_G8P01_contenu;
			CREATE TEMP TABLE w_G8P01_contenu AS
			SELECT
				t_listes.code AS liste_code,
				G8CENT,
				G8CETS,
				G8CGRP,
				G6CRUB::text AS G8RBXX
			FROM prod_shs.rhlib_g8p01
				JOIN w_etablissements_select ON XXCENT = G8CENT AND XXCETS = G8CETS
				JOIN rh.t_listes ON
					'G8P01_' || G8CGRP || '-' || to_char(G8CENT,'FM000') || to_char(G8CETS,'FM000') = t_listes.code
				JOIN prod_shs.rhlib_G6P01 ON 1=1
					AND G6CENT = G8CENT
					AND G6CETS = G8CETS
					AND (
						G6CRUB BETWEEN G8FRD1 AND G8FRF1 OR
						G6CRUB BETWEEN G8FRD2 AND G8FRF2 OR
						G6CRUB BETWEEN G8FRD3 AND G8FRF3 OR
						G6CRUB BETWEEN G8FRD4 AND G8FRF4 OR
						G6CRUB BETWEEN G8FRD5 AND G8FRF5 OR
						G6CRUB = G8RB01 OR
						G6CRUB = G8RB02 OR
						G6CRUB = G8RB03 OR
						G6CRUB = G8RB04 OR
						G6CRUB = G8RB05 OR
						G6CRUB = G8RB06 OR
						G6CRUB = G8RB07 OR
						G6CRUB = G8RB08 OR
						G6CRUB = G8RB09 OR
						G6CRUB = G8RB10 OR
						G6CRUB = G8RB11 OR
						G6CRUB = G8RB12 OR
						G6CRUB = G8RB13 OR
						G6CRUB = G8RB14 OR
						G6CRUB = G8RB15 OR
						G6CRUB = G8RB16 OR
						G6CRUB = G8RB17 OR
						G6CRUB = G8RB18 OR
						G6CRUB = G8RB19 OR
						G6CRUB = G8RB20 OR
						G6CRUB = G8RB21 OR
						G6CRUB = G8RB22 OR
						G6CRUB = G8RB23 OR
						G6CRUB = G8RB24 OR
						G6CRUB = G8RB25 OR
						G6CRUB = G8RB26 OR
						G6CRUB = G8RB27 OR
						G6CRUB = G8RB28 OR
						G6CRUB = G8RB29 OR
						G6CRUB = G8RB30 OR
						G6CRUB = G8RB31 OR
						G6CRUB = G8RB32 OR
						G6CRUB = G8RB33 OR
						G6CRUB = G8RB34 OR
						G6CRUB = G8RB35 OR
						G6CRUB = G8RB36 OR
						G6CRUB = G8RB37 OR
						G6CRUB = G8RB38 OR
						G6CRUB = G8RB39 OR
						G6CRUB = G8RB40 OR
						G6CRUB = G8RB41 OR
						G6CRUB = G8RB42 OR
						G6CRUB = G8RB43 OR
						G6CRUB = G8RB44 OR
						G6CRUB = G8RB45 OR
						G6CRUB = G8RB46 OR
						G6CRUB = G8RB47 OR
						G6CRUB = G8RB48 OR
						G6CRUB = G8RB49 OR
						G6CRUB = G8RB50
					)
			;

			UPDATE w_G8P01_contenu
			SET G8RBXX = in_code_original
			FROM w_cti_rubriques
			WHERE G8CENT = XXCENT AND
				G8CETS = XXCETS AND
				G8RBXX = XXCODO AND
				G8RBXX <> in_code_original
			;
			
			DELETE FROM rh.t_listes_contenu
			WHERE liste_id IN (SELECT oid FROM rh.t_listes WHERE code LIKE 'G8P01_%')
			;

			INSERT INTO rh.t_listes_contenu (liste_id, to_id)
			SELECT t_listes.oid, t_rubriques.oid
			FROM w_G8P01_contenu
			JOIN rh.t_listes ON t_listes.code = liste_code
			JOIN rh.t_rubriques ON t_rubriques.code_original = G8RBXX
			GROUP BY 1,2;

			-- Màj des motifs d'arret
			INSERT INTO rh.t_motifs_arret(code, texte, texte_court, code_original)
				SELECT DISTINCT
					N6MOTA,
					N6MOTA,
					N6MOTA,
					N6MOTA
				FROM prod_shs.rhlib_N6P01
					JOIN w_etablissements_select ON XXCENT = N6CENT AND XXCETS = N6CETS
					LEFT JOIN rh.t_motifs_arret ON (code_original = N6MOTA)
				WHERE 1=1
                    AND code_original IS NULL
                    AND (select valeur = '0' from rh.t_divers where code = 'SHS_MOTIF')
			;

			-- Màj des précisions du motif d'arrêt
			DROP TABLE IF EXISTS w_shs_precisions_motif_arret;
			CREATE TEMP TABLE w_shs_precisions_motif_arret AS
			SELECT
				to_number('0' || N0ENTR, '0000') AS XXCENT,
				to_number('0' || N0ETAB, '0000') AS XXCETS,
				N0CENR::text AS XXCODO,
				N0CENR::text AS XXCODE,
				N0LIBE AS XXTEXT
			FROM prod_shs.rhlib_N0P11
				JOIN w_etablissements_select ON XXCENT = to_number('0' || N0ENTR, '0000') AND XXCETS = to_number('0' || N0ETAB, '0000')
			WHERE   N0CTAB = 'ATMO'
				AND N0TYPE = '2'
			;

			SELECT rh.cti_shs_multicode('w_shs_precisions_motif_arret', 'w_cti_precisions_motif_arret')
			;
			
			INSERT INTO rh.t_precisions_motif_arret(code, texte, texte_court, code_original)
			SELECT
				MAX(in_code),
				MAX(in_texte),
				SUBSTR(MAX(in_texte),1,50),
				in_code_original
			FROM w_cti_precisions_motif_arret
			LEFT JOIN rh.t_precisions_motif_arret ON (code_original = in_code_original)
			WHERE code_original IS NULL
			GROUP BY 4
			;

			UPDATE rh.t_precisions_motif_arret SET
				code = in_code,
				texte = in_texte,
				texte_court = substr(in_texte,1,50)
			FROM w_cti_precisions_motif_arret
			WHERE in_code_original = code_original AND
				(
					code IS DISTINCT FROM in_code OR
					texte IS DISTINCT FROM in_texte OR
					texte_court IS DISTINCT FROM substr(in_texte,1,50)
				)
			;

			-- Màj des motifs de visite médicale
			INSERT INTO rh.t_motifs_visite(code_original, code, texte, texte_court)
				SELECT
					N0CENR,
					N0CENR,
					MAX(N0LIBE),
					substr(MAX(N0LIBE), 1, 50)
				FROM prod_shs.rhlib_n0p01
					JOIN w_entreprises_select ON XXCENT = to_number('0' || N0ENTR, '0000')
				WHERE 1=1
					AND n0ctab = 'MDVI'
					AND n0type = '2'
					AND N0CENR NOT IN (SELECT code_original FROM rh.t_motifs_visite)
				GROUP BY 1,2
			;

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

            select count(*) = 1
            from information_schema.tables
            where 1=1
                and table_schema = 'prod_shs'
                and table_name = 'rhlib_anp01pr'
            ;

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

            -- Màj des sections analytiques UNIQUEMENT si ANP01PR existe.
            INSERT INTO rh.t_sections_analytiques(code, texte, texte_court, code_original)
                SELECT
                    trim(to_char(ANSANA,'0000')),
                    ANINT3,
                    ANINT3,
                    trim(to_char(ANSANA,'0000'))
                FROM prod_shs.rhlib_anp01pr
                LEFT JOIN rh.t_sections_analytiques ON (code_original = trim(to_char(ANSANA,'0000')))
                WHERE code_original IS NULL
            ;

            ]]></sqlcmd>
        </NODE>
		<NODE label="Maintenance des listes/classes d'entreprises/établissements/qualification">
			<sqlcmd><![CDATA[

				-- Report des listes
				INSERT INTO rh.t_listes_contenu(liste_id, to_id)
					select t_listes.oid, t2.oid
					from rh.t_listes
						join rh.t_listes_tables ON t_listes_tables.oid = t_listes.table_id						
						join rh.t_listes_contenu on t_listes_contenu.liste_id = t_listes.oid
						join rh.t_qualifications as t1 on t1.oid = t_listes_contenu.to_id
						join rh.t_qualifications as t2 on t2.code = t1.code
						Left join rh.t_listes_contenu AS lc on 1=1
							AND lc.liste_id = t_listes.oid
							AND lc.to_id = t2.oid
					where 1=1
						and t_listes_tables.code = 'QUA'
						and lc.to_id is null
					group by 1,2
				;

				-- Report des classes
				INSERT INTO rh.t_classes_sections_elements(section_id, to_id)
					select t_classes_sections.oid, t2.oid
					from rh.t_classes
						join rh.t_listes_tables ON t_listes_tables.oid = t_classes.table_id
						join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
						join rh.t_classes_sections_elements on t_classes_sections_elements.section_id = t_classes_sections.oid
						join rh.t_qualifications as t1 on t1.oid = t_classes_sections_elements.to_id
						join rh.t_qualifications as t2 on t2.code = t1.code
						Left join rh.t_classes_sections_elements AS cse on 1=1
							AND cse.section_id = t_classes_sections_elements.section_id
							AND cse.to_id = t2.oid
					where 1=1
						and t_listes_tables.code = 'QUA'
						and cse.to_id is null
					group by 1,2
				;

				-- Suppression des entreprises superflues.
				DELETE FROM rh.t_entreprises
				WHERE oid IN (
					select oid
					from rh.t_entreprises
					where 1=1
						and length(code_original) != 3
						and oid != 0
					group by 1)
				;

				-- Suppression des établissements superflus.
				DELETE FROM rh.t_etablissements
				WHERE oid IN (
					select oid
					from rh.t_etablissements
					where 1=1
						and length(code_original) != 6
						and oid != 0
						group by 1)
				;

				-- Suppression des qualifications superflues.
				DELETE FROM rh.t_qualifications
				WHERE oid IN (
					select oid
					from rh.t_qualifications
					where 1=1
						and length(code_original) <= 6
						and oid != 0
						group by 1)
				;

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

			TRUNCATE rh.p_chiffrier_production
			;

			INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
				SELECT
					t_entreprises.oid AS entreprise_id,
					t_etablissements.oid AS etablissement_id,
					F1DFPA * 100 + F1DFPM AS mois,
					SUM(F1NBSA) AS nombre_contrats,
					SUM(F1BRUT) AS montant_brut,
					SUM(F1NBHR) AS nombre_heures
				FROM prod_shs.rhlib_F1P31
					JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS
					LEFT JOIN rh.t_entreprises ON lpad(F1CENT, 3, '0') = t_entreprises.code_original
					LEFT JOIN rh.t_etablissements ON lpad(F1CENT, 3, '0')||lpad(F1CETS, 3, '0') = t_etablissements.code_original
				WHERE 1=1
					AND F1DFPA >= to_char(rhp('rhprovider_start')::date, 'YYYY')
					AND (1!=1
						OR F1NBSA <> 0
						OR F1BRUT <> 0
						OR F1NBHR <> 0)
				GROUP BY 1,2,3
			;


			INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
				SELECT
					t_etablissements.entreprise_id,
					t_etablissements.oid AS etablissement_id,
					f1DFPA * 100 + f1DFPM AS mois,
					0 AS nombre_contrats,
					0 AS montant_brut,
					0 AS nombre_heures
				FROM prod_shs.rhlib_F1P01
					JOIN w_etablissements_select ON XXCENT = F1CENT AND XXCETS = F1CETS
					LEFT JOIN rh.t_etablissements ON lpad(F1CENT, 3, '0')||lpad(F1CETS, 3, '0') = t_etablissements.code_original
					LEFT JOIN rh.p_chiffrier_production ON 1=1
						AND p_chiffrier_production.entreprise_id = t_etablissements.entreprise_id
						AND p_chiffrier_production.etablissement_id = t_etablissements.oid
						AND p_chiffrier_production.mois = (f1DFPA * 100 + f1DFPM)
				WHERE 1=1
					AND f1DFPA >= to_char(rhp('rhprovider_start')::date, 'YYYY')
					AND	p_chiffrier_production.entreprise_id IS NULL
				GROUP BY 1,2,3
			;

			]]></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,
					F3NOM::text AS nom,
					F3PREN::text AS prenom,
                    F3NOSS::text||lpad(F3NCSS::text, 2, '0') as nir,
					CASE WHEN F3DTNA = 1900 THEN '1979-12-17'::date ELSE rh.cti_to_date(F3DTNA, F3DTNM, F3DTNJ)::date END AS date_naissance,
					F3SEXE::text AS sexe,
					F3CMAT::text AS matricule,
					F3CMAT::text AS code,
					to_char(F3CENT,'FM000') || F3CMAT::text AS code_original, -- code original inclu le code entreprise.
					coalesce(t_entreprises.oid,0)::bigint AS entreprise_id,
					coalesce(t_nationalites.oid,0)::bigint AS nationalite_id,
					coalesce(t_codes_postaux.oid,0)::bigint AS code_postal_id,
					F3NOMP::text AS nom_naissance,
					coalesce(t_situations_famille.oid,0)::bigint AS situation_famille_id,
					0::bigint AS profil_id, -- dernier profil salarié.
					'2099-12-31'::date AS date_debut, -- date de début du dernier contrat.
					'2099-12-31'::date AS date_fin, -- date de fin du dernier contrat.
					CASE WHEN f3de1a = 0 THEN '1900-01-01'::date ELSE rh.cti_to_date(f3de1a, f3de1m, f3de1j)::date END AS date_entree_ets,
					CASE WHEN f3ds9a = 0 THEN '2099-12-31'::date ELSE rh.cti_to_date(f3ds9a, f3ds9m, f3ds9j)::date END AS date_sortie_ets,
                    CASE WHEN f3de1a = 0 THEN '1900-01-01'::date ELSE rh.cti_to_date(f3de1a, f3de1m, f3de1j)::date END AS date_anciennete,
					-- Champs dédiés au public.
					'2099-12-31'::date AS date_entree_fp,
					'2099-12-31'::date AS date_entree_fph,
					0::text AS no_adeli,
					0::bigint AS code_cotisation_id,
					0::text AS matricule_retraite
				FROM prod_shs.rhlib_F3P01
					JOIN w_entreprises_select ON XXCENT = F3CENT
					LEFT JOIN rh.t_entreprises        ON lpad(F3CENT, 3, '0') = t_entreprises.code_original
					LEFT JOIN rh.t_nationalites       ON F3CNAT = t_nationalites.code_original
					LEFT JOIN base.t_codes_postaux    ON lpad(F3CPOS, 5, '0') = t_codes_postaux.code
					LEFT JOIN rh.t_situations_famille ON F3SFAM = t_situations_famille.code_original
			;

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

			DROP TABLE IF EXISTS w_F4P01
			;

			CREATE TEMP TABLE w_F4P01 AS
				SELECT
					F4P01.*,
					to_char(F4CENT,'FM000') || F4CMAT AS salarie_code_original,
					F4CMAT || '-' || F4NCNT AS F4CMATNCNT,
					to_char(F4CENT,'FM000') || to_char(F4CETS,'FM000') || F4CMAT || '-' || to_char(F4NCNT,'FM000') AS code_original,
					F4CQUA::text AS F4CQUA_profil,
					F4SRVC::text AS F4SRVC_profil,
					F4CSTT::text AS F4CSTT_profil,
					F4CCSP::text AS F4CCSP_profil,
					F4SPEC::text AS F4SPEC_profil,
					F4CEMP::text AS F4CEMP_profil,
					F4GCOT::text AS F4GCOT_profil,
					F4SANA::text AS F4SANA_profil,
					COALESCE(G0SCPA, '0000') AS F4SCPA,
                    (case when F4CTPS IN ('I', 'P') then F4CTPS||trim(to_char(F4NHRE, '000.00')) else F4CTPS end) AS F4CTTT,
                    CASE WHEN shs_anciennete.calcul_shs THEN ABS(F4MAN1) + ABS(F4MAE1) + ABS(F4MAD1) - ABS(F4MAN2) - ABS(F4MAE2) - ABS(F4MAD2) ELSE -1 END AS F4MAXX, -- Pour ancienneté SHS en mois.
                    CASE WHEN shs_anciennete.calcul_shs THEN (ABS(F4MAN1) + ABS(F4MAE1) + ABS(F4MAD1) - ABS(F4MAN2) - ABS(F4MAE2) - ABS(F4MAD2)) * (365.25 / 12.0) ELSE -1 END AS F4JAXX, -- Pour ancienneté SHS en jours (approximé).
					(CASE WHEN F4DC9A <> 0 THEN rh.cti_to_date(F4DC9A, F4DC9M, F4DC9J) ELSE now() END)::date - rh.cti_to_date(F4DC1A, F4DC1M, F4DC1J) + 1 AS duree -- Pour ancienneté iCTI.
				FROM prod_shs.rhlib_F4P01 F4P01
					JOIN w_etablissements_select ON XXCENT = F4CENT AND XXCETS = F4CETS
                    JOIN (select valeur = '0' as calcul_shs from rh.t_divers where code = 'SHS_ANCIENNETE' LIMIT 1) as shs_anciennete ON 1=1
					LEFT JOIN prod_shs.rhlib_g0p01 ON 1=1
						AND F4CENT = G0CENT
						AND F4CETS = G0CETS
						AND F4SANA = G0SANA
			;

			-- Services multi etablissements ?
			UPDATE w_F4P01
			SET F4SRVC_profil = in_code_original
			FROM w_cti_services
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4SRVC = XXCODO AND
				F4SRVC_profil <> in_code_original
			;
			
			-- Qualifications multi etablissements ?
			UPDATE w_F4P01
			SET F4CQUA_profil = in_code_original
			FROM w_cti_qualifications
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4CQUA = XXCODO AND
				F4CQUA_profil <> in_code_original
			;
			
			-- Catégories multi etablissements ?
			UPDATE w_F4P01
			SET F4CCSP_profil = in_code_original
			FROM w_cti_categories
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4CCSP = XXCODO AND
				F4CCSP_profil <> in_code_original
			;
			
			-- Statuts différents par établissement ?
			UPDATE w_F4P01
			SET F4CSTT_profil = in_code_original
			FROM w_cti_statuts
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4CSTT = XXCODE AND
				F4CSTT_profil <> in_code_original
			;
			
			-- spéfialités différents par établissement ?
			UPDATE w_F4P01
			SET F4SPEC_profil = in_code_original
			FROM w_cti_specialites
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4SPEC = XXCODE AND
				F4SPEC_profil <> in_code_original
			;
			
			-- Codes emploi différents par établissement ?
			UPDATE w_F4P01
			SET F4CEMP_profil = in_code_original
			FROM w_cti_codes_emploi
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4CEMP = XXCODE AND
				F4CEMP_profil <> in_code_original
			;
			
			-- Groupes cotisant différents par établissement ?
			UPDATE w_F4P01
			SET F4GCOT_profil = in_code_original
			FROM w_cti_groupes_cotisant
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4GCOT = XXCODE AND
				F4GCOT_profil <> in_code_original
			;
			
			-- Sections analytiques différents par établissement ?
			UPDATE w_F4P01
			SET F4SANA_profil = in_code_original
			FROM w_cti_sections_analytiques_paie
			WHERE F4CENT = XXCENT AND
				F4CETS = XXCETS AND
				F4SANA = XXCODE AND
				F4SANA_profil <> in_code_original
			;

			CREATE INDEX w_F4P01_i1	ON w_F4P01 USING btree(F4CMAT)
			;
			
			
			
			-- Contrats fictifs
			DELETE FROM w_F4P01
			USING
				(
				SELECT w_F4P01.ctid
				FROM w_F4P01
				LEFT JOIN prod_shs.rhlibH_J0P01 ON
					F4CENT = J0CENT AND
					F4CETS = J0CETS AND
					F4CMAT = J0CMAT AND
					F4NCNT = J0NCNT
				WHERE F4SUSP = '9' AND
					J0CMAT IS NULL
				) SUBVIEW
			WHERE w_F4P01.ctid = subview.ctid
			;


			UPDATE w_F4P01 
			SET
				F4DC1A = F3DE1A,
				F4DC1M = F3DE1M,
				F4DC1J = F3DE1J
			FROM prod_shs.rhlib_F3P01
				JOIN w_entreprises_select ON XXCENT = F3CENT
			WHERE 1=1
				AND F4CENT = F3CENT
				AND F4CMAT = F3CMAT
				AND F4DC1A = 0
				AND F4DC1M = 0
				AND F4DC1J = 0
			;

			-- Correction etablissement dans lignes de paie (contrat avec autre etablissement dans f4p01)
			DROP TABLE IF EXISTS wh_J0P01
			;
			CREATE TEMP TABLE wh_J0P01 AS
				SELECT *,
					to_char(J0CENT,'FM000') || to_char(J0CETS,'FM000') || J0CMAT::text || to_char(J0NCNT,'FM0000') || to_char(J0DFPA,'FM0000') || to_char(J0DFPM,'FM00') AS J0SMKEY
				FROM prod_shs.rhlibH_J0P01
					JOIN w_etablissements_select ON XXCENT = J0CENT AND XXCETS = J0CETS
				WHERE J0DFPA >= to_char(rhp('rhprovider_start')::date, 'YYYY') 
			;
			
			CREATE INDEX wh_J0P01_i1	ON wh_J0P01 USING btree(J0CMAT)
			;
			
			CREATE INDEX wh_J0P01_i2	ON wh_J0P01 USING btree(J0CRUB)
			;
			
			CREATE INDEX wh_J0P01_i3	ON wh_J0P01 USING btree(J0NORG)
			;
			
			CREATE INDEX wh_J0P01_i4	ON wh_J0P01 USING btree(J0SMKEY)
			;

			DROP TABLE IF EXISTS w_J0P01_pbcnt
			;
			CREATE TEMP TABLE w_J0P01_pbcnt AS
				SELECT
					F4P01.F4CENT,
					F4P01.F4CMAT,
					F4P01.F4NCNT,
					min(F4P01.F4CETS) AS F4CETS
				FROM wh_J0P01
					JOIN prod_shs.rhlib_F4P01 F4P01 ON 1=1
						AND J0CENT = F4P01.F4CENT
						AND J0CMAT = F4P01.F4CMAT
						AND J0NCNT = F4P01.F4NCNT
					LEFT JOIN prod_shs.rhlib_F4P01 F4P01_2 ON 1=1
						AND J0CENT = F4P01_2.F4CENT
						AND J0CETS = F4P01_2.F4CETS
						AND J0CMAT = F4P01_2.F4CMAT
						AND J0NCNT = F4P01_2.F4NCNT
				WHERE 1=1
					AND F4P01_2.F4CMAT IS NULL
				GROUP BY 1,2,3
			;

			UPDATE wh_J0P01
			SET J0CETS = F4CETS,
				J0SMKEY = to_char(J0CENT,'FM000') || to_char(F4CETS,'FM000') || J0CMAT::text || to_char(J0NCNT,'FM0000') || to_char(J0DFPA,'FM0000') || to_char(J0DFPM,'FM00')
			FROM w_J0P01_pbcnt
			WHERE 1=1
				AND J0CENT = F4CENT -- entreprise
				AND J0CMAT = F4CMAT -- matricule
				AND J0NCNT = F4NCNT -- contrat
			;

            -- #specifique Spécifiques Les Cèdres 984 (on renseigne dans nombre le nombre d'heures à inscrire dans le champ d'HP base).
            with coeff as (
                select
                    t_rubriques.code_original,
                    t_rubriques.coefficient_nombre
                from rh.t_listes
                join rh.t_listes_contenu on t_listes_contenu.liste_id = t_listes.oid
                join rh.t_rubriques on t_rubriques.oid = t_listes_contenu.to_id
                where t_listes.code = 'CED_FORFAITS')
            UPDATE wh_J0P01 SET
                J0BASE = coefficient_nombre
            FROM coeff
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND J0CRUB = coeff.code_original
            ;

            -- #specifique global I et P à 0.00 : on prend depuis les rubriques d'heures contrat.
            with rub_hcnt as (
                select
                    t_rubriques.code_original
                from rh.t_listes
                    join rh.t_listes_contenu on t_listes_contenu.liste_id = t_listes.oid
                    join rh.t_rubriques on t_rubriques.oid = t_listes_contenu.to_id
                where t_listes.code = 'CTI_HCNT'
                )
            ,hcnt as (
                select
                    J0CENT,
                    J0CETS,
                    J0CMAT,
                    J0NCNT,
                    max(J0BASE) as J0BASE
                FROM wh_J0P01
                    join rub_hcnt on rub_hcnt.code_original = wh_J0P01.J0CRUB
                where current_database() in ('icti_984', 'icti_971')
                group by 1,2,3,4)
            UPDATE w_F4P01 SET
                F4NHRE = J0BASE
            FROM hcnt
            where 1=1
                and current_database() in ('icti_984', 'icti_971')
                AND J0CENT = F4CENT
                AND J0CETS = F4CETS
                AND J0CMAT = F4CMAT
                AND J0NCNT = F4NCNT 
                and F4CTPS in ('I', 'P')
                and F4NHRE = 0
            ;

            -- #specifique 984 par matricule.
            UPDATE w_F4P01 SET
                F4NHRE = 151.67
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND f4cmat = '2398G'
            ;

            UPDATE w_F4P01 SET
                F4NHRE = 113.75
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND f4cmat = '1215W'
            ;

            UPDATE wh_J0P01 SET
                J0BASE = 113.75
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND J0CMAT = '1215W'
                AND J0CRUB = '1072'
            ;

            UPDATE wh_J0P01 SET
                J0BASE = 27.30
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND J0CMAT = '2299Z'
                AND J0CRUB = '1072'
            ;

            UPDATE wh_J0P01 SET
                J0BASE = 75.84
            WHERE 1=1
                AND current_database() = 'icti_984'
                AND J0CMAT = '1192W'
                AND J0CRUB = '1070'
            ;

            -- #specifique Spécifiques Archette 162 (on renseigne dans nombre le nombre d'heures à inscrire dans le champ d'HP base).
            UPDATE wh_J0P01 SET
                J0BASE = 151.67
            WHERE 1=1
                AND current_database() = 'icti_162'
                AND J0CRUB = '1011'
            ;

            UPDATE wh_J0P01 SET
                J0BASE = 60.7
            WHERE 1=1
                AND current_database() = 'icti_162'
                AND J0CRUB = '1015'
            ;

            -- #specifique INKERMANN : on prend depuis les heures forfait depuis les rubriques les rubriques d'heures contrat.
            with id as ( -- idenfication des bulletins avec rubrique 1070.
                select J0SMKEY
                from wh_J0P01
                where true
                    AND current_database() = 'icti_848'
                    and J0CRUB = '1070'),
            valeur as ( -- Récupération de la base de la 0099 à intégrer dans celle de la 1070.
                select
                    wh_J0P01.J0BASE,
                    wh_J0P01.J0SMKEY
                from wh_J0P01
                    join id on id.J0SMKEY = wh_J0P01.J0SMKEY
                where true
                    AND current_database() = 'icti_848'
                    and J0CRUB = '0099')
            UPDATE wh_J0P01 SET
                J0BASE = valeur.J0BASE
            FROM valeur
            WHERE 1=1
                AND current_database() = 'icti_848'
                AND wh_J0P01.J0CRUB = '1070' -- Rubrique de forfait dont la base n'est pas alimentée en heures.
                AND wh_J0P01.J0SMKEY = valeur.J0SMKEY
            ;

            -- Màj des types de temps de travail
            DROP TABLE IF EXISTS w_shs_types_temps_travail
            ;
            CREATE TEMP TABLE w_shs_types_temps_travail AS
                SELECT
                    XXCENT,
                    XXCETS,
                    coalesce(subq.code, N0CENR) AS XXCODO,
                    coalesce(subq.code, N0CENR) AS XXCODE,
                    MAX(N0LIBE)||coalesce(subq.libelle, ''::text) AS XXTEXT
                FROM prod_shs.rhlib_n0P01
                    JOIN w_etablissements_select ON 1=1
                    LEFT JOIN (select
                            F4CTPS,
                            case when F4CTPS IN ('I', 'P') then F4CTPS||trim(to_char(F4NHRE, '000.00')) else F4CTPS end as code,
                            ' ' || F4NHRE::text as libelle,
                            F4CENT,
                            F4CETS
                        from w_F4P01
                            JOIN w_etablissements_select ON 1=1
                                AND XXCENT = F4CENT
                                AND XXCETS = F4CETS
                        WHERE F4CTPS IN ('I', 'P')
                        group by 1,2,3,4,5) as subq on 1=1
                            AND subq.F4CTPS = N0CENR
                            AND subq.F4CENT = XXCENT
                            AND subq.F4CETS = XXCETS
                WHERE 1=1
                    AND N0CTAB = 'TTPS'
                    AND N0TYPE = '2'
                GROUP BY 1,2,3,4, subq.libelle
            ;

            SELECT rh.cti_shs_multicode('w_shs_types_temps_travail', 'w_cti_types_temps_travail')
            ;

            INSERT INTO rh.t_types_temps_travail(code, texte, texte_court, code_original)
                SELECT
                    MAX(in_code),
                    MAX(in_texte),
                    MAX(in_texte),
                    in_code_original
                FROM w_cti_types_temps_travail
                LEFT JOIN rh.t_types_temps_travail ON (code_original = in_code_original)
                WHERE code_original IS NULL
                GROUP BY 4
            ;

            UPDATE rh.t_types_temps_travail SET
                code = in_code,
                texte = in_texte,
                texte_court = in_texte
            FROM w_cti_types_temps_travail
            WHERE 1=1
                AND in_code_original = code_original
                AND (1!=1
                    OR code IS DISTINCT FROM in_code
                    OR texte IS DISTINCT FROM in_texte
                    OR texte_court IS DISTINCT FROM in_texte)
            ;

            TRUNCATE rh.p_profils
            ;

            ALTER SEQUENCE rh.s_profils RESTART WITH 1
            ;

            INSERT INTO rh.p_profils(
                type_contrat_code_original,
                type_horaire_code_original,
                motif_debut_code_original,
                motif_fin_code_original,
                qualification_code_original,
                service_code_original,
                specialite_code_original,
                type_temps_travail_code_original,
                categorie_socio_professionnelle_code_original,
                statut_code_original,
                code_emploi_code_original,
                societe_interim_code_original,
                section_analytique_paie_code_original,
                section_analytique_code_original,
                grille_code_original,
                grille_groupe_code_original,
                groupe_cotisant_code_original
                )
                SELECT
                    F4TCNT     AS type_contrat_code_original,
                    F4CTJN     AS type_horaire_code_original,
                    F4MOTD     AS motif_debut_code_original,
                    F4MOTF     AS motif_fin_code_original,
                    F4CQUA_profil AS qualification_code_original,
                    F4SRVC_profil AS service_code_original,
                    F4SPEC_profil AS specialite_code_original,
                    F4CTTT     AS type_temps_travail_code_original,
                    F4CCSP_profil AS categorie_socio_professionnelle_code_original,
                    F4CSTT_profil AS statut_code_original,
                    F4CEMP_profil AS code_emploi_code_original,
                    F4CSOC     AS societe_interim_code_original,
                    F4SANA_profil AS section_analytique_paie_code_original,
                    F4SCPA     AS section_analytique_code_original,
                    F4GRIE     AS grille_code_original,
                    F4GRPE     AS grille_groupe_code_original,
                    F4GCOT_profil AS groupe_cotisant_code_original
                FROM w_F4P01
            GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
            ;

			DROP TABLE IF EXISTS w_J0P01_0
			;
			CREATE TEMP TABLE w_J0P01_0 AS
				SELECT
					J0SMKEY AS J0SMKEY_0,
					J0CENT AS J0CENT_0,
					J0CETS AS J0CETS_0,
					J0CMAT AS J0CMAT_0,
					to_char(J0CENT,'FM000')|| J0CMAT AS salarie_code_original,
					J0NCNT AS J0NCNT_0,
					F4CMATNCNT AS J0CMATNCNT_0,
					w_F4P01.code_original AS contrat_code_original,
					J0DFPA AS J0DFPA_0,
					J0DFPM AS J0DFPM_0,
					J0DFPA * 100 + J0DFPM AS mois_paie,
					rh.cti_to_date(J0DFPA, J0DFPM, 1::numeric) + interval '1 month' - interval '1 day' AS date_paie,
					F4TCNT AS J0TCNT_0,
					F4CTJN AS J0CTJN_0,
					F4MOTD AS J0MOTD_0,
					F4MOTF AS J0MOTF_0,
					F4CSOC AS J0CSOC_0,
					F4GRIE AS J0GRIE_0,
					F4GRPE AS J0GRPE_0,
					F4GCOT AS J0GCOT_0,
					F4GCOT::text AS J0GCOT_0_profil,
                    case when F4CTPS IN ('I', 'P') then F4CTPS||trim(to_char(F4NHRE, '000.00')) else F4CTPS end as J0CTTT_0,
                    CASE WHEN F4CTPS = 'C' THEN 1 ELSE round(F4NHRE / 151.67, 7) END ratio_temps_travail,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CQUA]))[2] AS J0CQUA_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CQUA]))[2]::text AS J0CQUA_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SRVC]))[2] AS J0SRVC_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SRVC]))[2]::text AS J0SRVC_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SPEC]))[2] AS J0SPEC_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SPEC]))[2]::text AS J0SPEC_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CTPS]))[2] AS J0CTPS_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CCSP]))[2] AS J0CCSP_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CCSP]))[2]::text AS J0CCSP_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CSTT]))[2] AS J0CSTT_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CSTT]))[2]::text AS J0CSTT_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CEMP]))[2] AS J0CEMP_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0CEMP]))[2]::text AS J0CEMP_0_profil,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SANA]))[2] AS J0SANA_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),J0SANA]))[2]::text AS J0SANA_0_profil,
					''::text AS J0SCPA_0,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),(rh.cti_to_date(J0DA1A, J0DA1M, J0DA1J))::text]))[2]::date AS date_debut,
					(MIN(ARRAY[to_char(J0CRUB,'FM0000'),(rh.cti_to_date(J0DA9A, J0DA9M, J0DA9J))::text]))[2]::date AS date_fin,
					0::bigint AS salarie_id,
					0::bigint AS contrat_id,
					0::bigint AS contrat_mois_id,
					0::bigint AS profil_id,
					'H'::text AS est_historique
				FROM wh_J0P01
					LEFT JOIN w_F4P01 ON 1=1
						AND J0CENT = F4CENT
						AND J0CETS = F4CETS
						AND J0CMAT = F4CMAT
						AND J0NCNT = F4NCNT
				WHERE 1=1
					AND J0CRUB >= 5
				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
			;

			
			INSERT INTO w_J0P01_0
				SELECT
					to_char(F9CENT,'FM000') || to_char(F9CETS,'FM000') || F9CMAT::text || to_char(F9NCNT,'FM0000') || to_char(F1DFPA,'FM0000') || to_char(F1DFPM,'FM00') AS J0SMKEY_0,
					F9CENT AS J0CENT_0,
					F9CETS AS J0CETS_0,
					F9CMAT AS J0CMAT_0,
					to_char(F9CENT,'FM000')|| F9CMAT AS salarie_code_original,
					F9NCNT AS J0NCNT_0,
					F4CMATNCNT AS J0CMATNCNT_0,
					w_F4P01.code_original AS contrat_code_original,
					F1DFPA AS J0DFPA_0,
					F1DFPM AS J0DFPM_0,
					F1DFPA * 100 + F1DFPM AS mois_paie,
					rh.cti_to_date(F1DFPA, F1DFPM, 1::numeric) + interval '1 month' - interval '1 day' AS date_paie,
					F4TCNT AS J0TCNT_0,
					F4CTJN AS J0CTJN_0,
					F4MOTD AS J0MOTD_0,
					F4MOTF AS J0MOTF_0,
					F4CSOC AS J0CSOC_0,
					F4GRIE AS J0GRIE_0,
					F4GRPE AS J0GRPE_0,
					F4GCOT AS J0GCOT_0,
					F4GCOT AS J0GCOT_0_profil,
                    case when F4CTPS IN ('I', 'P') then F4CTPS||trim(to_char(F4NHRE, '000.00')) else F4CTPS end as J0CTTT_0,
                    CASE WHEN F4CTPS = 'C' THEN 1 ELSE round(F4NHRE / 151.67, 7) END ratio_temps_travail,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CQUA]))[2] AS J0CQUA_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CQUA]))[2] AS J0CQUA_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SRVC]))[2] AS J0SRVC_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SRVC]))[2] AS J0SRVC_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SPEC]))[2] AS J0SPEC_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SPEC]))[2] AS J0SPEC_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CTPS]))[2] AS J0CTPS_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CCSP]))[2] AS J0CCSP_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CCSP]))[2] AS J0CCSP_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CSTT]))[2] AS J0CSTT_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CSTT]))[2] AS J0CSTT_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CEMP]))[2] AS J0CEMP_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9CEMP]))[2] AS J0CEMP_0_profil,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SANA]))[2] AS J0SANA_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),F9SANA]))[2] AS J0SANA_0_profil,
					''::text AS J0SCPA_0,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),(rh.cti_to_date(F9DA1A, F9DA1M, F9DA1J))::text]))[2]::date AS date_debut,
					(MIN(ARRAY[to_char(F9CRUB,'FM0000'),(rh.cti_to_date(F9DA9A, F9DA9M, F9DA9J))::text]))[2]::date AS date_fin,
					0::bigint AS salarie_id,
					0::bigint AS contrat_id,
					0::bigint AS contrat_mois_id,
					0::bigint AS profil_id,
					''::text AS est_historique
				FROM prod_shs.rhlib_F9P01
					JOIN w_etablissements_select ON XXCENT = F9CENT AND XXCETS = F9CETS
					JOIN prod_shs.rhlib_F1P01 ON 1=1
						AND F9CENT = F1CENT
						AND F9CETS = F1CETS
					LEFT JOIN w_F4P01 ON 1=1
						AND F9CENT = F4CENT
						AND F9CETS = F4CETS
						AND F9CMAT = F4CMAT
						AND F9NCNT = F4NCNT
				WHERE 1=1
					AND F9CRUB >= 5
				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
			;

			CREATE INDEX w_J0P01_0_i1 ON w_J0P01_0 USING btree (J0CMAT_0)
			;
			CREATE INDEX w_J0P01_0_i2 ON w_J0P01_0 USING btree (salarie_code_original)
			;
			CREATE INDEX w_J0P01_0_i3 ON w_J0P01_0 USING btree (J0SMKEY_0)
			;

			UPDATE w_J0P01_0
			SET
				salarie_id   = p_salaries.oid
			FROM rh.p_salaries
			WHERE salarie_code_original  = p_salaries.code_original
			;

			UPDATE w_J0P01_0
			SET J0SCPA_0 = G0SCPA
			FROM prod_shs.rhlib_g0p01
			WHERE 1=1
				AND J0CENT_0 = G0CENT
				AND J0CETS_0 = G0CETS
				AND J0SANA_0 = G0SANA
			;

			-- Services multi etablissements ?
			UPDATE w_J0P01_0
			SET J0SRVC_0_profil = in_code_original
			FROM w_cti_services
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0SRVC_0 = XXCODO AND
				J0SRVC_0_profil <> in_code_original
			;
			
			-- Qualifications multi etablissements ?
			UPDATE w_J0P01_0
			SET J0CQUA_0_profil = in_code_original
			FROM w_cti_qualifications
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0CQUA_0 = XXCODO AND
				J0CQUA_0_profil <> in_code_original
			;
			
			-- Catégories multi etablissements ?
			UPDATE w_J0P01_0
			SET J0CCSP_0_profil = in_code_original
			FROM w_cti_categories
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0CCSP_0 = XXCODO AND
				J0CCSP_0_profil <> in_code_original
			;
			
			-- Statuts différents par établissement ?
			UPDATE w_J0P01_0
			SET J0CSTT_0_profil = in_code_original
			FROM w_cti_statuts
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0CSTT_0 = XXCODE AND
				J0CSTT_0_profil <> in_code_original
			;
			
			-- Spécialités différents par établissement ?
			UPDATE w_J0P01_0
			SET J0SPEC_0_profil = in_code_original
			FROM w_cti_specialites
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0SPEC_0 = XXCODE AND
				J0SPEC_0_profil <> in_code_original
			;
			
			-- Codes emplois différents par établissement ?
			UPDATE w_J0P01_0
			SET J0CEMP_0_profil = in_code_original
			FROM w_cti_codes_emploi
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0CEMP_0 = XXCODE AND
				J0CEMP_0_profil <> in_code_original
			;
			
			-- Groupes cotisants différents par établissement ?
			UPDATE w_J0P01_0
			SET J0GCOT_0_profil = in_code_original
			FROM w_cti_groupes_cotisant
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0GCOT_0 = XXCODE AND
				J0GCOT_0_profil <> in_code_original
			;
			
			-- Sections analytiques différents par établissement ?
			UPDATE w_J0P01_0
			SET J0SANA_0_profil = in_code_original
			FROM w_cti_sections_analytiques_paie
			WHERE J0CENT_0 = XXCENT AND
				J0CETS_0 = XXCETS AND
				J0SANA_0 = XXCODE AND
				J0SANA_0_profil <> in_code_original
			;

			INSERT INTO rh.p_profils(
				type_contrat_code_original,
				type_horaire_code_original,
				motif_debut_code_original,
				motif_fin_code_original,
				qualification_code_original,
				service_code_original,
				specialite_code_original,
				type_temps_travail_code_original,
				categorie_socio_professionnelle_code_original,
				statut_code_original,
				code_emploi_code_original,
				societe_interim_code_original,
				section_analytique_paie_code_original,
				section_analytique_code_original,
				grille_code_original,
				grille_groupe_code_original,
				groupe_cotisant_code_original
				)
				SELECT
					J0TCNT_0     AS type_contrat_code_original,
					J0CTJN_0     AS type_horaire_code_original,
					J0MOTD_0     AS motif_debut_code_original,
					J0MOTF_0     AS motif_fin_code_original,
					J0CQUA_0_profil AS qualification_code_original,
					J0SRVC_0_profil AS service_code_original,
					J0SPEC_0_profil AS specialite_code_original,
					J0CTTT_0     AS type_temps_travail_code_original,
					J0CCSP_0_profil AS categorie_socio_professionnelle_code_original,
					J0CSTT_0_profil AS statut_code_original,
					J0CEMP_0_profil AS code_emploi_code_original,
					J0CSOC_0     AS societe_interim_code_original,
					J0SANA_0_profil AS section_analytique_paie_code_original,
					J0SCPA_0     AS section_analytique_code_original,
					J0GRIE_0     AS grille_code_original,
					J0GRPE_0     AS grille_groupe_code_original,
					J0GCOT_0_profil AS groupe_cotisant_code_original
				FROM w_J0P01_0
					LEFT JOIN rh.p_profils ON 1=1
						AND J0TCNT_0     = type_contrat_code_original
						AND J0CTJN_0     = type_horaire_code_original
						AND J0MOTD_0     = motif_debut_code_original
						AND J0MOTF_0     = motif_fin_code_original
						AND J0CQUA_0_profil = qualification_code_original
						AND J0SRVC_0_profil = service_code_original
						AND J0SPEC_0_profil = specialite_code_original
						AND J0CTTT_0     = type_temps_travail_code_original
						AND J0CCSP_0_profil = categorie_socio_professionnelle_code_original
						AND J0CSTT_0_profil = statut_code_original
						AND J0CEMP_0_profil = code_emploi_code_original
						AND J0CSOC_0     = societe_interim_code_original
						AND J0SANA_0_profil = section_analytique_paie_code_original
						AND J0SCPA_0     = section_analytique_code_original
						AND J0GRIE_0     = grille_code_original
						AND J0GRPE_0     = grille_groupe_code_original
						AND J0GCOT_0_profil = groupe_cotisant_code_original
				WHERE p_profils.oid IS NULL
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17
			;

			UPDATE w_J0P01_0
				SET	profil_id = p_profils.oid
				FROM rh.p_profils
				WHERE 1=1
					AND J0TCNT_0     = type_contrat_code_original
					AND J0CTJN_0     = type_horaire_code_original
					AND j0MOTD_0     = motif_debut_code_original
					AND j0MOTF_0     = motif_fin_code_original
					AND J0CQUA_0_profil = qualification_code_original
					AND J0SRVC_0_profil = service_code_original
					AND J0SPEC_0_profil = specialite_code_original
					AND J0CTTT_0     = type_temps_travail_code_original
					AND J0CCSP_0_profil = categorie_socio_professionnelle_code_original
					AND J0CSTT_0_profil = statut_code_original
					AND J0CEMP_0_profil = code_emploi_code_original
					AND J0CSOC_0     = societe_interim_code_original
					AND J0SANA_0_profil = section_analytique_paie_code_original
					AND J0SCPA_0     = section_analytique_code_original
					AND J0GRIE_0     = grille_code_original
					AND J0GRPE_0     = grille_groupe_code_original
					AND J0GCOT_0_profil = groupe_cotisant_code_original
			;

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

			TRUNCATE rh.p_contrats
			;

			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

			INSERT INTO rh.p_contrats(
				code_original,
				salarie_id,
				date_debut,
				date_fin,
				numero_contrat,
				etablissement_id,
				profil_id,
				anciennete_anterieure_mois,
                anciennete_anterieure_jours) -- utilisé pour l'ancienneté calculée SHS.
				SELECT
					w_F4P01.code_original,
					p_salaries.oid AS salarie_id,
					rh.cti_to_date(F4DC1A, F4DC1M, F4DC1J) AS date_debut,
					CASE WHEN F4DC9A <> 0 THEN rh.cti_to_date(F4DC9A, F4DC9M, F4DC9J) ELSE '20991231' END AS date_fin,
					F4CMATNCNT AS numero_contrat,
					COALESCE(t_etablissements.oid,0) AS etablissement_id,
					p_profils.oid AS profil_id,
                    -- Dans le cas où SHS_ANCIENNETE est à 0 (calcul SHS), F4MAXX et F4JMAXX sont bien renseignés.
                    -- Sinon ils sont à -1 ce qui signifie qu'anciennete_anterieure_mois/jours seront toujours à 0.
                    -- Et cela ne permturbera pas le mode de calcul iCTI lors de la ventilation par mois des contrats.
                    CASE WHEN F4MAXX/12 BETWEEN 0 AND 50 THEN F4MAXX ELSE 0 END AS anciennete_anterieure_mois,
                    CASE WHEN F4MAXX/12 BETWEEN 0 AND 50 THEN F4JAXX ELSE 0 END AS anciennete_anterieure_jours
				FROM w_F4P01
					JOIN rh.t_etablissements ON lpad(F4CENT, 3, '0')||lpad(F4CETS, 3, '0') = t_etablissements.code_original
					JOIN rh.p_salaries ON w_F4P01.salarie_code_original = p_salaries.code_original
					JOIN rh.p_profils ON 1=1
						AND F4TCNT     = type_contrat_code_original
						AND F4CTJN     = type_horaire_code_original
						AND F4MOTD     = motif_debut_code_original
						AND F4MOTF     = motif_fin_code_original
						AND F4CQUA_profil = qualification_code_original
						AND F4SRVC_profil = service_code_original
						AND F4SPEC_profil = specialite_code_original
						AND F4CTTT     = type_temps_travail_code_original
						AND F4CCSP_profil = categorie_socio_professionnelle_code_original
						AND F4CSTT_profil = statut_code_original
						AND F4CEMP_profil = code_emploi_code_original
						AND F4CSOC     = societe_interim_code_original
						AND F4SANA_profil = section_analytique_paie_code_original
						AND F4SCPA     = section_analytique_code_original
						AND F4GRIE     = grille_code_original
						AND F4GRPE     = grille_groupe_code_original
						AND F4GCOT_profil = groupe_cotisant_code_original
					LEFT JOIN rh.p_contrats ON w_F4P01.code_original = p_contrats.code_original
				WHERE p_contrats.oid IS NULL
			;

            -- #correction Correction de l'ancienneté SHS antérieure.
            UPDATE rh.p_contrats SET
                anciennete_anterieure_mois = 0,
                anciennete_anterieure_jours = 0
            FROM rh.p_salaries
            WHERE 1=1
                AND salarie_id = p_salaries.oid
                AND ((p_contrats.date_debut - date_naissance) / 30) - anciennete_anterieure_mois < 150
            ;

			-- #correction @todo : à mettre soit dans un t_divers + expert.
			-- Si les dates d'entrée/sortie d'établissement semblent incohérentes par rapports aux dates des contrats, les corriger.
			UPDATE rh.p_salaries
			SET date_entree_ets = date_debut_contrat
			FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND	date_entree_ets > date_debut_contrat
			;

            -- #correction @todo : à mettre soit dans un t_divers + expert.
			UPDATE rh.p_salaries
			SET date_entree_ets = date_debut_contrat
			FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND to_char(date_entree_ets, 'YYYY')::numeric >= 2009
				AND	date_entree_ets < date_debut_contrat
			;
			
            -- #correction @todo : à mettre soit dans un t_divers + expert.
			UPDATE rh.p_salaries
			SET date_sortie_ets = date_fin_contrat
			FROM (SELECT salarie_id, max(date_fin) AS date_fin_contrat from rh.p_contrats group by 1) AS s
			WHERE 1=1
				AND p_salaries.oid = s.salarie_id
				AND date_fin_contrat > date_sortie_ets
			;

            UPDATE rh.p_salaries
            SET date_entree_ets = s.date_debut_contrat
            FROM (SELECT salarie_id, min(date_debut) AS date_debut_contrat from rh.p_contrats group by 1) AS s
            WHERE 1=1
                AND (select valeur = '1' from rh.t_divers where code = 'CORRECTION_DE_ETS' LIMIT 1)
                AND p_salaries.oid = s.salarie_id
                AND p_salaries.date_entree_ets != s.date_debut_contrat
                AND date_entree_ets = '1900-01-01'::date -- uniquement pour les salariés où la date n'est pas renseignée.
            ;

            UPDATE rh.p_salaries
            SET date_sortie_ets = s.date_fin_contrat
            FROM (SELECT salarie_id, max(date_fin) AS date_fin_contrat from rh.p_contrats group by 1) AS s
            WHERE 1=1
                AND (select valeur = '1' from rh.t_divers where code = 'CORRECTION_DS_ETS' LIMIT 1)
                AND p_salaries.oid = s.salarie_id
                AND p_salaries.date_sortie_ets != s.date_fin_contrat
                AND p_salaries.date_sortie_ets = '2099-12-31'::date -- uniquement pour les salariés où la date n'est pas renseignée.
            ;
            
			-- Màj des salariés.
			UPDATE rh.p_salaries
			SET
				date_debut = subview.date_debut,
				date_fin = subview.date_fin,
				profil_id = subview.profil_id
			FROM
				(
					SELECT salarie_id,
						MIN(date_debut) AS date_debut,
						MAX(date_fin) AS date_fin,
						((base.cti_last(ARRAY[p_contrats.date_fin::text, p_contrats.profil_id::text]))[2])::bigint As profil_id
					FROM rh.p_contrats
					GROUP BY salarie_id
				) AS subview
			WHERE 1=1
				AND p_salaries.oid = subview.salarie_id
				AND (1!=1
					OR p_salaries.date_debut IS DISTINCT FROM subview.date_debut
					OR p_salaries.date_fin   IS DISTINCT FROM subview.date_fin
					OR p_salaries.profil_id  IS DISTINCT FROM subview.profil_id
				)
			;

            -- Calcul ancienneté SHS.
            -- Pas la peine d'alimenter comme dans les autres cas (SHS_ANCIENNETE à 1 ou 2) les 2 champs
            -- anciennete_anterieure_jours et anciennete_anterieure_mois car ils sont déjà bien alimentés
            -- dans le INSERT INTO rh.p_contrats plus haut.
            UPDATE rh.p_contrats SET
                anciennete_anterieure_calculee_mois = COALESCE((
                    SELECT floor(SUM(p_contrats_anterieurs.date_fin - p_contrats_anterieurs.date_debut + 1) / 30)
                    FROM rh.p_contrats p_contrats_anterieurs
                    WHERE p_contrats_anterieurs.salarie_id = p_contrats.salarie_id AND p_contrats_anterieurs.date_fin < p_contrats.date_debut
                ), 0),
                anciennete_anterieure_calculee_jours = COALESCE((
                    SELECT floor(SUM(p_contrats_anterieurs.date_fin - p_contrats_anterieurs.date_debut + 1))
                    FROM rh.p_contrats p_contrats_anterieurs
                    WHERE p_contrats_anterieurs.salarie_id = p_contrats.salarie_id AND p_contrats_anterieurs.date_fin < p_contrats.date_debut
                ), 0)
            WHERE (select valeur = '0' from rh.t_divers where code = 'SHS_ANCIENNETE' LIMIT 1)
            ;

			-- Calcul ancienneté iCTI (au début de contrat).
			UPDATE rh.p_contrats SET
                anciennete_anterieure_jours          = subq.anciennete_jours,
				anciennete_anterieure_calculee_jours = subq.anciennete_jours,
                anciennete_anterieure_mois           = subq.anciennete_mois,
				anciennete_anterieure_calculee_mois  = subq.anciennete_mois
			FROM (
				SELECT
					t1.code_original,
					sum(t2.duree) AS anciennete_jours,
					sum(t2.duree) / 30 AS anciennete_mois
				FROM w_F4P01 AS t1
					JOIN w_F4P01 AS t2 ON 1=1
						AND t2.f4cent = t1.f4cent
						AND t2.f4cmat = t1.f4cmat
						AND t2.f4ncnt < t1.f4ncnt
				group by 1
				) AS subq
			WHERE 1=1
				AND p_contrats.code_original = subq.code_original
                AND anciennete_anterieure_calculee_jours != subq.anciennete_jours
                AND (select valeur = '1' from rh.t_divers where code = 'SHS_ANCIENNETE' LIMIT 1)
			;

            -- Calcul ancienneté iCTI (par rapport à date de début d'entrée ets. SHS sans prendre en compte les contrats).
            with anciennete_2 as (
                select
                    p_contrats.oid as contrat_id,
                    greatest(coalesce(p_contrats.date_debut - p_salaries.date_anciennete, 0), 0) as anciennete_jours,
                    greatest(round(coalesce(p_contrats.date_debut - p_salaries.date_anciennete, 0) / 30.0), 0) as anciennete_mois
                from rh.p_contrats
                    join rh.p_salaries on p_salaries.oid = p_contrats.salarie_id)
            UPDATE rh.p_contrats SET
                anciennete_anterieure_jours          = anciennete_2.anciennete_jours,
                anciennete_anterieure_calculee_jours = anciennete_2.anciennete_jours,
                anciennete_anterieure_mois           = anciennete_2.anciennete_mois,
                anciennete_anterieure_calculee_mois  = anciennete_2.anciennete_mois
            FROM anciennete_2
            WHERE 1=1
                AND p_contrats.oid = anciennete_2.contrat_id
                AND anciennete_anterieure_calculee_jours != anciennete_2.anciennete_jours
                AND (select valeur = '2' from rh.t_divers where code = 'SHS_ANCIENNETE' LIMIT 1)
            ;

			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				nombre_entrees,
				nombre_departs,
				nombre_debut_contrat,
				nombre_fin_contrat,
				est_hors_periode,
				present_debut_mois,
				present_fin_mois,
				equivalent_temps_plein,
                nombre_heures,
                ratio_temps_travail,
				age_id,
				age_jours,
				anciennete_jours,
				anciennete_mois,
				anciennete_annee_id
				)
				SELECT
					p_salaries.oid AS salarie_id,
					p_contrats.oid AS contrat_id,
					p_calendrier_mois.mois AS mois,
					GREATEST(p_calendrier_mois.date_debut, p_contrats.date_debut) AS date_debut,
					LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin) AS date_fin,
					CASE WHEN p_salaries.date_entree_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_entrees,
					CASE WHEN p_salaries.date_sortie_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_departs,
					CASE WHEN p_contrats.date_debut BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_debut_contrat,
					CASE WHEN p_contrats.date_fin BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_fin_contrat,
					'0' AS est_hors_periode,
					CASE WHEN p_calendrier_mois.date_debut BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_debut_mois,
					CASE WHEN p_calendrier_mois.date_fin BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_fin_mois,
					CASE WHEN F4CTPS = 'C' THEN 1 ELSE round(F4NHRE / 151.67,7) END AS equivalent_temps_plein, -- FIXME Prendre depuis la rubrique 1000
                    CASE WHEN F4CTPS = 'C' THEN 151.67 ELSE F4NHRE END as nombre_heures, -- FIXME prendre depuis la rubrique 1000
                    CASE WHEN F4CTPS = 'C' THEN 1 ELSE round(F4NHRE / 151.67,7) END ratio_temps_travail,
					base.cti_age(LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin), p_salaries.date_naissance, 'ny')  AS age_id,
					LEAST(p_calendrier_mois.date_fin, p_contrats.date_fin)::date - p_salaries.date_naissance AS age_jours,
				    (least(p_calendrier_mois.date_fin, p_contrats.date_fin) - p_contrats.date_debut)
                        + greatest(p_contrats.anciennete_anterieure_jours, p_contrats.anciennete_anterieure_calculee_jours)
						+ 1
					AS anciennete_jours,
					base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
                        + greatest(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois)
					AS anciennete_mois,
					floor(
						(
							base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
							+ greatest(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois)
						) / 12
					) AS anciennete_annee_id
				FROM rh.p_contrats
					JOIN rh.p_salaries ON (p_contrats.salarie_id = p_salaries.oid)
					JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
					JOIN rh.t_entreprises ON t_etablissements.entreprise_id = t_entreprises.oid
					JOIN w_F4P01 ON 1=1
						AND p_contrats.code_original = w_F4P01.code_original
						AND lpad(F4CENT, 3, '0') = t_entreprises.code_original
					JOIN prod_shs.rhlib_F1P01 ON lpad(F1CENT, 3, '0')||lpad(F1CETS, 3, '0') = t_etablissements.code_original
					JOIN base.p_calendrier_mois ON 1=1
						AND p_contrats.date_debut <= p_calendrier_mois.date_fin
						AND p_contrats.date_fin >= p_calendrier_mois.date_debut
				WHERE 1=1
					AND p_calendrier_mois.mois >= to_char(rhp('rhprovider_start')::date, 'YYYYMM')
					AND p_calendrier_mois.mois <= (F1DFPA * 100 + F1DFPM)
				ORDER BY numero_contrat, p_calendrier_mois.mois
			;

			-- Affection du contrat_id nouvelle créé à la table temp des paies (version contrat _0).
			UPDATE w_J0P01_0
			SET	contrat_id = p_contrats.oid
			FROM rh.p_contrats
			WHERE contrat_code_original = p_contrats.code_original
			;

			-- Le n° de contrat a disparu (remplacé par un autre)
			UPDATE w_J0P01_0
			SET	contrat_id = p_contrats.oid
			FROM rh.p_salaries
				JOIN rh.p_contrats ON p_salaries.oid = p_contrats.salarie_id
			WHERE 1=1
				AND w_J0P01_0.contrat_id = 0
				AND salarie_code_original = p_salaries.code_original
				AND w_J0P01_0.date_debut BETWEEN p_contrats.date_debut AND p_contrats.date_fin
			;

			UPDATE w_J0P01_0
			SET	contrat_id = p_contrats.oid
			FROM rh.p_salaries
				JOIN rh.p_contrats ON p_salaries.oid = p_contrats.salarie_id
			WHERE 1=1
				AND w_J0P01_0.contrat_id = 0
				AND salarie_code_original = p_salaries.code_original
				AND w_J0P01_0.date_fin BETWEEN p_contrats.date_debut AND p_contrats.date_fin
			;

			-- Màj du contrat_mois_id.
			UPDATE w_J0P01_0
			SET	contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			WHERE 1=1
				AND contrat_mois_id = 0
				AND w_J0P01_0.contrat_id = p_contrats_mois.contrat_id
				AND mois_paie = p_contrats_mois.mois_activite
			;

			INSERT INTO rh.p_contrats_mois(
				contrat_id,
				salarie_id,
				mois_activite,
				date_debut,
				date_fin,
				nombre_debut_contrat,
				nombre_fin_contrat,
				equivalent_temps_plein,
                nombre_heures,
                ratio_temps_travail,
				age_id,
				age_jours,
				est_hors_periode,
				present_fin_mois,
				anciennete_jours,
				anciennete_mois,
				anciennete_annee_id)
			SELECT
				contrat_id,
				p_contrats.salarie_id,
				mois_paie AS mois_activite,
				GREATEST(w_J0P01_0.date_debut, date(date_trunc('month',w_J0P01_0.date_fin))) AS date_debut,
				w_J0P01_0.date_fin,
				0 AS nombre_debut_contrat,
				0 AS nombre_fin_contrat,
				0 AS equivalent_temps_plein,
                0 as nombre_heures,
                ratio_temps_travail,
				base.cti_age(w_J0P01_0.date_fin, p_salaries.date_naissance, 'ny')  AS age_id,
				w_J0P01_0.date_fin::date - p_salaries.date_naissance AS age_jours,
				'1' AS est_hors_periode,
				0 AS present_fin_mois,
					(w_J0P01_0.date_fin::date - p_contrats.date_debut::date)
					+ 
					p_contrats.anciennete_anterieure_jours
					+ 1 
				AS anciennete_jours,
				base.cti_age(
						date_trunc('month',w_J0P01_0.date_fin)::date,
						date_trunc('month',p_contrats.date_debut)::date,
						'nm'
					)
					+ 
					GREATEST(
						p_contrats.anciennete_anterieure_mois,
						p_contrats.anciennete_anterieure_calculee_mois
					) + 1 
					AS anciennete_mois,
				floor((base.cti_age(date_trunc('month',w_J0P01_0.date_fin::date)::date, date_trunc('month',p_contrats.date_debut)::date, 'nm')
					+ GREATEST(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) + 1) / 12) AS anciennete_annee_id
			FROM w_J0P01_0
				JOIN rh.p_salaries ON w_J0P01_0.salarie_id = p_salaries.oid
				JOIN rh.p_contrats ON w_J0P01_0.contrat_id = p_contrats.oid
			WHERE contrat_mois_id = 0
			;

			UPDATE w_J0P01_0
			SET	contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			WHERE 1=1
				AND contrat_mois_id = 0
				AND w_J0P01_0.contrat_id = p_contrats_mois.contrat_id
				AND mois_paie = p_contrats_mois.mois_activite
			;

			UPDATE w_J0P01_0
			SET contrat_mois_id = p_contrats_mois.oid
			FROM rh.p_contrats_mois
			WHERE 1=1
				AND contrat_mois_id = 0
				AND w_J0P01_0.contrat_id = p_contrats_mois.contrat_id
				AND mois_paie = p_contrats_mois.mois_activite
			;

			-- Salariés remplacés
			DROP TABLE IF EXISTS w_remplacements
			;
			CREATE TEMP TABLE w_remplacements AS
				SELECT
					p_contrats.oid AS contrat_id,
					(MIN(Array[to_char(F5NLIG,'FM000'), p_salaries.oid::text]))[2]::bigint AS salarie_remplace_id
				FROM rh.p_contrats
					JOIN prod_shs.rhlib_F5P01 ON 1=1
						AND p_contrats.code_original = to_char(F5CENT,'FM000') || to_char(F5CETS,'FM000') || F5CMAT || '-' || to_char(F5NCNT,'FM000')
						AND F5NLIG = 1
					JOIN w_etablissements_select ON XXCENT = F5CENT AND XXCETS = F5CETS
					JOIN rh.p_salaries ON (to_char(F5CENT,'FM000') || F5AMAT) = p_salaries.code_original
				WHERE 1=1
					AND F5AMAT IN (
						SELECT F4CMAT 
						FROM prod_shs.rhlib_F4P01 
						JOIN w_etablissements_select ON XXCENT = F4CENT AND XXCETS = F4CETS
						WHERE F4SUSP <> 9 )
				GROUP BY 1
			;

			UPDATE rh.p_contrats
				SET salarie_remplace_id = w_remplacements.salarie_remplace_id
			FROM w_remplacements
			WHERE 1=1
				AND p_contrats.oid = w_remplacements.contrat_id
				AND p_contrats.salarie_remplace_id IS DISTINCT FROM w_remplacements.salarie_remplace_id
			;

			UPDATE rh.p_contrats
			SET salarie_remplace_id = 0
			WHERE 1=1
				AND salarie_remplace_id IS DISTINCT FROM 0
				AND oid NOT IN (SELECT contrat_id FROM w_remplacements)
			;

			-- Contrats suspendus
			UPDATE rh.p_contrats_mois
			SET
				est_hors_periode = CASE WHEN subq.present_debut_mois = 0 AND subq.present_fin_mois = 0 THEN 1 ELSE 0 END,
				present_debut_mois = subq.present_debut_mois,
				present_fin_mois = subq.present_fin_mois
			FROM (
				SELECT
					p_calendrier_mois.mois,
					p_contrats.oid AS contrat_id,
					CASE WHEN p_calendrier_mois.date_debut >= rh.cti_to_date(f4ddsa,f4ddsm,f4ddsj)::date then 1 else 0 end AS present_debut_mois,
					CASE WHEN p_calendrier_mois.date_fin <= rh.cti_to_date(f4dfsa,f4dfsm,f4dfsj)::date then 1 else 0 end AS present_fin_mois
				FROM w_F4P01
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_F4P01.code_original
					JOIN base.p_calendrier_mois ON base.cti_overlaps(
						p_calendrier_mois.date_debut,
						p_calendrier_mois.date_fin,
						rh.cti_to_date(f4ddsa,f4ddsm,f4ddsj)::date,
						rh.cti_to_date(f4dfsa,f4dfsm,f4dfsj)::date)
				WHERE 1=1
					AND f4susp != 0 -- qui a un motif de suspension renseigné
				GROUP BY 1,2,3,4
				) AS subq
			WHERE 1=1
				AND p_contrats_mois.contrat_id = subq.contrat_id
				AND p_contrats_mois.mois_activite = subq.mois
			;

			-- Pour info : trouver l'"effectif inscrit" :
			/*
			
			select f4tcnt,count(* )
			from prod_shs.piprso226_f4p01
			where 1=1
				and '2005-11-30'::date between (f4dc1a::text||'-'||f4dc1m::text||'-'||f4dc1j::text)::date and (case when (f4dc9a::text||f4dc9m::text||f4dc9j::text) = '000' then '2099-12-31' else (f4dc9a::text||'-'||f4dc9m::text||'-'||f4dc9j::text) end)::date
				and case when f4susp != 0 then ('2005-11-30'::date not between (f4ddsa||'-'||f4ddsm||'-'||f4ddsj)::date and (f4dfsa||'-'||f4dfsm||'-'||f4dfsj)::date) else true end
				and f4cets = 0
				and f4cent = 0
			group by 1
			order by 1
			
			-- Correction date depart non saisie selon code sortie et date dernier contrat
			UPDATE rh.p_salaries
			SET date_sortie_ets = subview.date_sortie_ets
			FROM
			(
			SELECT p_salaries.oid, MAX(p_contrats.date_fin) AS date_sortie_ets
			FROM rh.p_salaries
				JOIN rh.p_contrats ON p_contrats.salarie_id = p_salaries.oid
				JOIN prod_shs.rhlib_F3P01 ON p_salaries.code_original = (to_char(F3CENT,'FM000')||F3CMAT) AND F3CPST = '1'
			WHERE date_sortie_ets = '20991231'
			GROUP BY 1
			) subview
			WHERE p_salaries.oid = subview.oid

			 */
			
			DROP TABLE IF EXISTS w_departs
			;

			CREATE TEMP TABLE w_departs AS
				SELECT
					F3CMAT,
					p_salaries.oid AS salarie_id,
					(MAX(ARRAY[p_contrats_mois.date_fin::text, p_contrats_mois.oid::text]))[2]::bigint AS oid
				FROM rh.p_contrats_mois
					JOIN rh.p_contrats ON p_contrats_mois.contrat_id = p_contrats.oid AND nombre_fin_contrat = 1
					JOIN rh.p_salaries ON p_contrats.salarie_id = p_salaries.oid
					JOIN prod_shs.rhlib_F3P01 ON p_salaries.code_original = (to_char(F3CENT,'FM000')||F3CMAT) AND F3CPST = '1'
					JOIN w_entreprises_select ON XXCENT = F3CENT
				WHERE 1=1
					AND rh.cti_to_date(F3DS9A, F3DS9M, F3DS9J) >= p_contrats_mois.date_fin
				GROUP BY 1,2
			;

			UPDATE rh.p_contrats_mois
			SET	nombre_departs = 1
			FROM w_departs
			WHERE p_contrats_mois.oid = w_departs.oid
			;

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

			-- Désactivation des index
			SELECT base.cti_stash_table_indexes('rh', 'p_historique_paie')
			;

			TRUNCATE rh.p_historique_paie
			;

			INSERT INTO rh.p_historique_paie(
				salarie_id,
				contrat_id,
				contrat_mois_id,
				profil_id,
				mois_activite,
				date_debut,
				date_fin,
				mois_paie,
				date_paie,
				rubrique_id,
				organisme_cotisation_id,
				base,
				montant_brut,
				montant_avantage_nature,
				montant_frais_imposables,
				taux_cotisation_salarie,
				montant_cotisation_salarie,
				taux_cotisation_patronale,
				montant_cotisation_patronale,
				montant_od_net_salarie,
				montant_net_imposable_salarie,
				montant_net_a_payer_salarie
				)
				SELECT
					w_J0P01_0.salarie_id,
					w_J0P01_0.contrat_id,
					w_J0P01_0.contrat_mois_id,
					w_J0P01_0.profil_id,
					date_part('year',w_J0P01_0.date_fin) * 100 + date_part('month',w_J0P01_0.date_fin),
					w_J0P01_0.date_debut,
					w_J0P01_0.date_fin,
					w_J0P01_0.mois_paie,
					w_J0P01_0.date_paie,
					COALESCE(w_cti_rubriques.in_id,0) AS rubrique_id,
					COALESCE(w_cti_organismes_cotisation.in_id,0) AS organisme_cotisation_id,
					J0BASE AS base,
					CASE WHEN j0chap = '10' AND J0CRUB < 3000 THEN j0mont ELSE 0 END AS montant_brut,
					CASE WHEN j0chap = '10' AND J0CRUB BETWEEN 3000 AND 3499 THEN j0mont ELSE 0 END AS montant_avantage_nature,
					CASE WHEN j0chap = '10' AND J0CRUB BETWEEN 3500 AND 3999 THEN j0mont ELSE 0 END AS montant_frais_imposables,
					CASE WHEN j0chap = '10' THEN j0prix WHEN j0chap = '20' THEN j0prix ELSE 0 END as taux_cotisation_salarie,
					CASE WHEN j0chap = '20' AND (j0crub BETWEEN 4000 AND 6999 OR j0crub > 9000) THEN 0 - j0mont ELSE 0 END AS montant_cotisation_salarie,
					CASE WHEN j0chap = '20' THEN j0tpat ELSE 0 END AS taux_cotisation_patronale,
					CASE WHEN j0chap = '20' OR t_rubriques.code_calcul = '8' THEN j0mpat ELSE 0 END AS montant_cotisation_patronale,
					CASE
						WHEN j0chap = '20' AND (j0crub BETWEEN 7000 AND 8999 OR j0crub > 9000)  THEN 0 - j0mont
						WHEN j0chap = '30' THEN 0 - j0mont
						ELSE 0
					END AS montant_od_net_salarie,
                    CASE WHEN t_rubriques.code_calcul = '7' THEN j0mpat ELSE 0 END +
					CASE
						WHEN j0chap = '10' THEN j0mont
						WHEN j0chap = '20' AND (j0crub BETWEEN 4000 AND 6999 OR j0crub > 9000)  THEN j0mont
						ELSE 0
					END AS montant_net_imposable_salarie,
					CASE
						WHEN j0chap = '10' AND (CASE WHEN rhp('opt_avt_nature') = '1' THEN (J0CRUB NOT BETWEEN 3000 AND 3499) ELSE true END) THEN j0mont
						WHEN j0chap = '20' THEN j0mont
						WHEN j0chap = '30' THEN j0mont
						ELSE 0
					END AS montant_net_a_payer_salarie
				FROM wh_J0P01 -- Historique de paie des mois clôturés
					JOIN w_J0P01_0 ON 1=1
						AND wh_J0P01.J0SMKEY = w_J0P01_0.J0SMKEY_0
						AND est_historique = 'H'
					JOIN w_cti_rubriques ON 
						J0CENT = w_cti_rubriques.XXCENT AND
						J0CETS = w_cti_rubriques.XXCETS AND
						J0CRUB = w_cti_rubriques.XXCODO
                    JOIN rh.t_rubriques ON t_rubriques.code_original = w_cti_rubriques.in_code_original
                    LEFT JOIN w_cti_organismes_cotisation ON
                        J0CENT = w_cti_organismes_cotisation.XXCENT AND
                        J0CETS = w_cti_organismes_cotisation.XXCETS AND
                        J0NORG = w_cti_organismes_cotisation.XXCODO
				WHERE wh_J0P01.j0dfpa >= to_char(rhp('rhprovider_start')::date, 'YYYY')
			;

			
            -- La table principale pour les mois non clotures est F9P01 mais il peut aussi y avoir quelques rubriques dans F6P01
            -- F6CGEN = '6' et F6MONT > 0 sont des garde-fous
            DROP TABLE IF EXISTS w_F69P01; CREATE TEMP TABLE w_F69P01 AS
            (
                SELECT
                    F9BASE,
                    F9CENT,
                    F9CETS,
                    F9CHAP,
                    F9CMAT,
                    F9CRUB,
                    F9MONT,
                    F9MPAT,
                    F9NCNT,
                    F9NORG,
                    F9PRIX,
                    F9TPAT,
                    F9CENT::text || F9CETS::text || F9CRUB::text  || F9CMAT::text || F9DA1A::text || F9DA1M::text || F9DA9A::text || F9DA9M::text as F9CKEY
                FROM
                    prod_shs.rhlib_F9P01
            );
            INSERT INTO w_F69P01
                SELECT
                    F6BASE,
                    F6CENT,
                    F6CETS,
                    '10'::text AS F9CHAP,
                    F6CMAT,
                    F6CRUB,
                    F6MONT,
                    0 AS F9MPAT,
                    F6NCNT,
                    '' AS F9NORG,
                    F6PRIX,
                    0 AS F6TPAT,
                    '' as F9CKEY
                FROM
                    prod_shs.rhlib_F6P01
                WHERE 1=1
                    AND F6CGEN = '6'
                    AND F6MONT > 0
                    AND F6CENT::text || F6CETS::text || F6CRUB::text  || F6CMAT::text || F6DA1A::text || F6DA1M::text || F6DA9A::text || F6DA9M::text != ALL (ARRAY(SELECT F9CKEY FROM w_F69P01 GROUP BY 1)::text[]);
                    
            INSERT INTO rh.p_historique_paie(
				salarie_id,
				contrat_id,
				contrat_mois_id,
				profil_id,
				mois_activite,
				date_debut,
				date_fin,
				mois_paie,
				date_paie,
				rubrique_id,
				organisme_cotisation_id,
				base,
				montant_brut,
				montant_avantage_nature,
				montant_frais_imposables,
				taux_cotisation_salarie,
				montant_cotisation_salarie,
				taux_cotisation_patronale,
				montant_cotisation_patronale,
				montant_od_net_salarie,
				montant_net_imposable_salarie,
				montant_net_a_payer_salarie
				)
				SELECT
					w_J0P01_0.salarie_id,
					w_J0P01_0.contrat_id,
					w_J0P01_0.contrat_mois_id,
					w_J0P01_0.profil_id,
					date_part('year',w_J0P01_0.date_fin) * 100 + date_part('month',w_J0P01_0.date_fin),
					w_J0P01_0.date_debut,
					w_J0P01_0.date_fin,
					w_J0P01_0.mois_paie,
					w_J0P01_0.date_paie,
					COALESCE(w_cti_rubriques.in_id,0) AS rubrique_id,
					COALESCE(w_cti_organismes_cotisation.in_id,0) AS organisme_cotisation_id,
					F9BASE AS base,
					CASE WHEN F9chap = '10' AND F9CRUB < 3000 THEN F9mont ELSE 0 END AS montant_brut,
					CASE WHEN F9chap = '10' AND F9CRUB BETWEEN 3000 AND 3499 THEN F9mont ELSE 0 END AS montant_avantage_nature,
					CASE WHEN F9chap = '10' AND F9CRUB BETWEEN 3500 AND 3999 THEN F9mont ELSE 0 END AS montant_frais_imposables,
					CASE WHEN F9chap = '10' THEN F9prix WHEN F9chap = '20' THEN F9prix ELSE 0 END as taux_cotisation_salarie,
					CASE WHEN F9chap = '20' AND (F9crub BETWEEN 4000 AND 6999 OR F9crub > 9000) THEN 0 - F9mont ELSE 0 END AS montant_cotisation_salarie,
					CASE WHEN F9chap = '20' THEN F9tpat ELSE 0 END AS taux_cotisation_patronale,
					CASE WHEN F9chap = '20' OR t_rubriques.code_calcul = '8' THEN F9mpat ELSE 0 END AS montant_cotisation_patronale,
					CASE
						WHEN F9chap = '20' AND (F9crub BETWEEN 7000 AND 8999 OR F9crub > 9000)  THEN 0 - F9mont
						WHEN F9chap = '30' THEN 0 - F9mont
						ELSE 0
					END AS montant_od_net_salarie,
                    CASE WHEN t_rubriques.code_calcul = '7' THEN F9tpat ELSE 0 END +
					CASE
						WHEN F9chap = '10' THEN F9mont
						WHEN F9chap = '20' AND (F9crub BETWEEN 4000 AND 6999 OR F9crub > 9000)  THEN F9mont
						ELSE 0
					END AS montant_net_imposable_salarie,
					CASE
						WHEN F9chap = '10' AND (CASE WHEN rhp('opt_avt_nature') = '1' THEN (F9CRUB NOT BETWEEN 3000 AND 3499) ELSE true END) THEN F9mont
						WHEN F9chap = '20' THEN F9mont
						WHEN F9chap = '30' THEN F9mont
						ELSE 0
					END AS montant_net_a_payer_salarie
				FROM w_F69P01 -- mois non clôturé
					JOIN prod_shs.rhlib_F1P01 ON 1=1
						AND F9CENT = F1CENT
						AND F9CETS = F1CETS
					JOIN w_J0P01_0 ON 1=1
						AND w_F69P01.F9CENT = w_J0P01_0.J0CENT_0
						AND w_F69P01.F9CETS = w_J0P01_0.J0CETS_0
						AND w_F69P01.F9CMAT = w_J0P01_0.J0CMAT_0
						AND w_F69P01.F9NCNT = w_J0P01_0.J0NCNT_0
						AND rhlib_F1p01.F1DFPA = w_J0P01_0.J0DFPA_0
						AND rhlib_F1p01.F1DFPM = w_J0P01_0.J0DFPM_0
						AND est_historique = ''
					JOIN w_cti_rubriques ON 
						F9CENT = w_cti_rubriques.XXCENT AND
						F9CETS = w_cti_rubriques.XXCETS AND
						F9CRUB = w_cti_rubriques.XXCODO
                    JOIN rh.t_rubriques ON t_rubriques.code_original = w_cti_rubriques.in_code_original
					LEFT JOIN w_cti_organismes_cotisation ON
						F9CENT = w_cti_organismes_cotisation.XXCENT AND
						F9CETS = w_cti_organismes_cotisation.XXCETS AND
						F9NORG = w_cti_organismes_cotisation.XXCODO
			;

			-- Correction des périodes incohérentes.
			UPDATE rh.p_historique_paie
			SET	date_debut = date_fin
			WHERE date_debut > date_fin
			;

			-- Re-activation des index
			SELECT base.cti_stash_pop_table_indexes('rh', 'p_historique_paie')
			;

            -- Mise à 0 de l'ETP si pas d'heures payées.
            UPDATE rh.p_contrats_mois
            SET equivalent_temps_plein = 0
            WHERE 1=1
                AND equivalent_temps_plein <> 0
                AND oid NOT IN
                    (SELECT contrat_mois_id
                    FROM rh.p_historique_paie
                    WHERE rubrique_id IN 
                        (SELECT oid FROM rh.t_rubriques WHERE code = '0099'))
            ;

            -- Renseigner les heures contrats à partir de la rubriques d'heures salaire de base conventionnel lorsque le nombre d'heures contrat n'est pas renseigné.
            UPDATE rh.p_contrats_mois SET
                nombre_heures = 0
            ;
            
            UPDATE rh.p_contrats_mois SET
                nombre_heures = subq.nombre_heures
            FROM (
                SELECT
                    contrat_mois_id,
                    sum(base) as nombre_heures
                FROM rh.p_historique_paie
                WHERE rubrique_id IN (SELECT oid FROM rh.t_rubriques WHERE code = '1000')
                GROUP BY 1) as subq
            WHERE 1=1
                AND p_contrats_mois.oid = subq.contrat_mois_id
                AND p_contrats_mois.nombre_heures = 0
            ;

            -- Appliquer le type de temps de travail pour les rubriques de paie ayant une base != valeur absolue de 1.
            -- UPDATE rh.p_historique_paie SET

            -- FROM () as subq
            -- WHERE 1=1
            --     AND p_contrats_mois.oid = subq.contrat_mois_id
            --     AND p_contrats_mois.nombre_heures = 0
            -- ;

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

			-- Alimentation des profils simultanés.
			TRUNCATE rh.p_profil_contrat_mois
			;

			INSERT INTO rh.p_profil_contrat_mois (
				profil_id,
				contrat_mois_id,
				salarie_id,
				ratio,
				mois
				)
				SELECT
					coalesce(w_J0P01_0.profil_id, p_contrats.profil_id) AS profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					1 AS ratio,
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
					JOIN rh.p_contrats ON p_contrats.oid = p_contrats_mois.contrat_id
					LEFT JOIN w_J0P01_0 ON w_J0P01_0.contrat_mois_id = p_contrats_mois.oid
				GROUP BY 1,2,3,4,5
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Arrêts de travail">
			<sqlcmd><![CDATA[

			TRUNCATE rh.p_arrets_travail
			;

			ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
			;
			
			DROP TABLE IF exists w_N6p01;
			CREATE TEMP TABLE w_N6p01 As
			SELECT ''::text AS N6MOPR_code_original,* FROM prod_shs.rhlib_N6p01
			;
			
			UPDATE w_N6p01
			SET
				N6MOPR_code_original = w_cti_precisions_motif_arret.in_code_original
			FROM
				w_cti_precisions_motif_arret
			WHERE
				N6CENT = XXCENT AND
				N6CETS = XXCETS AND
				N6MOPR = XXCODO AND
				N6MOPR_code_original <> in_code_original
			;

			INSERT INTO rh.p_arrets_travail(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				date_reprise,
				motif_arret_id,
				precision_motif_arret_id,
				nb_jours
				)
				SELECT
					p_salaries.oid AS salarie_id,
					(max(ARRAY[extract(epoch from p_contrats.date_debut), p_contrats.oid]))[2] AS contrat_id,
					N6D1AA * 100 + N6D1AM AS mois_activite,
					rh.cti_to_date(N6D1AA, N6D1AM, N6D1AJ) AS date_debut,
					CASE WHEN N6D9AA <> 0 THEN rh.cti_to_date(N6D9AA, N6D9AM, N6D9AJ) ELSE '20991231' END AS date_fin,
					CASE
						WHEN N6DREA BETWEEN 1900 AND 2020 THEN rh.cti_to_date(N6DREA, N6DREM, N6DREJ) 
						WHEN N6D9AA <> 0 THEN rh.cti_to_date(N6D9AA, N6D9AM, N6D9AJ)::date + 1
						ELSE '20991231' END AS date_reprise,
					COALESCE(t_motifs_arret.oid, 0) AS motif_arret_id,
					COALESCE(t_precisions_motif_arret.oid, 0) AS precision_motif_arret_id,
					N6NJOU AS nb_jours
				FROM w_N6p01
					JOIN w_etablissements_select ON XXCENT = N6CENT AND XXCETS = N6CETS
					JOIN rh.p_salaries ON (to_char(N6CENT,'FM000')||N6CMAT) = p_salaries.code_original
					JOIN rh.p_contrats ON 1=1
						AND p_contrats.salarie_id = p_salaries.oid
						AND base.cti_overlaps(
							p_contrats.date_debut,
							p_contrats.date_fin,
							rh.cti_to_date(N6D1AA, N6D1AM, N6D1AJ),
							CASE WHEN N6D9AA <> 0 THEN rh.cti_to_date(N6D9AA, N6D9AM, N6D9AJ) ELSE '20991231' END)
					LEFT JOIN rh.t_motifs_arret ON (N6MOTA = t_motifs_arret.code_original)
					LEFT JOIN rh.t_precisions_motif_arret ON (N6MOPR_code_original = t_precisions_motif_arret.code_original)
				GROUP BY 1,3,4,5,6,7,8,9
			;

			-- Correction des dates de reprises saisies entre les dates de début/fin des arrêts.
			-- #correction
			UPDATE rh.p_arrets_travail
			SET date_reprise = date_fin + 1
			WHERE base.cti_overlaps(date_reprise, date_reprise, date_debut, date_fin)
			;

			-- Màj des dates de reprise à date_fin + 1 lorsque plusieurs arrêts consécutifs ont tous la même date de reprise.
			-- Le drapeau nb_reprise_apres_arret dans p_arrets_travail_mois sera tout de même positionné à 0 afin qu'un seul arrêt
			-- donne lieu à une seule reprise.
			/* EXEMPLE :
			 Avant :
			 	   debut      fin      reprise    drapeau
			 	2005-02-28 2005-03-13 2005-02-05     1
				2005-03-14 2005-03-27 2005-02-05     1
				2005-03-28 2005-07-17 2005-02-05     1

			 Après :
			 	   debut      fin      reprise    drapeau
			 	2005-02-28 2005-03-13 2005-03-14     0
				2005-03-14 2005-03-27 2005-03-28     0
				2005-03-28 2005-07-17 2005-02-05     1

			 */
			UPDATE rh.p_arrets_travail
			SET date_reprise = subq.date_reprise
			FROM (
				SELECT 
					t1.oid,
					t1.mois_activite,
					min(case when t1.date_fin + '1 day'::interval =  t2.date_debut THEN t1.date_fin + '1 day'::interval ELSE t1.date_reprise END) AS date_reprise
				FROM rh.p_arrets_travail AS t1
					LEFT JOIN rh.p_arrets_travail AS t2 ON 1=1
						AND t1.salarie_id = t2.salarie_id
						AND t1.date_debut != t2.date_debut
						AND t1.date_fin != t2.date_fin
				GROUP BY t1.oid, t1.mois_activite
				ORDER BY 2 
				) AS subq
			WHERE 1=1
				AND p_arrets_travail.oid = subq.oid
				AND p_arrets_travail.mois_activite = subq.mois_activite
			;

			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_arret,
				nb_debut_arret,
				nb_fin_arret,
				nb_reprise_apres_arret,
				date_debut,
				date_fin,
				nb_jours
				)
				SELECT
					arr.oid AS arret_travail_id,
					arr.salarie_id AS salarie_id,
					cnt.contrat_id AS contrat_id,
					cnt.oid AS contrat_mois_id,
					cal.mois AS mois_activite,
					CASE WHEN base.cti_overlaps(arr.date_debut, arr.date_fin, cnt.date_debut, cnt.date_fin) THEN 1 ELSE 0 END AS nb_arret,
					CASE WHEN arr.date_debut BETWEEN cnt.date_debut AND cnt.date_fin THEN 1 ELSE 0 END AS nb_debut_arret,
					CASE WHEN arr.date_fin BETWEEN cnt.date_debut AND cnt.date_fin THEN 1 ELSE 0 END AS nb_fin_arret,
					CASE WHEN arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin THEN 1 ELSE 0 END AS nb_reprise_apres_arret,
					CASE 
						WHEN base.cti_overlaps(arr.date_debut, arr.date_fin, cal.date_debut, cal.date_fin) 
						THEN GREATEST(cnt.date_debut, arr.date_debut) 
						ELSE arr.date_reprise 
					END AS date_debut,
					CASE
						WHEN base.cti_overlaps(arr.date_debut, arr.date_fin, cal.date_debut, cal.date_fin)
						THEN LEAST(cnt.date_fin, arr.date_fin)
						ELSE arr.date_reprise
					END AS date_fin,
					CASE 
						WHEN base.cti_overlaps(arr.date_debut, arr.date_fin, cal.date_debut, cal.date_fin) 
						THEN
							CASE WHEN LEAST(cnt.date_fin, arr.date_fin)::date >= GREATEST(cnt.date_debut, arr.date_debut)::date
								THEN LEAST(cnt.date_fin, arr.date_fin)::date - GREATEST(cnt.date_debut, arr.date_debut)::date + 1
								ELSE 0
							END 
						ELSE 0
					END AS nb_jours
				FROM base.p_calendrier_mois AS cal
					JOIN rh.p_arrets_travail AS arr ON 1!=1
						OR base.cti_overlaps(arr.date_debut, arr.date_fin, cal.date_debut, cal.date_fin)
						OR (1=1
							AND arr.date_reprise BETWEEN cal.date_debut AND cal.date_fin
							AND arr.date_reprise != '2099-12-31')
					JOIN rh.p_contrats_mois AS cnt ON 1=1
						AND cnt.salarie_id = arr.salarie_id
						AND base.cti_overlaps(cnt.date_debut, cnt.date_fin, cal.date_debut, cal.date_fin)
						AND base.cti_overlaps(cnt.date_debut, cnt.date_fin, arr.date_debut, arr.date_reprise)
						AND est_hors_periode = '0'
						AND fictif = '0'
				WHERE 1=1
					AND cal.mois >= to_char(rhp('rhprovider_start')::date, 'YYYYMM')
			;

			-- Màj des ventil d'arrêts hors contrat (contrat_mois_id IS NULL)
			/*
			:: DEV EN COURS :: DEV EN COURS :: DEV EN COURS :: DEV EN COURS :: DEV EN COURS ::
			UPDATE rh.p_arrets_travail_mois
			SET contrat_mois_id = subq.contrat_mois_id
			FROM
			:: DEV EN COURS :: DEV EN COURS :: DEV EN COURS :: DEV EN COURS :: DEV EN COURS :: DEV EN COURS ::
			*/

			-- Màj des reprises.
			/*UPDATE rh.p_arrets_travail_mois
			SET nb_reprise_apres_arret = subq.nb_reprise_apres_arret
			FROM (
				SELECT 
					t1.arret_travail_id,
					t1.mois_activite,
					min(case when p_arrets_travail.date_reprise between t2.date_debut AND t2.date_fin then 0 else 1 end) AS nb_reprise_apres_arret
				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.date_debut != t2.date_debut
						AND t1.date_fin != t2.date_fin
				GROUP BY t1.arret_travail_id, t1.mois_activite
				ORDER BY 2 DESC
				) AS subq
			WHERE 1=1
				AND p_arrets_travail_mois.arret_travail_id = subq.arret_travail_id
				AND p_arrets_travail_mois.mois_activite = subq.mois_activite
			;*/

			]]></sqlcmd>
		</NODE>
        <NODE label="Option : remplacement motif par précision.">
            <condition><![CDATA[
                
            select valeur = '1'
            from rh.t_divers
            where code = 'SHS_MOTIF'
            ;

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

            TRUNCATE rh.t_motifs_arret
            ;

            INSERT INTO rh.t_motifs_arret(oid, code, texte, texte_court, code_original)
				SELECT oid, code, texte, texte_court, code_original
				FROM rh.t_precisions_motif_arret
			;

            UPDATE rh.p_arrets_travail SET
                motif_arret_id = precision_motif_arret_id
            WHERE motif_arret_id IS DISTINCT FROM precision_motif_arret_id
            ;

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

			-- Création d'une table temporaire
			DROP TABLE IF EXISTS w_visites
			;
			CREATE TEMP TABLE w_visites AS
				SELECT
					f6cent AS ent,
					f6cets AS ets,
					p_salaries.oid AS salarie_id,
					0 as motif,
					(lpad(f6annr, 4, '0')||lpad(f6moir, 2, '0'))::numeric AS mois_activite,
					(lpad(f6annr, 4, '0')||lpad(f6moir, 2, '0')||lpad(f6jour, 2, '0'))::date as date,
					max(p_contrats_mois.oid) as contrat_mois_id,
					max(p_contrats_mois.contrat_id) as contrat_id,
					t_motifs_visite.oid AS motif_visite_id
				FROM prod_shs.rhlib_f6p21
					JOIN w_etablissements_select ON XXCENT = F6CENT AND XXCETS = F6CETS
					JOIN rh.p_salaries ON p_salaries.code_original = (to_char(rhlib_f6p21.f6cent,'FM000')||rhlib_f6p21.f6cmat)
					JOIN rh.t_motifs_visite ON t_motifs_visite.code_original = rhlib_f6p21.f6tvis
					JOIN rh.p_contrats_mois ON 1=1
						AND p_contrats_mois.salarie_id = p_salaries.oid
						AND base.cti_overlaps((lpad(f6annr, 4, '0')||lpad(f6moir, 2, '0')||lpad(f6jour, 2, '0'))::date, (lpad(f6annr, 4, '0')||lpad(f6moir, 2, '0')||lpad(f6jour, 2, '0'))::date, p_contrats_mois.date_debut, p_contrats_mois.date_fin)
					JOIN rh.p_contrats ON p_contrats.oid = p_contrats_mois.contrat_id
					JOIN rh.t_etablissements ON 1=1
						AND t_etablissements.oid = p_contrats.etablissement_id
						AND t_etablissements.code_original = lpad(f6cent, 3, '0')||lpad(f6cets, 3, '0')
				WHERE 1=1
					AND lpad(f6annr, 4, '0') BETWEEN to_char(rhp('rhprovider_start')::date, 'YYYY') AND 2050
					AND (lpad(f6annr, 4, '0')||lpad(f6moir, 2, '0')||lpad(f6jour, 2, '0'))::date >= to_char(rhp('rhprovider_start')::date, 'YYYY')
				GROUP BY 1,2,3,4,5,6,9
			;

			-- Peuplement de rh.p_visites_medicales
			TRUNCATE rh.p_visites_medicales
			;

			ALTER SEQUENCE rh.s_visites_medicales RESTART WITH 1
			;

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

			]]></sqlcmd>
		</NODE>
		<NODE label="Accidents du travail">
			<sqlcmd><![CDATA[

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

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

			TRUNCATE rh.p_handicap
			;

			ALTER SEQUENCE rh.s_handicap RESTART WITH 1
			;

			INSERT INTO rh.p_handicap(
				salarie_id,
				taux_incapacite,
				date_effet,
				type_handicap,
				categorie_cotorep,
				form_prof_500h,
				annee_form_prof,
				placement_anterieur,
				taux_ipp,
				date_echeance,
				code_protection,
				nature_contrat,
				rqth,
				beneficiaire_aah,
				carte_invalidite,
				maladie_p_at,
				invalide_pensionne,
				mutile_guerre,
				assimile_mutile_guerre,
				pompier_volontaire,
				unite_age_26_51,
				lourd_handicap,
				emb_1er_handicap,
				emb_chom_long,
				emb_ea_cdtd_esat,
				annee_embauche)
			SELECT
				p_salaries.oid,
				rhlib_F3P01.f3thdp,
				CASE WHEN (	(rhlib_F3P10.F3DEFJ IS NULL OR F3DEFJ NOT BETWEEN 1 AND 31) OR
							(rhlib_F3P10.F3DEFM IS NULL OR F3DEFM NOT BETWEEN 1 AND 12) OR
							(rhlib_F3P10.F3DEFA IS NULL OR F3DEFA NOT BETWEEN 1901 AND 2100)) THEN '2099-12-31'::date
					 ELSE
						(rhlib_F3P10.F3DEFA || '-' || rhlib_F3P10.F3DEFM || '-' ||  rhlib_F3P10.F3DEFJ) :: date
					 END,
				rhlib_F3P10.F3TYHA,
				rhlib_F3P10.F3CATH,
				rhlib_F3P10.F3FORP,
				rhlib_F3P10.F3AFOR,
				rhlib_F3P10.F3PLCA,
				rhlib_F3P10.F3TIPP,
				CASE WHEN (	(rhlib_F3P10.F3DECJ IS NULL OR F3DECJ NOT BETWEEN 1 AND 31) OR
							(rhlib_F3P10.F3DECM IS NULL OR F3DECM NOT BETWEEN 1 AND 12) OR
							(rhlib_F3P10.F3DECA IS NULL OR F3DECA NOT BETWEEN 1901 AND 2100)) THEN '2099-12-31'::date
					 ELSE
						(rhlib_F3P10.F3DECA || '-' || rhlib_F3P10.F3DECM || '-' ||  rhlib_F3P10.F3DECJ) :: date
					 END,
				rhlib_F3P10.F3CPRO,
				rhlib_F3P10.F3NACO,
				rhlib_F3P10.F3RQTH,
				rhlib_F3P10.F3BAAH,
				rhlib_F3P10.F3CAIN,
				rhlib_F3P10.F3ATMP,
				rhlib_F3P10.F3INPE,
				rhlib_F3P10.F3MUGE,
				rhlib_F3P10.F3ASMG,
				rhlib_F3P10.F3SPVO,
				rhlib_F3P10.F3AGEH,
				rhlib_F3P10.F3LOUH,
				rhlib_F3P10.F3HAN1,
				rhlib_F3P10.F3HALG,
				rhlib_F3P10.F3HSEA,
				rhlib_F3P10.F3EHAA

			FROM
				rh.p_salaries
				JOIN prod_shs.rhlib_F3P01 ON p_salaries.matricule = rhlib_F3P01.f3cmat
				JOIN prod_shs.rhlib_F3P10 ON rhlib_F3P10.f3cmat = rhlib_F3P01.f3cmat
			WHERE 1=1
				AND rhlib_F3P01.f3cent IN (select column2::numeric from rhp where column1 = 'entreprise')
				AND rhlib_F3P10.f3cent IN (select column2::numeric from rhp where column1 = 'entreprise')
				AND rhlib_F3P01.f3chdp = '1'
			;

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

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

			INSERT INTO rh.t_divers(
				code,
  				texte,
  				valeur,
  				valeur_date,
  				description)
			VALUES(
				'MOIS_EN_COURS',
				'Mois en cours (non clôturé).',
				(select max(f9da9a::text||lpad(f9da9m, 2, '0')) FROM prod_shs.rhlib_F9p01),
				(select max(f9da9a::text||lpad(f9da9m, 2, '0')||'01'::text)::date FROM prod_shs.rhlib_F9p01),
				'Mois en cours (non clôturé).'
				)
			;
			
			-- Correction nombre entrées en double
			UPDATE rh.p_contrats_mois
			SET nombre_entrees = 0
			FROM 
				(SELECT salarie_id, (MIN(Array[date_debut::text, oid::text]))[2] AS oid_ok FROM rh.p_contrats_mois WHERE nombre_entrees = 1 GROUP BY 1 HAVING count(*) > 1) subview
			WHERE p_contrats_mois.salarie_id = subview.salarie_id AND
				p_contrats_mois.nombre_entrees = 1 AND
				p_contrats_mois.oid <> oid_ok
				;
			
			]]></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>
