<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
    <NODE name="INIT" type="common" />
    <NODE name="PROD" label="Synchronisation données">
		<NODE label="Initialisation tables">
			<condition><![CDATA[
				SELECT count(*) > 0
				FROM information_schema.tables
				WHERE 1=1
                AND table_schema = 'prod_octime'
            ;
            ]]></condition>
			<NODE label="Initialisation table niveaux">
				<condition><![CDATA[
					select count(*) = 0
					from information_schema.tables
					where 1=1
						AND table_schema = 'prod_octime'
						AND table_name = 'niveaux'
					;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					CREATE TABLE prod_octime.niveaux AS
						SELECT
							0::bigint as nar_id,
							''::text as niv_cod1,
							''::text as niv_cod2,
							''::text as niv_cod3,
							''::text as niv_cod4,
							''::text as niv_lib4
						LIMIT 0
					;
					
					-- changement description table pour que le putrecrée la table
					COMMENT ON TABLE prod_octime.niveaux IS 'table created';

					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité HS/HC colonne CAL_VAL62">
				<condition><![CDATA[
					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val62'
					;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column cal_val62 numeric
					;

					update prod_octime.cptres1 set
						cal_val62 = 0
					;
					
					-- changement description table pour que le putrecrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added';

					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité HS/HC colonne CAL_VAL97">
				<condition><![CDATA[

				select count(*) = 0
				from information_schema.columns
				where 1=1
					AND table_schema = 'prod_octime'
					AND table_name = 'cptres1'
					AND lower(column_name) = 'cal_val97'
				;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column cal_val97 numeric
					;

					update prod_octime.cptres1 set
						cal_val97 = 0
					;

					-- changement description table pour que le putrecrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added';
					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité HS/HC colonne CAL_VAL387">
				<condition><![CDATA[

				select count(*) = 0
				from information_schema.columns
				where 1=1
					AND table_schema = 'prod_octime'
					AND table_name = 'cptres1'
					AND lower(column_name) = 'cal_val387'
				;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column cal_val387 numeric
					;

					update prod_octime.cptres1 set
						cal_val387 = 0
					;
					
					-- changement description table pour que le putrecrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added';

					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité HS/HC colonne CAL_VAL388">
				<condition><![CDATA[

				select count(*) = 0
				from information_schema.columns
				where 1=1
					AND table_schema = 'prod_octime'
					AND table_name = 'cptres1'
					AND lower(column_name) = 'cal_val388'
				;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column cal_val388 numeric
					;

					update prod_octime.cptres1 set
						cal_val388 = 0
					;

					-- changement description table pour que le putrecrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added';
					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité colonne nar_id">
				<condition><![CDATA[

				select count(*) = 0
				from information_schema.columns
				where 1=1
					AND table_schema = 'prod_octime'
					AND table_name = 'cptres1'
					AND lower(column_name) = 'nar_id'
				;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column nar_id bigint
					;

					update prod_octime.cptres1 set
						nar_id = 0
					;

					-- changement description table pour que le put recrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added'
					;

					]]></sqlcmd>
				</NODE>
			</NODE>
			<NODE label="Compatibilité colonne niv_cod4">
				<condition><![CDATA[

				select count(*) = 0
				from information_schema.columns
				where 1=1
					AND table_schema = 'prod_octime'
					AND table_name = 'cptres1'
					AND lower(column_name) = 'niv_cod4'
				;

				]]></condition>
				<NODE label="Paramétres et Profils">
					<sqlcmd><![CDATA[
					
					ALTER TABLE prod_octime.cptres1 add column niv_cod4 text
					;

					update prod_octime.cptres1 set
						niv_cod4 = '0'
					;

					-- changement description table pour que le put recrée la table
					COMMENT ON TABLE prod_octime.cptres1 IS 'column added'
					;

					]]></sqlcmd>
				</NODE>
			</NODE>
		</NODE>
		<NODE>
			<condition><![CDATA[
				SELECT count(*) > 0
				FROM information_schema.tables
				WHERE 1=1
                AND table_schema = 'prod_octime2'
                AND table_name LIKE 'cptres1%'
            ;
            ]]></condition>
			<NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL62 (octime2)">
					<condition><![CDATA[
						select count(*) = 0
						from information_schema.columns
						where 1=1
							AND table_schema = 'prod_octime2'
							AND table_name = 'cptres1'
							AND lower(column_name) = 'cal_val62'
						;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime2.cptres1 add column cal_val62 numeric
						;

						update prod_octime2.cptres1 set
							cal_val62 = 0
						;
						
						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime2.cptres1 IS 'column added';

						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL97 (octime2)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime2'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val97'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime2.cptres1 add column cal_val97 numeric
						;

						update prod_octime2.cptres1 set
							cal_val97 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime2.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL387 (octime2)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime2'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val387'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime2.cptres1 add column cal_val387 numeric
						;

						update prod_octime2.cptres1 set
							cal_val387 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime2.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL388 (octime2)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime2'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val388'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime2.cptres1 add column cal_val388 numeric
						;

						update prod_octime2.cptres1 set
							cal_val388 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime2.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
                <NODE label="Compatibilité colonne nar_id">
                    <condition><![CDATA[

                    select count(*) = 0
                    from information_schema.columns
                    where 1=1
                        AND table_schema = 'prod_octime2'
                        AND table_name = 'cptres1'
                        AND lower(column_name) = 'nar_id'
                    ;

                    ]]></condition>
                    <NODE label="Paramétres et Profils">
                        <sqlcmd><![CDATA[
                        
                        ALTER TABLE prod_octime2.cptres1 add column nar_id bigint
                        ;

                        update prod_octime2.cptres1 set
                            nar_id = 0
                        ;

                        -- changement description table pour que le put recrée la table
                        COMMENT ON TABLE prod_octime2.cptres1 IS 'column added'
                        ;

                        ]]></sqlcmd>
                    </NODE>
                </NODE>
                <NODE label="Compatibilité colonne niv_cod4">
                    <condition><![CDATA[

                    select count(*) = 0
                    from information_schema.columns
                    where 1=1
                        AND table_schema = 'prod_octime2'
                        AND table_name = 'cptres1'
                        AND lower(column_name) = 'niv_cod4'
                    ;

                    ]]></condition>
                    <NODE label="Paramétres et Profils">
                        <sqlcmd><![CDATA[
                        
                        ALTER TABLE prod_octime2.cptres1 add column niv_cod4 text
                        ;

                        update prod_octime2.cptres1 set
                            niv_cod4 = '0'
                        ;

                        -- changement description table pour que le put recrée la table
                        COMMENT ON TABLE prod_octime2.cptres1 IS 'column added'
                        ;

                        ]]></sqlcmd>
                    </NODE>
                </NODE>
			</NODE>
		</NODE>
        <NODE>
			<condition><![CDATA[
				SELECT count(*) > 0
				FROM information_schema.tables
				WHERE 1=1
                AND table_schema = 'prod_octime_saas'
                AND table_name LIKE 'cptres1%'
            ;
            ]]></condition>
			<NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL62 (octime_saas)">
					<condition><![CDATA[
						select count(*) = 0
						from information_schema.columns
						where 1=1
							AND table_schema = 'prod_octime_saas'
							AND table_name = 'cptres1'
							AND lower(column_name) = 'cal_val62'
						;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime_saas.cptres1 add column cal_val62 text
						;

						update prod_octime_saas.cptres1 set
							cal_val62 = 0
						;
						
						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added';

						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL97 (octime_saas)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime_saas'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val97'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime_saas.cptres1 add column cal_val97 text
						;

						update prod_octime_saas.cptres1 set
							cal_val97 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL387 (octime_saas)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime_saas'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val387'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime_saas.cptres1 add column cal_val387 text
						;

						update prod_octime_saas.cptres1 set
							cal_val387 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
				<NODE label="Compatibilité HS/HC colonne CAL_VAL388 (octime_saas)">
					<condition><![CDATA[

					select count(*) = 0
					from information_schema.columns
					where 1=1
						AND table_schema = 'prod_octime_saas'
						AND table_name = 'cptres1'
						AND lower(column_name) = 'cal_val388'
					;

					]]></condition>
					<NODE label="Paramétres et Profils">
						<sqlcmd><![CDATA[
						
						ALTER TABLE prod_octime_saas.cptres1 add column cal_val388 text
						;

						update prod_octime_saas.cptres1 set
							cal_val388 = 0
						;

						-- changement description table pour que le putrecrée la table
						COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added';
						]]></sqlcmd>
					</NODE>
				</NODE>
                <NODE label="Compatibilité colonne nar_id">
                    <condition><![CDATA[

                    select count(*) = 0
                    from information_schema.columns
                    where 1=1
                        AND table_schema = 'prod_octime_saas'
                        AND table_name = 'cptres1'
                        AND lower(column_name) = 'nar_id'
                    ;

                    ]]></condition>
                    <NODE label="Paramétres et Profils">
                        <sqlcmd><![CDATA[
                        
                        ALTER TABLE prod_octime_saas.cptres1 add column nar_id bigint
                        ;

                        update prod_octime_saas.cptres1 set
                            nar_id = 0
                        ;

                        -- changement description table pour que le put recrée la table
                        COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added'
                        ;

                        ]]></sqlcmd>
                    </NODE>
                </NODE>
                <NODE label="Compatibilité colonne niv_cod4">
                    <condition><![CDATA[

                    select count(*) = 0
                    from information_schema.columns
                    where 1=1
                        AND table_schema = 'prod_octime_saas'
                        AND table_name = 'cptres1'
                        AND lower(column_name) = 'niv_cod4'
                    ;

                    ]]></condition>
                    <NODE label="Paramétres et Profils">
                        <sqlcmd><![CDATA[
                        
                        ALTER TABLE prod_octime_saas.cptres1 add column niv_cod4 text
                        ;

                        update prod_octime_saas.cptres1 set
                            niv_cod4 = '0'
                        ;

                        -- changement description table pour que le put recrée la table
                        COMMENT ON TABLE prod_octime_saas.cptres1 IS 'column added'
                        ;

                        ]]></sqlcmd>
                    </NODE>
                </NODE>
			</NODE>
		</NODE>
		<NODE>
			<condition><![CDATA[
				SELECT count(*) > 0
				FROM information_schema.tables
				WHERE 1=1
				AND table_schema = 'prod_octime'
			;
			]]></condition>
			<NODE label="Matérialisation des tables OCTIME">
				<sqlcmd><![CDATA[

				-- Technique : reconstitution d'une table parente à partir des tables filles contenant les données pour chaque année.
				DROP TABLE IF EXISTS prod_octime_cptres1
				;
				CREATE TEMP TABLE prod_octime_cptres1 AS
					SELECT
						pers_mat,
						cal_dat,
						nar_id,
						niv_cod1,
						niv_cod2,
						niv_cod3,
						niv_cod4,
						pos_cod,
						cont_cod,
						hor_theo,
						cyc_cod,
						cyc_codmod,
						cyc_ndep,
						cal_hcyc,
						rot_cod,
						rot_ndep,
						hor_cod,
						cal_val1,
						cal_val2,
						cal_val3,
						cal_val4,
						cal_val5,
						cal_val6,
						cal_val7,
						cal_val8,
						cal_val9,
						cal_val10,
						cal_val11,
						cal_val12,
						cal_val13,
						cal_val14,
						cal_val15,
						cal_val16,
						cal_val17,
						cal_val18,
						cal_val19,
						cal_val20,
						cal_val21,
						cal_val22,
						cal_val23,
						cal_val24,
						cal_val25,
						cal_val26,
						cal_val27,
						cal_val28,
						cal_val29,
						cal_val62,
						cal_val97,
						cal_val201,
						cal_val202,
						cal_val203,
						cal_val204,
						cal_val205,
						cal_val206,
						cal_val387,
						cal_val388,
						''::text AS salarie_corr
					FROM prod_octime.cptres1
				;

				DROP TABLE IF EXISTS prod_octime_niveau1
				;
				CREATE TEMP TABLE prod_octime_niveau1 AS
					SELECT
						niv_cod1,
						niv_lib1
					FROM prod_octime.niveau1
				;

				DROP TABLE IF EXISTS prod_octime_niveau2
				;
				CREATE TEMP TABLE prod_octime_niveau2 AS
					SELECT
						niv_cod1,
						niv_cod2,
						niv_lib2
					FROM prod_octime.niveau2
				;

				DROP TABLE IF EXISTS prod_octime_niveau3
				;
				CREATE TEMP TABLE prod_octime_niveau3 AS
					SELECT
						niv_cod1,
						niv_cod2,
						niv_cod3,
						niv_lib3
					FROM prod_octime.niveau3
				;

				DROP TABLE IF EXISTS prod_octime_niveau4
				;
				CREATE TEMP TABLE prod_octime_niveau4 AS
					SELECT
						nar_id,
						niv_cod1,
						niv_cod2,
						niv_cod3,
						niv_cod4,
						niv_lib4
					FROM prod_octime.niveaux
				;

				DROP TABLE IF EXISTS prod_octime_cjourn
				;
				CREATE TEMP TABLE prod_octime_cjourn AS
					SELECT
						hor_cod,
						hor_abr,
						hor_dmis,
						hor_fmis,
						hor_tmis
					FROM prod_octime.cjourn
				;
				
				DROP TABLE IF EXISTS prod_octime_poste
				;
				CREATE TEMP TABLE prod_octime_poste AS
					SELECT
						pos_cod,
						pos_lib
					FROM prod_octime.poste
				;
				
				DROP TABLE IF EXISTS prod_octime_absence
				;
				CREATE TEMP TABLE prod_octime_absence AS
					SELECT
						abs_cod,
						abs_lib
					FROM prod_octime.absence
				;

				DROP TABLE IF EXISTS prod_octime_contrat
				;
				CREATE TEMP TABLE prod_octime_contrat AS
					SELECT
						cont_cod,
						cont_lib,
						cont_cdi
					FROM prod_octime.contrat
				;

				DROP TABLE IF EXISTS prod_octime_contprev
				;
				CREATE TEMP TABLE prod_octime_contprev AS
					SELECT
						pers_mat,
						cont_datd,
						cont_datf,
						cont_cod
					FROM prod_octime.contprev
				;

				DROP TABLE IF EXISTS prod_octime_pers
				;
				CREATE TEMP TABLE prod_octime_pers AS
					SELECT
						pers_cp,
						pers_dnai,
						pers_mat,
						pers_matp,
						pers_idweb,
						pers_nom,
						pers_nomjf,
						pers_nsecu,
						pers_pre,
						pers_sexe,
						pers_dent,
						pers_dsor
					FROM prod_octime.pers
				;

				]]></sqlcmd>
			</NODE>
		</NODE>
        <NODE label="Matérialisation des tables OCTIME2">
            <condition><![CDATA[

            SELECT count(*) > 0
            FROM information_schema.tables
            WHERE 1=1
                AND table_schema = 'prod_octime2'
                AND table_name LIKE 'cptres1%'
            ;

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

            INSERT INTO prod_octime_cptres1
                SELECT
                    pers_mat,
                    cal_dat,
                    nar_id,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    pos_cod,
                    cont_cod,
                    hor_theo,
                    cyc_cod,
                    cyc_codmod,
                    cyc_ndep,
                    cal_hcyc,
                    rot_cod,
                    rot_ndep,
                    hor_cod,
                    cal_val1,
                    cal_val2,
                    cal_val3,
                    cal_val4,
                    cal_val5,
                    cal_val6,
                    cal_val7,
                    cal_val8,
                    cal_val9,
                    cal_val10,
                    cal_val11,
                    cal_val12,
                    cal_val13,
                    cal_val14,
                    cal_val15,
                    cal_val16,
                    cal_val17,
                    cal_val18,
                    cal_val19,
                    cal_val20,
                    cal_val21,
                    cal_val22,
                    cal_val23,
                    cal_val24,
                    cal_val25,
                    cal_val26,
                    cal_val27,
                    cal_val28,
                    cal_val29,
                    cal_val62,
                    cal_val97,
                    cal_val201,
                    cal_val202,
                    cal_val203,
                    cal_val204,
                    cal_val205,
                    cal_val206,
                    cal_val387,
                    cal_val388,
                    ''::text AS salarie_corr
                FROM prod_octime2.cptres1;
            
            INSERT INTO prod_octime_niveau1
                SELECT
                    niv_cod1,
                    niv_lib1
                FROM prod_octime2.niveau1
            ;

            INSERT INTO prod_octime_niveau2
                SELECT
                    niv_cod1,
                    niv_cod2,
                    niv_lib2
                FROM prod_octime2.niveau2
            ;

            INSERT INTO prod_octime_niveau3
                SELECT
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_lib3
                FROM prod_octime2.niveau3
            ;

            INSERT INTO prod_octime_niveau4
                SELECT
                    nar_id,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    niv_lib4
                FROM prod_octime2.niveaux
            ;

            INSERT INTO prod_octime_cjourn
                SELECT
                    hor_cod,
                    hor_abr,
                    hor_dmis,
                    hor_fmis,
                    hor_tmis
                FROM prod_octime2.cjourn
                WHERE hor_cod NOT IN (SELECT hor_cod FROM prod_octime_cjourn)
            ;

            INSERT INTO prod_octime_poste
                SELECT
                    pos_cod,
                    pos_lib
                FROM prod_octime2.poste
                WHERE pos_cod NOT IN (SELECT pos_cod FROM prod_octime_poste)
            ;

            INSERT INTO prod_octime_absence
                SELECT
                    abs_cod,
                    abs_lib
                FROM prod_octime2.absence
                WHERE abs_cod NOT IN (SELECT abs_cod FROM prod_octime_absence)
            ;

            INSERT INTO prod_octime_contrat
                SELECT
                    cont_cod,
                    cont_lib,
                    cont_cdi
                FROM prod_octime2.contrat
                WHERE cont_cod NOT IN (SELECT cont_cod FROM prod_octime_contrat)
            ;

            INSERT INTO prod_octime_contprev
                SELECT
                    pers_mat,
                    cont_datd,
                    cont_datf,
                    cont_cod
                FROM prod_octime2.contprev
            ;

            INSERT INTO prod_octime_pers
                SELECT
                    pers_cp,
                    pers_dnai,
                    pers_mat,
                    pers_matp,
                    pers_idweb,
                    pers_nom,
                    pers_nomjf,
                    pers_nsecu,
                    pers_pre,
                    pers_sexe,
                    pers_dent,
                    pers_dsor
                FROM prod_octime2.pers
                WHERE pers_mat NOT IN (SELECT pers_mat FROM prod_octime_pers)
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Matérialisation des tables OCTIME SaaS">
            <condition><![CDATA[

            SELECT count(*) > 0
            FROM information_schema.tables
            WHERE 1=1
                AND table_schema = 'prod_octime_saas'
                AND table_name LIKE 'cptres1%'
            ;

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

			-- Technique : reconstitution d'une table parente à partir des tables filles contenant les données pour chaque année.
			DROP TABLE IF EXISTS prod_octime_cptres1
			;
			
			CREATE TEMP TABLE prod_octime_cptres1 AS
                SELECT
                    pers_mat,
                    cal_dat::date,
                    nar_id::bigint,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    pos_cod,
                    cont_cod,
                    hor_theo::bigint,
                    cyc_cod::bigint,
                    cyc_codmod::bigint,
                    cyc_ndep::bigint,
                    cal_hcyc,
                    rot_cod::bigint,
                    rot_ndep::bigint,
                    hor_cod::bigint,
                    cal_val1::bigint,
                    cal_val2::bigint,
                    cal_val3::bigint,
                    cal_val4::bigint,
                    cal_val5::bigint,
                    cal_val6::bigint,
                    cal_val7::bigint,
                    cal_val8::bigint,
                    cal_val9::bigint,
                    cal_val10::bigint,
                    cal_val11::bigint,
                    cal_val12::bigint,
                    cal_val13::bigint,
                    cal_val14::bigint,
                    cal_val15::bigint,
                    cal_val16::bigint,
                    cal_val17::bigint,
                    cal_val18::bigint,
                    cal_val19::bigint,
                    cal_val20::bigint,
                    cal_val21::bigint,
                    cal_val22::bigint,
                    cal_val23::bigint,
                    cal_val24,
                    cal_val25,
                    cal_val26,
                    cal_val27,
                    cal_val28,
                    cal_val29,
                    cal_val62::bigint,
                    cal_val97::bigint,
                    cal_val201,
                    cal_val202,
                    cal_val203,
                    cal_val204::bigint,
                    cal_val205::bigint,
                    cal_val206::bigint,
                    cal_val387::bigint,
                    cal_val388::bigint,
                    ''::text AS salarie_corr
                FROM prod_octime_saas.cptres1
            ;
            
			DROP TABLE IF EXISTS prod_octime_niveau1
			;
			
			CREATE TEMP TABLE prod_octime_niveau1 AS
			    SELECT
                    niv_cod1,
                    niv_lib1
                FROM prod_octime_saas.niveau1
            ;
			
			INSERT INTO prod_octime_niveau1
				SELECT 
					niveaux.niv_cod1,
					niveaux.niv_lib1
				FROM prod_octime_saas.niveaux
				LEFT JOIN prod_octime_niveau1 ON prod_octime_niveau1.niv_cod1 = niveaux.niv_cod1
				WHERE prod_octime_niveau1.niv_cod1 IS NULL
			;
			
            DROP TABLE IF EXISTS prod_octime_niveau2
			;
			
			CREATE TEMP TABLE prod_octime_niveau2 AS
                SELECT
                    niv_cod1,
                    niv_cod2,
                    niv_lib2
                FROM prod_octime_saas.niveau2
            ;
			
			INSERT INTO prod_octime_niveau2
				SELECT 
					niveaux.niv_cod1,
					niveaux.niv_cod2,
					niveaux.niv_lib2
				FROM prod_octime_saas.niveaux
				LEFT JOIN prod_octime_niveau2 ON prod_octime_niveau2.niv_cod1 = niveaux.niv_cod1 AND prod_octime_niveau2.niv_cod2 = niveaux.niv_cod2
				WHERE prod_octime_niveau2.niv_cod1 IS NULL
			;

			DROP TABLE IF EXISTS prod_octime_niveau3
			;
			
			CREATE TEMP TABLE prod_octime_niveau3 AS
                SELECT
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_lib3
                FROM prod_octime_saas.niveau3
            ;
			
			INSERT INTO prod_octime_niveau3
				SELECT 
					niveaux.niv_cod1,
					niveaux.niv_cod2,
					niveaux.niv_cod3,
					niveaux.niv_lib3
				FROM prod_octime_saas.niveaux
				LEFT JOIN prod_octime_niveau3 ON prod_octime_niveau3.niv_cod1 = niveaux.niv_cod1 AND prod_octime_niveau3.niv_cod2 = niveaux.niv_cod2 AND prod_octime_niveau3.niv_cod3 = niveaux.niv_cod3
				WHERE prod_octime_niveau3.niv_cod1 IS NULL
			;

			DROP TABLE IF EXISTS prod_octime_niveau4
			;
			
			CREATE TEMP TABLE prod_octime_niveau4 AS
                SELECT
                    nar_id::bigint,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    niv_lib4
                FROM prod_octime_saas.niveaux
            ;

			DROP TABLE IF EXISTS prod_octime_cjourn
			;
			
			CREATE TEMP TABLE prod_octime_cjourn AS
                SELECT
                    hor_cod::bigint,
                    hor_abr,
                    hor_dmis,
                    hor_fmis,
                    hor_tmis
                FROM prod_octime_saas.cjourn
            ;

			DROP TABLE IF EXISTS prod_octime_poste
			;
			
			CREATE TEMP TABLE prod_octime_poste AS
                SELECT
                    pos_cod,
                    pos_lib
                FROM prod_octime_saas.poste
            ;

			DROP TABLE IF EXISTS prod_octime_absence
			;
			
			CREATE TEMP TABLE prod_octime_absence AS
                SELECT
                    abs_cod,
                    abs_lib
                FROM prod_octime_saas.absence
            ;

			DROP TABLE IF EXISTS prod_octime_contrat
			;
			
			CREATE TEMP TABLE prod_octime_contrat AS
                SELECT
                    cont_cod,
                    cont_lib,
                    cont_cdi
                FROM prod_octime_saas.contrat
            ;

			DROP TABLE IF EXISTS prod_octime_contprev
			;
			
			CREATE TEMP TABLE prod_octime_contprev AS
                SELECT
                    pers_mat,
                    cont_datd::date,
                    cont_datf::date,
                    cont_cod
                FROM prod_octime_saas.contprev
            ;

			DROP TABLE IF EXISTS prod_octime_pers
			;
			
			CREATE TEMP TABLE prod_octime_pers AS
                SELECT
                    pers_cp,
                    pers_dnai::date,
                    pers_mat,
                    pers_matp,
                    pers_idweb,
                    pers_nom,
                    pers_nomjf,
                    pers_nsecu,
                    pers_pre,
                    pers_sexe,
                    pers_dent::date,
                    pers_dsor::date
                FROM prod_octime_saas.pers
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE label="Intérim">
            <condition><![CDATA[

            -- Remontée de l'intérim.
            select valeur = 1
            from rh.t_divers
            where code = 'OPT_INTERIM_PLANNING'
            ;

            -- TOUS LES INTERIMAIRES, quelque soit la stratégie, ont un code [original]/matricule préfixé par 'INT'.

            ]]></condition>
            <NODE label="Paramétres et Profils">
                <sqlcmd><![CDATA[

                -- Vérification des séquences.
                -- Utile dans la cas où il y a fusion RH.
                SELECT base.cti_verify_sequences('rh')
                ;

                -- Màj des types de contrat
                INSERT INTO rh.t_types_contrat(code_original, code, texte, texte_court)
                    SELECT cont_cod, cont_cod, cont_lib, substr(cont_lib, 1, 50)
                    FROM prod_octime_contrat
                    WHERE true
                        AND cont_cod NOT IN (SELECT code_original FROM rh.t_types_contrat)
                        AND cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE') -- Par défaut à 'INT'.
                    GROUP BY 1,2,3,4
                ;

                DROP TABLE IF EXISTS w_profils
                ;

                CREATE TEMP TABLE w_profils AS
                    select
                        0::bigint as profil_id,
                        chr(1)||'*' AS cadre_emploi_code_original,
                        chr(1)||'*' AS categorie_conge_code_original,
                        chr(1)||'*' AS categorie_socio_professionnelle_code_original,
                        chr(1)||'*' AS categorie_statutaire_code_original,
                        chr(1)||'*' AS code_emploi_code_original,
                        chr(1)||'*' AS commission_paritaire_code_original,
                        chr(1)||'*' AS compte_salarie_code_original,
                        chr(1)||'*' AS filiere_code_original,
                        chr(1)||'*' AS grille_code_original,
                        chr(1)||'*' AS grille_groupe_code_original,
                        chr(1)||'*' AS groupe_cotisant_code_original,
                        chr(1)||'*' AS lettre_budgetaire_code_original,
                        chr(1)||'*' AS motif_debut_code_original,
                        chr(1)||'*' AS motif_fin_code_original,
                        chr(1)||'*' AS qualification_code_original,
                        chr(1)||'*' AS section_analytique_code_original,
                        chr(1)||'*' AS section_analytique_paie_code_original,
                        chr(1)||'*' AS service_code_original,
                        chr(1)||'*' AS societe_interim_code_original,
                        chr(1)||'*' AS specialite_code_original,
                        chr(1)||'*' AS statut_code_original,
                        (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE')::text AS type_contrat_code_original,
                        chr(1)||'*' AS type_horaire_code_original,
                        chr(1)||'*' AS type_temps_travail_code_original,
                        chr(1)||'*' AS unite_fonctionnelle_code_original
                ;

                -- Alimentation de la table CTI des profils
                INSERT INTO rh.p_profils
                    (
                    cadre_emploi_code_original,
                    categorie_conge_code_original,
                    categorie_socio_professionnelle_code_original,
                    categorie_statutaire_code_original,
                    code_emploi_code_original,
                    commission_paritaire_code_original,
                    compte_salarie_code_original,
                    filiere_code_original,
                    grille_code_original,
                    grille_groupe_code_original,
                    groupe_cotisant_code_original,
                    lettre_budgetaire_code_original,
                    motif_debut_code_original,
                    motif_fin_code_original,
                    qualification_code_original,
                    section_analytique_code_original,
                    section_analytique_paie_code_original,
                    service_code_original,
                    societe_interim_code_original,
                    specialite_code_original,
                    statut_code_original,
                    type_contrat_code_original,
                    type_horaire_code_original,
                    type_temps_travail_code_original,
                    unite_fonctionnelle_code_original
                    )
                    SELECT
                        w_profils.cadre_emploi_code_original,
                        w_profils.categorie_conge_code_original,
                        w_profils.categorie_socio_professionnelle_code_original,
                        w_profils.categorie_statutaire_code_original,
                        w_profils.code_emploi_code_original,
                        w_profils.commission_paritaire_code_original,
                        w_profils.compte_salarie_code_original,
                        w_profils.filiere_code_original,
                        w_profils.grille_code_original,
                        w_profils.grille_groupe_code_original,
                        w_profils.groupe_cotisant_code_original,
                        w_profils.lettre_budgetaire_code_original,
                        w_profils.motif_debut_code_original,
                        w_profils.motif_fin_code_original,
                        w_profils.qualification_code_original,
                        w_profils.section_analytique_code_original,
                        w_profils.section_analytique_paie_code_original,
                        w_profils.service_code_original,
                        w_profils.societe_interim_code_original,
                        w_profils.specialite_code_original,
                        w_profils.statut_code_original,
                        w_profils.type_contrat_code_original,
                        w_profils.type_horaire_code_original,
                        w_profils.type_temps_travail_code_original,
                        w_profils.unite_fonctionnelle_code_original
                    FROM w_profils
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25
                ;

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

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

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

                -- Identifier les intérimaires pour lesquels on va remonter TOUS les contrats.
                -- On considère qu'un intérimaire travaille dans un seul établissement d'un point de vue de ses contrats.
                -- D'où le max(entest.etablissement_id) as etablissement_id ci-dessous.
                DROP TABLE IF EXISTS w_salaries
                ;

                CREATE TEMP TABLE w_salaries AS
                    WITH entest as (
                        SELECT
                            t_entreprises.planning_code||t_etablissements.planning_code as planning_code,
                            min(t_etablissements.entreprise_id) as entreprise_id,
                            min(t_etablissements.oid) as etablissement_id
                        FROM rh.t_entreprises
                            JOIN rh.t_etablissements on t_etablissements.entreprise_id = t_entreprises.oid
                        GROUP BY 1
                    )
                    SELECT
                        0::bigint as salarie_id,
                        rhp('finess') AS finess,
                        pers_nom as nom,
                        pers_pre as prenom,
                        pers_nomjf as nom_naissance,
                        pers_dnai::date as date_naissance,
                        case when pers_sexe = 'H' then 'M' else 'F' end as sexe,
                        pers.pers_mat,
                        'INTERIM-'||CASE octime_interim_str.valeur -- Prefixe rajouté par CTI pour identifier les intérimaires.
                            WHEN '1' THEN right(pers.pers_mat, 5) -- On supprime le préfixe ent/ets.
                            ELSE pers.pers_mat END as code,
                        'INTERIM-'|| pers.pers_mat as code_original, -- Prefixe rajouté par CTI pour identifier les intérimaires.
                        'INTERIM-'|| coalesce(nullif(pers.pers_matp, ''), pers.pers_mat) as nir, -- Prefixe rajouté par CTI pour identifier les intérimaires.
                        'INTERIM-'|| CASE octime_interim_str.valeur -- Prefixe rajouté par CTI pour identifier les intérimaires.
                            WHEN '1' THEN right(pers.pers_mat, 5) -- On supprime le préfixe ent/ets.
                            ELSE pers.pers_mat END as matricule,
                        'INTERIM-'||lower(coalesce(nullif(pers_idweb, ''), nullif(pers.pers_mat, ''), pers.pers_matp)) as matricule_planning,
                        max(entest.entreprise_id) as entreprise_id,
                        0 AS nationalite_id,
                        coalesce(t_codes_postaux.oid, 0) AS code_postal_id,
                        0 AS situation_famille_id,
                        w_profils.profil_id AS profil_id,
                        pers_dent::date AS date_debut,
                        pers_dsor::date AS date_fin,
                        pers_dent::date as date_entree_ets,
                        pers_dsor::date as date_sortie_ets,
                        -- Champs dédiés au public.
                        null::date AS date_entree_fp,
                        null::date AS date_entree_fph,
                        0 AS no_adeli,
                        0 AS code_cotisation_id,
                        0 AS matricule_retraite,
                        max(entest.etablissement_id) as etablissement_id
                    from prod_octime_pers as pers
                        JOIN prod_octime_contprev as contprev on contprev.pers_mat = pers.pers_mat
                        JOIN prod_octime_cptres1 as cptres1 on cptres1.pers_mat = pers.pers_mat
                        JOIN w_profils on true
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_INTERIM_STR') AS octime_interim_str ON 1=1 -- Stratégie d'idenfication des intérimaires
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                        JOIN entest ON entest.planning_code =
                            CASE octime_ets_id.valeur
                                WHEN 0 THEN octime_ets_manuel.valeur
                                WHEN 1 THEN cptres1.niv_cod1
                                WHEN 2 THEN cptres1.niv_cod2
                                WHEN 3 THEN cptres1.niv_cod3
                                WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN substr((SELECT trim(valeur) FROM rh.t_divers WHERE code = 'OCTIME_INTERIM_PREFIXE')||coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), 1, 6) ELSE cptres1.niv_cod4 END -- Cas SHS.
                                WHEN 9 THEN substr((SELECT trim(valeur) FROM rh.t_divers WHERE code = 'OCTIME_INTERIM_PREFIXE')||coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), 1, 6) -- Cas SHS.
                            END
                        LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = pers.pers_cp
                    WHERE 1=1
                        AND contprev.cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE')
                        AND CASE octime_interim_str.valeur
                            WHEN '1' THEN strpos(coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), 'INT') > 0 -- il faut que le matricule de paie Octime contienne INT.
                            ELSE true END
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13, 15,16,17,18,19,20,21,22,23,24,25,26
                ;

                -- Alimenter le champ prod_octime_cptres1.salarie_corr pour les intérim qui n'auraient pas été préfixés par le code ent/ets comme les matricules salariés.
                UPDATE prod_octime_cptres1 SET
                    salarie_corr = (SELECT trim(valeur) FROM rh.t_divers WHERE code = 'OCTIME_INTERIM_PREFIXE')||coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)
                FROM prod_octime_pers AS pers, w_salaries
                WHERE 1=1
                    AND prod_octime_cptres1.pers_mat = pers.pers_mat
                    AND prod_octime_cptres1.pers_mat = w_salaries.pers_mat -- uniquement les intérimaires.
                    AND salarie_corr = '' -- uniquement les données pas déjà mis à jour.
                    AND (SELECT trim(valeur) != '' FROM rh.t_divers WHERE code = 'OCTIME_INTERIM_PREFIXE') -- uniquement si un paramétrage a été fait.
                ;

                ]]></sqlcmd>
            </NODE>
            <NODE name="SALARIE" type="common2" />
            <NODE label="Màj id salariés">
                <sqlcmd><![CDATA[

                update w_salaries SET
                    salarie_id = p_salaries.oid
                from rh.p_salaries
                where p_salaries.code_original = w_salaries.code_original
                ;

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

                -- Suppression des profils contrats mois liés aux intérimaires.
                DELETE FROM rh.p_profil_contrat_mois
                USING rh.p_contrats_mois, rh.p_contrats
                WHERE 1=1
                    AND p_profil_contrat_mois.contrat_mois_id = p_contrats_mois.oid
                    AND p_contrats_mois.contrat_id = p_contrats.oid
                    AND substr(p_contrats.code_original, 1, 8) = 'INTERIM-' -- Prefixe rajouté par CTI pour identifier les contrats intérim.
                ;

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

                -- Pas de repositionnement de la séquence à l'oid max connu (pas utile car peu de contrats générés).
                -- ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
                -- ;

                -- Suppression des contrats mois liés aux intérimaires.
                DELETE FROM rh.p_contrats_mois
                USING rh.p_contrats
                WHERE 1=1
                    AND p_contrats_mois.contrat_id = p_contrats.oid
                    AND substr(p_contrats.code_original, 1, 8) = 'INTERIM-' -- Prefixe rajouté par CTI pour identifier les contrats intérim.
                ;

                -- Suppression des contrats liés aux intérimaires.
                DELETE FROM rh.p_contrats
                WHERE substr(p_contrats.code_original, 1, 8) = 'INTERIM-' -- Prefixe rajouté par CTI pour identifier les contrats intérim.
                ;

                -- Pas de repositionnement de la séquence à l'oid max connu (pas utile car peu de contrats générés).
                -- ALTER SEQUENCE rh.s_contrats RESTART WITH 1
                -- ;

                INSERT INTO rh.p_contrats(
                        salarie_id,
                        date_debut,
                        date_fin,
                        numero_contrat,
                        code_original,
                        etablissement_id,
                        profil_id)
                    SELECT
                        w_salaries.salarie_id,
                        contprev.cont_datd::date AS date_debut,
                        contprev.cont_datf::date AS date_fin,
                        w_salaries.matricule||'-'::text||lpad(rank() over w, 3, '0') AS numero_contrat,
                        w_salaries.matricule||to_char(contprev.cont_datd, 'YYYYMMDD') AS code_original, -- La matricule a un préfixe rajouté par CTI pour identifier les contrats intérim.
                        w_salaries.etablissement_id,
                        w_profils.profil_id AS profil_id
                    FROM prod_octime_contprev as contprev
                        JOIN w_salaries on w_salaries.pers_mat = contprev.pers_mat
                        JOIN w_profils on true
					WHERE contprev.cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE')
                    GROUP BY 1,2,3,  5,6,7, w_salaries.matricule, contprev.cont_datd
                    window w as (PARTITION BY w_salaries.salarie_id ORDER BY cont_datd)
                ;

                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,
                    age_id,
                    age_jours,
                    anciennete_jours,
                    anciennete_mois,
                    anciennete_annee_id,
                    etablissement_id,
                    profil_id,
                    fictif)
                    SELECT
                        w_salaries.salarie_id AS salarie_id,
                        p_contrats.oid AS contrat_id,
                        p_calendrier.mois AS mois,
                        min(p_calendrier.date) as date_debut,
                        max(p_calendrier.date) as date_fin,
                        0 AS nombre_entrees,
                        0 AS nombre_departs,
                        0 AS nombre_debut_contrat,
                        0 AS nombre_fin_contrat,
                        1 as est_hors_periode,
                        0 AS present_debut_mois,
                        0 AS present_fin_mois,
                        1 AS equivalent_temps_plein,
                        1.0 * t_etablissements.base_calcul_etp as nombre_heures,
                        0 AS age_id,
                        0 AS age_jours,
                        0 AS anciennete_jours,
                        0 AS anciennete_mois,
                        0 AS anciennete_annee_id,
                        p_contrats.etablissement_id,
                        w_profils.profil_id as profil_id,
                        1 as fictif
                    FROM prod_octime_contprev as contprev
                        JOIN w_salaries ON w_salaries.pers_mat = contprev.pers_mat
                        JOIN w_profils on true
                        JOIN rh.p_contrats ON p_contrats.code_original = w_salaries.matricule||to_char(contprev.cont_datd, 'YYYYMMDD')
                        JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
                        join base.p_calendrier on p_calendrier.date between contprev.cont_datd and contprev.cont_datf
					WHERE contprev.cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE')
                    GROUP BY 1,2,3, 6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22
                ;

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

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

                INSERT INTO rh.p_profil_contrat_mois (
                    profil_id,
                    contrat_mois_id,
                    salarie_id,
                    ratio,
                    mois)
                    SELECT
                        w_profils.profil_id AS profil_id,
                        p_contrats_mois.oid AS contrat_mois_id,
                        p_contrats_mois.salarie_id,
                        1 AS ratio,
                        p_contrats_mois.mois_activite
                    FROM rh.p_contrats_mois
                        JOIN w_salaries ON w_salaries.salarie_id = p_contrats_mois.salarie_id
                        JOIN w_profils on true
                    GROUP BY 1,2,3,4,5
                ;

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

            -- Todo Fixme Supression de l'historique planning hors période de paie.

            -- Alimentation de niv_cod4 lorsqu'option d'utiliser le niveau 4 est activée.
            UPDATE prod_octime_cptres1 SET
                niv_cod4 = prod_octime_niveau4.niv_cod4
            FROM prod_octime_niveau4, (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau
            WHERE 1=1
                AND prod_octime_cptres1.nar_id = prod_octime_niveau4.nar_id
                AND octime_max_niveau.valeur = '4'
                AND prod_octime_cptres1.niv_cod4 IS DISTINCT FROM prod_octime_niveau4.niv_cod4
            ;
            
            -- Maintenance table temporaire prod_octime_cptres1.
            VACUUM ANALYSE prod_octime_cptres1
            ;

            CREATE INDEX prod_octime_cptres1_ik_pers_mat ON prod_octime_cptres1 USING btree (pers_mat)
            ;

            -- Alimenter le champ prod_octime_cptres1.salarie_corr.
            UPDATE prod_octime_cptres1 SET
                salarie_corr =  CASE WHEN cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE') THEN 'INTERIM-'::text ELSE ''::text END||
                                CASE (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SALARIE')
                                    WHEN 1 THEN ltrim(coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), '0')                   -- Cas 1 - Parc à Caen/Cegid où il faut retirer les 0 parce qu'entre Octime et Cegid les matricules n'ont pas le même nombre de 0 (à gauche).
                                    WHEN 2 THEN coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)                               -- Cas 2 - Hopale/SHS où le matricule Octime contient la concaténation Ent.Ets.Mat..
                                    WHEN 3 THEN prod_octime_cptres1.niv_cod1||'|'||coalesce(nullif(pers.pers_matp, ''), pers.pers_mat) -- Cas 3 - AHO/Sage où les matricule sont les mêmes mais il faut faire le lien avec les établissements (pas les entreprises).
                                    WHEN 4 THEN substring(coalesce(nullif(pers.pers_matp, ''), pers.pers_mat) from '(..........).$') -- Cas 4 PCBS (suppression du dernier caractère pour matcher avec Cegid).
                                    WHEN 5 THEN coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)                               -- Cas 5 - SHS où le matricule Octime contient la concaténation Ent.Ets.Mat..
                                    WHEN 6 THEN coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)                               -- Cas 6 - SHS Grouple HPL où le matricule Octime contient la concaténation : Niveau1(= ets. sur 2 caractères)||Ent.||Ets.||Mat.. ex : "010000002631K".
                                    WHEN 7 THEN substr(coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), 3)                    -- Cas 7 - Cador Expert où les 2 premiers caractères doivent être retirés pour faire 10 de taille et correspondre à ceux de la paie.
                                    WHEN 8 THEN right(coalesce(nullif(pers.pers_matp, ''), pers.pers_mat), 6)                    -- Cas 8 - ELSAN - VHU Sigems où il faut conserver les 6 derniers caractères (un préfixe établissement est éventuellement ajouté mais il ne faut pas en tenir compte. Le niveau 1 est là pour identifier l'ets.)
                                    WHEN 9 THEN lower(coalesce(nullif(pers_idweb, ''), nullif(pers.pers_mat, ''), pers.pers_matp)) -- Cas 9 - Le matricule planning est saisie dans la paie.
                                    WHEN 10 THEN coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)                                -- Cas 10 - Fusion QuadraRH -> ADP.
                                    WHEN 11 THEN -- Cas 11 - NIR. avec gestion de l'interim sans NIR
                                        CASE WHEN cont_cod = (select valeur from rh.t_divers where code = 'INTERIM_CNT_CODE')
                                            THEN coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)
                                            ELSE pers.pers_nsecu
                                        END
                                    ELSE coalesce(nullif(pers.pers_matp, ''), pers.pers_mat)   -- Par défaut.
                                END
            FROM prod_octime_pers AS pers
            WHERE 1=1
                AND prod_octime_cptres1.pers_mat = pers.pers_mat
                AND salarie_corr = '' -- uniquement les données pas déjà mis à jour (cf. interim plus haut).
            ;

            -- Recensement des salariés et établissements.
            DROP TABLE IF EXISTS w_sal_pla
            ;
            CREATE TEMP TABLE w_sal_pla AS
                SELECT 
                    p_salaries.oid AS salarie_id,
                    p_salaries.nir,
                    p_salaries.matricule,
                    p_salaries.date_debut as sal_date_debut, -- utilisé lorsque 
                    p_salaries.date_fin as sal_date_fin,
                    p_salaries.matricule_planning as matricule_paie_planning, -- Matricule planning saisi dans la paie.
                    t_entreprises.code_original AS entreprise_code_original,
                    t_etablissements.code_original AS etablissement_code_original,
                    t_entreprises.code AS entreprise_code,
                    t_entreprises.planning_code AS entreprise_planning_code,
                    t_etablissements.code AS etablissement_code,
                    t_etablissements.planning_code as etablissement_planning_code, -- Pour cas 3 Sage
                    lpad(t_entreprises.code, 3, '0') || lpad(t_etablissements.code, 3, '0') || p_salaries.matricule AS matricule_planning, -- Pour cas 2 SHS
                    lpad(t_entreprises.planning_code, 3, '0') || lpad(t_etablissements.planning_code, 3, '0') || substr(p_salaries.matricule, 1, 5) AS matricule_planning_conso, -- Pour cas 5 SHS consolidé
                    ltrim(p_salaries.matricule, '0') AS matricule_trim, -- Pour cas 1 Cegid
                    rank() over (partition by p_salaries.nir order by p_salaries.date_fin desc) as rang, -- Lorsque stratégie basée sur le NIR, permet d'identifier les doublons.
                    ''::text AS salarie_corr
                FROM rh.p_salaries
                    -- Il faut absoluement faire le produit cartésien matricule/établissement même si un salarié n'a jamais travaillé dans un des établissement.
                    -- En effet, cela pourrait être le cas dans Octime et ce traitement pourrait ne pas remonter les données associées.
					JOIN rh.t_entreprises ON t_entreprises.oid = p_salaries.entreprise_id
					JOIN rh.t_etablissements ON t_etablissements.entreprise_id = p_salaries.entreprise_id
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                WHERE 1=1
                    AND salarie_fusionne_id = 0
                    -- Uniquement les établissements avec planning_code renseigné dans le cas où l'établissement est en mode manuel.
                    AND CASE WHEN octime_ets_id.valeur = 0 THEN nullif(trim(t_etablissements.planning_code), '') IS NOT NULL ELSE TRUE END
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15
                ORDER BY 1,2,3
            ;

            -- Stratégie basée sur le NIR : suppression des salariés en doublons.
            DELETE FROM w_sal_pla
            WHERE 1=1
                and (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SALARIE') = 11
                and rang > 1
            ;
            
            -- Gestion des salariés fusionnés.
            INSERT INTO w_sal_pla
                SELECT 
                    w_sal_pla.salarie_id,
                    p_salaries.nir,
                    p_salaries.matricule,
                    w_sal_pla.sal_date_debut,
                    w_sal_pla.sal_date_fin,
                    p_salaries.matricule_planning as matricule_paie_planning,
                    w_sal_pla.entreprise_code_original,
                    w_sal_pla.etablissement_code_original,
                    w_sal_pla.entreprise_code,
                    w_sal_pla.entreprise_planning_code,
                    w_sal_pla.etablissement_code,
                    w_sal_pla.etablissement_planning_code,
                    lpad(w_sal_pla.entreprise_code, 3, '0') || lpad(w_sal_pla.etablissement_code, 3, '0') || p_salaries.matricule AS matricule_planning,
                    lpad(w_sal_pla.entreprise_planning_code, 3, '0') || lpad(w_sal_pla.etablissement_planning_code, 3, '0') || substr(p_salaries.matricule, 1, 5) AS matricule_planning_conso,
                    ltrim(p_salaries.matricule, '0') AS matricule_trim,
                    1 as rang,
                    ''::text AS salarie_corr
                FROM w_sal_pla
                    JOIN rh.p_salaries ON salarie_fusionne_id = w_sal_pla.salarie_id
                WHERE salarie_fusionne_id != 0
            ;

            -- #CORRECTION SHS lorsque le code établissement contient un tiret, utiliser son code original uniquement pour matricule_planning.
            UPDATE w_sal_pla SET
                matricule_planning = etablissement_code_original || matricule
            WHERE etablissement_code LIKE '%-%'
            ;

            -- Alimenter le champ w_sal_pla.salarie_corr.
            UPDATE w_sal_pla SET
                salarie_corr =
                    CASE (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SALARIE')
                        WHEN 1 THEN matricule_trim
                        WHEN 2 THEN matricule_planning
                        WHEN 5 THEN matricule_planning_conso
                        WHEN 3 THEN etablissement_planning_code||'|'||matricule
                        -- Le cas 6 nécessite le paramétrage du planning_code pour l'établissement et éventuellement l'entreprise.
                        -- Pour le cas "010000002631K", on peut paramétrer ent. à "01000" et ets. à "000".
                        WHEN 6 THEN entreprise_planning_code||etablissement_planning_code||matricule
                        -- Le cas 9 utilise la matricule planning saisi dans la paie.
                        WHEN 9 THEN matricule_paie_planning
                        WHEN 10 THEN case when substr(matricule, 1 , 4) = '0000' then (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_OLDMAT_PREFIXE')||matricule_trim else matricule end -- Cas 10 - Fusion QuadraRH -> ADP.
                        WHEN 11 THEN nir -- Cas 11 : NIR
                        -- Les cas 4, 7 et 8 ne nécessitent pas de transformation du matricule issu de la paie.
                        ELSE matricule
                    END
            ;

            -- Création d'index.
            CREATE INDEX w_sal_pla_i_matricule          ON w_sal_pla USING btree (matricule)
            ;
            CREATE INDEX w_sal_pla_i_matricule_planning ON w_sal_pla USING btree (matricule_planning)
            ;
            CREATE INDEX w_sal_pla_i_matricule_trim     ON w_sal_pla USING btree (matricule_trim)
            ;

            DROP SEQUENCE IF EXISTS w_cptres1_seq
            ;
            
            CREATE TEMP SEQUENCE w_cptres1_seq
            ;

            DROP TABLE IF EXISTS w_cptres1
            ;

            CREATE TEMP TABLE w_cptres1 AS
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    ''::text AS abs_cod,
                    hor_cod, -- code horaire.
                    cal_val2/60.00 AS temps_du_initial,
                    cal_val3/60.00 AS temps_du,
                    CASE tps_valide.valeur WHEN '6' THEN cal_val6 ELSE cal_val5 END/60.00 AS temps_valide,
                    0::numeric AS temps_absence,
                    0 AS temps_hs,
                    0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_TPS_VALIDE') AS tps_valide ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE 1!=1
                    OR cal_val2 != 0
                    OR cal_val3 != 0
                    OR CASE tps_valide.valeur WHEN '6' THEN cal_val6 ELSE cal_val5 END != 0
            ;

            INSERT INTO w_cptres1
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    cal_val24 AS abs_cod,
                    hor_cod, -- code horaire.
                    0 AS temps_du,
                    0 AS temps_du_initial,
                    0 AS temps_valide,
                    cal_val21/60.00 AS temps_absence,
                    0 AS temps_hs,
                    0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE cal_val21 != 0
            ;

            INSERT INTO w_cptres1
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    cal_val25 AS abs_cod,
                    hor_cod, -- code horaire.
                    0 AS temps_du,
                    0 AS temps_du_initial,
                    0 AS temps_valide,
                    cal_val22/60.00 AS temps_absence,
                    0 AS temps_hs,
                    0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE cal_val22 != 0
            ;

            INSERT INTO w_cptres1
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    cal_val26 AS abs_cod,
                    hor_cod, -- code horaire.
                    0 AS temps_du,
                    0 AS temps_du_initial,
                    0 AS temps_valide,
                    cal_val23/60.00 AS temps_absence,
                    0 AS temps_hs,
                    0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE cal_val23 != 0
            ;

            INSERT INTO w_cptres1
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    cal_val26 AS abs_cod,
                    hor_cod, -- code horaire.
                    0 AS temps_du,
                    0 AS temps_du_initial,
                    0 AS temps_valide,
                    0 AS temps_absence,
                    cal_val387/60.0 AS temps_hs,
                    0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE cal_val387 != 0
            ;

            INSERT INTO w_cptres1
                SELECT
                    nextval('w_cptres1_seq') as cptres1_id,
                    prod_octime_cptres1.salarie_corr,
                    w_sal_pla.salarie_id,
                    null::bigint AS contrat_id,
                    null::bigint AS contrat_mois_id,
                    date(cal_dat) AS date,
                    pos_cod,
                    niv_cod1,
                    niv_cod2,
                    niv_cod3,
                    niv_cod4,
                    CASE octime_max_niveau.valeur
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS niveau_code_original,
                    CASE octime_service_id.valeur
                        WHEN 1 THEN niv_cod1
                        WHEN 2 THEN niv_cod1 || '|' || niv_cod2
                        WHEN 3 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3
                        WHEN 4 THEN niv_cod1 || '|' || niv_cod2 || '|' || niv_cod3 || '|' || niv_cod4
                    END AS service_code_original,
                    CASE octime_ets_id.valeur
                        WHEN 0 THEN octime_ets_manuel.valeur
                        WHEN 1 THEN niv_cod1 -- cas AHO
                        WHEN 2 THEN niv_cod2
                        WHEN 3 THEN niv_cod3
                        WHEN 4 THEN CASE WHEN octime_max_niveau.valeur = '3' THEN left(prod_octime_cptres1.pers_mat, -5) ELSE niv_cod4 END -- cas Fondation Hopale avec OCTIME_MAX_NIVEAU positionné par défaut sur 3.
                        WHEN 9 THEN left(prod_octime_cptres1.pers_mat, -5) -- cas Fondation Hopale
                    END AS entets_code,
                    cal_val26 AS abs_cod,
                    hor_cod, -- code horaire.
                    0 AS temps_du,
                    0 AS temps_du_initial,
                    0 AS temps_valide,
                    0 AS temps_absence,
                    0 AS temps_hs,
                    cal_val388/60.0 AS temps_hc
                FROM prod_octime_cptres1
                    JOIN w_sal_pla ON w_sal_pla.salarie_corr = prod_octime_cptres1.salarie_corr
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_ID') AS octime_ets_id ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_ETS_MANUEL') AS octime_ets_manuel ON 1=1
                    JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                WHERE cal_val388 != 0
            ;

            -- Permet de s'assurer que le Niveau Planning non renseigné sera bien celui avec l'OID 0.
            UPDATE w_cptres1 SET
                niveau_code_original = ''
            WHERE niveau_code_original = '||'
            ;

            VACUUM ANALYSE w_cptres1
            ;

            -- Association aux contrats et contrat_mois.
            -- En général, les heures planning sont effectuées AVANT un contrat/paie à cause du décallage avec la paie :
            -- => les heures effectuées en fin de mois sont à associer avec le mois suivant.
            with w_asso as (
                select
                    cptres1_id,
                    (max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
                    (max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
                from w_cptres1
                    join rh.p_contrats_mois on 1=1
                        and p_contrats_mois.salarie_id = w_cptres1.salarie_id
                        and w_cptres1.date between p_contrats_mois.date_debut and p_contrats_mois.date_fin -- Sélection des contrats pendant heures planning.
                where 1!=1
                    OR w_cptres1.contrat_id is null
                    OR w_cptres1.contrat_mois_id is null
                group by 1)
            UPDATE w_cptres1 SET
                contrat_id = w_asso.contrat_id,
                contrat_mois_id = w_asso.contrat_mois_id
            FROM w_asso
            WHERE w_cptres1.cptres1_id = w_asso.cptres1_id
            ;

            with w_asso as (
                select
                    cptres1_id,
                    (min(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
                    (min(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
                from w_cptres1
                    join rh.p_contrats_mois on 1=1
                        and p_contrats_mois.salarie_id = w_cptres1.salarie_id
                        and p_contrats_mois.date_debut > w_cptres1.date -- Sélection des contrats APRES heures planning.
                where 1!=1
                    OR w_cptres1.contrat_id is null
                    OR w_cptres1.contrat_mois_id is null
                group by 1)
            UPDATE w_cptres1 SET
                contrat_id = w_asso.contrat_id,
                contrat_mois_id = w_asso.contrat_mois_id
            FROM w_asso
            WHERE w_cptres1.cptres1_id = w_asso.cptres1_id
            ;

            with w_asso as (
                select
                    cptres1_id,
                    (max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.contrat_id]))[2] as contrat_id,
                    (max(array[extract(epoch from p_contrats_mois.date_debut), p_contrats_mois.oid]))[2] as contrat_mois_id
                from w_cptres1
                    join rh.p_contrats_mois on 1=1
                        and p_contrats_mois.salarie_id = w_cptres1.salarie_id
                        and p_contrats_mois.date_debut < w_cptres1.date -- Sélection des contrats AVANT heures planning.
                where 1!=1
                    OR w_cptres1.contrat_id is null
                    OR w_cptres1.contrat_mois_id is null
                group by 1)
            UPDATE w_cptres1 SET
                contrat_id = w_asso.contrat_id,
                contrat_mois_id = w_asso.contrat_mois_id
            FROM w_asso
            WHERE w_cptres1.cptres1_id = w_asso.cptres1_id
            ;

            -- Création d'index.
            CREATE INDEX w_cptres1_i_contrat_id      ON w_cptres1 USING btree (contrat_id)
            ;
            CREATE INDEX w_cptres1_i_contrat_mois_id ON w_cptres1 USING btree (contrat_mois_id)
            ;
            CREATE INDEX w_cptres1_i_date            ON w_cptres1 USING btree (date)
            ;
            CREATE INDEX w_cptres1_i_salarie_id      ON w_cptres1 USING btree (salarie_id)
            ;

            -- Alimentation des tables de paramètres.
            -- Màj des Services du Planning.
            INSERT INTO rh.t_planning_service(code_original, code, texte, texte_court, service_id)
                with w_cptres1_tmp as (
                    select
                        service_code_original,
                        niv_cod1,
                        niv_cod2,
                        niv_cod3,
                        niv_cod4,
                        octime_service_id.valeur
                    from w_cptres1
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_SERVICE_ID') AS octime_service_id ON 1=1
                    group by 1,2,3,4,5,6)
                SELECT
                    w_cptres1.service_code_original,
                    w_cptres1.service_code_original,
                    coalesce(niv1.niv_lib1, w_cptres1.niv_cod1)||case when valeur >= 2 THEN ' - '||coalesce(niv2.niv_lib2, w_cptres1.niv_cod2) ELSE '' END||CASE WHEN valeur >= 3 THEN ' - '||coalesce(niv3.niv_lib3, w_cptres1.niv_cod3) ELSE '' END||CASE WHEN valeur >= 4 THEN ' - '||coalesce(niv4.niv_lib4, w_cptres1.niv_cod4) ELSE '' END,
                    substr(coalesce(niv1.niv_lib1, w_cptres1.niv_cod1)||case when valeur >= 2 THEN ' - '||coalesce(niv2.niv_lib2, w_cptres1.niv_cod2) ELSE '' END||CASE WHEN valeur >= 3 THEN ' - '||coalesce(niv3.niv_lib3, w_cptres1.niv_cod3) ELSE '' END||CASE WHEN valeur >= 4 THEN ' - '||coalesce(niv4.niv_lib4, w_cptres1.niv_cod4) ELSE '' END, 1, 50),
                    0 as service_id
                FROM w_cptres1_tmp as w_cptres1
                    LEFT JOIN prod_octime_niveau1 as niv1 ON niv1.niv_cod1 = w_cptres1.niv_cod1
                    LEFT JOIN prod_octime_niveau2 as niv2 ON 1=1
                        AND niv2.niv_cod1 = w_cptres1.niv_cod1
                        AND niv2.niv_cod2 = w_cptres1.niv_cod2
                    LEFT JOIN prod_octime_niveau3 as niv3 ON 1=1
                        AND niv3.niv_cod1 = w_cptres1.niv_cod1
                        AND niv3.niv_cod2 = w_cptres1.niv_cod2
                        AND niv3.niv_cod3 = w_cptres1.niv_cod3
                    LEFT JOIN prod_octime_niveau4 as niv4 ON 1=1
                        AND niv4.niv_cod1 = w_cptres1.niv_cod1
                        AND niv4.niv_cod2 = w_cptres1.niv_cod2
                        AND niv4.niv_cod3 = w_cptres1.niv_cod3
                        AND niv4.niv_cod4 = w_cptres1.niv_cod4
                WHERE w_cptres1.service_code_original NOT IN (SELECT code_original FROM rh.t_planning_service WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4
            ;

            -- Màj des Niveaux du Planning.
            DROP TABLE IF EXISTS w_nivpla
            ;

            CREATE TEMP TABLE w_nivpla AS
                with w_cptres1_tmp as (
                    select
                        niveau_code_original,
                        niv_cod1,
                        niv_cod2,
                        niv_cod3,
                        niv_cod4,
                        octime_max_niveau.valeur as octime_max_niveau
                    from w_cptres1
                        JOIN (SELECT valeur FROM rh.t_divers WHERE code = 'OCTIME_MAX_NIVEAU') AS octime_max_niveau ON 1=1
                    group by 1,2,3,4,5,6)
                SELECT
                    w_cptres1.niveau_code_original,
                    coalesce(niv1.niv_lib1, w_cptres1.niv_cod1)||' -|- '||coalesce(niv2.niv_lib2, w_cptres1.niv_cod2)||' -|- '||coalesce(niv3.niv_lib3, w_cptres1.niv_cod3)||case when octime_max_niveau = 4 then ' -|- '||coalesce(niv4.niv_lib4, w_cptres1.niv_cod4) else '' end as niv_txt,
                    substr(coalesce(niv1.niv_lib1, w_cptres1.niv_cod1)||' -|- '||coalesce(niv2.niv_lib2, w_cptres1.niv_cod2)||' -|- '||coalesce(niv3.niv_lib3, w_cptres1.niv_cod3)||case when octime_max_niveau = 4 then ' -|- '||coalesce(niv4.niv_lib4, w_cptres1.niv_cod4) else '' end, 1, 50) as niv_txt_crt
                FROM w_cptres1_tmp as w_cptres1
                    LEFT JOIN prod_octime_niveau1 as niv1 ON niv1.niv_cod1 = w_cptres1.niv_cod1
                    LEFT JOIN prod_octime_niveau2 as niv2 ON 1=1
                        AND niv2.niv_cod1 = w_cptres1.niv_cod1
                        AND niv2.niv_cod2 = w_cptres1.niv_cod2
                    LEFT JOIN prod_octime_niveau3 as niv3 ON 1=1
                        AND niv3.niv_cod1 = w_cptres1.niv_cod1
                        AND niv3.niv_cod2 = w_cptres1.niv_cod2
                        AND niv3.niv_cod3 = w_cptres1.niv_cod3
                    LEFT JOIN prod_octime_niveau4 as niv4 ON 1=1
                        AND niv4.niv_cod1 = w_cptres1.niv_cod1
                        AND niv4.niv_cod2 = w_cptres1.niv_cod2
                        AND niv4.niv_cod3 = w_cptres1.niv_cod3
                        AND niv4.niv_cod4 = w_cptres1.niv_cod4
                WHERE 1=1
                    AND niveau_code_original != ''
                GROUP BY 1,2,3
            ;

            -- Màj des libellés uniquement.
            UPDATE rh.t_planning_niveau SET
                texte = niv_txt,
                texte_court = niv_txt_crt
            FROM w_nivpla
            WHERE 1=1
                AND t_planning_niveau.code_original = w_nivpla.niveau_code_original
                AND (1!=1
                    OR t_planning_niveau.texte IS DISTINCT FROM w_nivpla.niv_txt
                    OR t_planning_niveau.texte_court IS DISTINCT FROM w_nivpla.niv_txt_crt)
            ;

            -- Insertion des nouveaux niveaux de planning.
            INSERT INTO rh.t_planning_niveau(code_original, code, texte, texte_court)
                SELECT
                    w_nivpla.niveau_code_original,
                    w_nivpla.niveau_code_original,
                    w_nivpla.niv_txt,
                    w_nivpla.niv_txt_crt
                FROM w_nivpla
                    JOIN w_cptres1 ON w_cptres1.niveau_code_original = w_nivpla.niveau_code_original
                WHERE w_nivpla.niveau_code_original NOT IN (SELECT code_original FROM rh.t_planning_niveau WHERE code_original IS NOT NULL GROUP BY 1)
                GROUP BY 1,2,3,4
            ;

            -- Màj des Qualifications du Planning.
            INSERT INTO rh.t_planning_qualification(code_original, code, texte, texte_court)
                SELECT
                    pos_cod,
                    pos_cod,
                    pos_lib,
                    pos_lib
                FROM prod_octime_poste AS poste
                WHERE 1=1
                    AND pos_cod IN (SELECT pos_cod FROM w_cptres1)
                    AND pos_cod NOT IN (SELECT code_original FROM rh.t_planning_qualification WHERE code_original IS NOT NULL)
            ;

            -- Màj des Types d'absences du Planning.
            INSERT INTO rh.t_planning_type_absence(code_original, code, texte, texte_court)
                SELECT
                    abs_cod,
                    abs_cod,
                    abs_lib,
                    abs_lib
                FROM prod_octime_absence AS absence
                WHERE 1=1
                    AND abs_cod IN (SELECT abs_cod FROM w_cptres1)
                    AND abs_cod NOT IN (SELECT code_original FROM rh.t_planning_type_absence WHERE code_original IS NOT NULL)
            ;

            -- Màj des Codes Horaires du Planning.
            INSERT INTO rh.t_planning_code_horaire(code_original, code, texte, texte_court)
                SELECT
                    hor_cod,
                    hor_abr,
                    substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')',
                    substr(substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')', 1, 50)
                FROM prod_octime_cjourn AS cjourn
                WHERE 1=1
                    AND hor_cod IN (SELECT hor_cod FROM w_cptres1)
                    AND hor_cod NOT IN (SELECT code_original FROM rh.t_planning_code_horaire WHERE code_original IS NOT NULL)
            ;

            -- Forçage des libellés et codes horaires lorsqu'ils sautent
            UPDATE rh.t_planning_code_horaire
            SET code = hor_abr,
                texte = substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')',
                texte_court = substr(substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')', 1, 50)
            FROM prod_octime_cjourn AS cjourn
            WHERE code_original = hor_cod AND
               (code <> hor_abr OR
               texte <> substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')' OR
               texte_court <> substr(substr(hor_dmis, 1, 2)||'h'||substr(hor_dmis, 3, 2)||'-'||substr(hor_fmis, 1, 2)||'h'||substr(hor_fmis, 3, 2)||' ('||substr(hor_tmis, 1, 2)||':'||substr(hor_tmis, 3, 2)||')', 1, 50))
            ;

            -- Création d'une table Entreprise/Etablissement.
            DROP TABLE IF EXISTS w_entets
            ;

            CREATE TEMP TABLE w_entets AS
                select
                    max(ent.oid) as entreprise_id,
                    max(ets.oid) as etablissement_id,
                    ent.planning_code||ets.planning_code as entets_code
                from rh.t_entreprises as ent
                    join rh.t_etablissements as ets on ets.entreprise_id = ent.oid
                Where 1=1
                    and ent.oid != 0
                    and ets.oid != 0
                GROUP BY ent.planning_code||ets.planning_code
            ;

            -- Ajout de l'établissement en cours si la valeur de OCTIME_REPRISE_HISTO est à 1 (reprise de l'histo paramétré) car le max renvoi l'établissement historique
			WITH w_ets_encours_reprise_histo AS 
			(SELECT ent.oid as entreprise_id,
				    ets.oid as etablissement_id,
				    ent.planning_code||ets.planning_code as entets_code
			 FROM rh.t_entreprises as ent 
			 JOIN rh.t_etablissements as ets on ets.entreprise_id = ent.oid
			 JOIN rh.t_divers ON t_divers.code IN ('OCTIME_REPRISE_HISTO')
			 LEFT JOIN w_entets ON w_entets.entreprise_id = ent.oid AND w_entets.etablissement_id = ets.oid
			 WHERE 1=1
				   AND ent.oid != 0
				   AND ets.oid != 0
				   AND ent.planning_code||ets.planning_code != '' 
				   AND t_divers.valeur = 1
				   AND w_entets.etablissement_id IS NULL)
			INSERT INTO w_entets SELECT * FROM w_ets_encours_reprise_histo;

            -- Alimentation de la table de mouvement.
            TRUNCATE rh.p_planning_mouvement
            ;
            INSERT INTO rh.p_planning_mouvement(
                salarie_id,
                contrat_id,
                contrat_mois_id,
                date,
                semaine,
                mois,
                etablissement_id, -- @todo à renseigner en fonction du paramétrage dans t_divers.
                service_id,
                qualification_id,
                type_absence_id,
                niveau_id,
                code_horaire_id,
                temps_du,
                temps_du_initial,
                temps_valide,
                temps_absence,
				temps_du_ajuste,
				temps_valide_ajuste,
				temps_absence_ajuste)
                SELECT
                    w_cptres1.salarie_id,
                    w_cptres1.contrat_id,
                    w_cptres1.contrat_mois_id,
                    w_cptres1.date,
                    to_char(w_cptres1.date, 'IYYYIW'::text)::numeric AS semaine,
                    to_char(w_cptres1.date, 'YYYYMM'::text)::numeric AS mois,
                    coalesce(w_entets.etablissement_id, 0) as etablissement_id,
                    coalesce(t_planning_service.oid, 0) AS service_id,
                    coalesce(t_planning_qualification.oid, 0) AS qualification_id,
                    coalesce(t_planning_type_absence.oid, 0) AS type_absence_id,
                    coalesce(t_planning_niveau.oid, 0) as niveau_id,
                    coalesce(t_planning_code_horaire.oid, 0) as code_horaire_id,
                    temps_du,
                    temps_du_initial,
                    temps_valide,
                    temps_absence,
                    temps_du,
                    temps_valide,
                    temps_absence
                FROM w_cptres1
                    JOIN rh.p_salaries ON p_salaries.oid = w_cptres1.salarie_id
                    JOIN w_entets                         ON true
                        AND w_entets.entreprise_id = p_salaries.entreprise_id
                        AND w_entets.entets_code   = w_cptres1.entets_code -- Limiter les données au seul établissement paramétré.
                    LEFT JOIN rh.t_planning_niveau        ON t_planning_niveau.code_original        = w_cptres1.niveau_code_original
                    LEFT JOIN rh.t_planning_service       ON t_planning_service.code_original       = w_cptres1.service_code_original
                    LEFT JOIN rh.t_planning_qualification ON t_planning_qualification.code_original = w_cptres1.pos_cod
                    LEFT JOIN rh.t_planning_type_absence  ON t_planning_type_absence.code_original  = w_cptres1.abs_cod
                    LEFT JOIN rh.t_planning_code_horaire  ON t_planning_code_horaire.code_original  = w_cptres1.hor_cod
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
            ;

            VACUUM ANALYSE rh.p_planning_mouvement
            ;
            
            -- Ajustement des temps
            
            -- Temps validé sans temps du, alimenter temps du
            UPDATE rh.p_planning_mouvement
            SET temps_du_ajuste = p_planning_mouvement.temps_valide
            FROM
            (
            SELECT salarie_id, date
            FROM rh.p_planning_mouvement
            JOIN RH.t_divers ON t_divers.code = 'OCTIME_TPS_VALIDE_A' AND t_divers.valeur = '1'
            GROUP BY 1,2
            HAVING SUM(temps_du) = 0 AND SUM(temps_valide) > 0
            ) subview
            WHERE p_planning_mouvement.salarie_id = subview.salarie_id AND
                p_planning_mouvement.date = subview.date 
            ;


            -- Temps du - temps absence différent de temps validé -> temps valide = Temps du - temps absence
            UPDATE rh.p_planning_mouvement
            SET temps_valide_ajuste = p_planning_mouvement.temps_valide + ecart_temps_valide
            FROM
            (
            SELECT salarie_id, date, SUM(temps_du_ajuste) AS temps_du_ajuste, SUM(temps_valide) AS temps_valide, SUM(temps_absence) AS temps_absence, 
                MIN(CASE WHEN temps_du_ajuste > 0 THEN p_planning_mouvement.CTID ELSE NULL END) AS upd_ctid, SUM(temps_du_ajuste) - SUM(temps_absence) - SUM(temps_valide) AS ecart_temps_valide
            FROM rh.p_planning_mouvement
            JOIN RH.t_divers ON t_divers.code = 'OCTIME_TPS_VALIDE_A' AND t_divers.valeur = '1'
            GROUP BY 1,2
            HAVING SUM(temps_du_ajuste) - SUM(temps_absence) <>  SUM(temps_valide)
            ) subview
            WHERE p_planning_mouvement.salarie_id = subview.salarie_id AND
                p_planning_mouvement.date = subview.date AND
                p_planning_mouvement.ctid = subview.upd_ctid
            ;
            
            ]]></sqlcmd>
        </NODE>
    </NODE>
    <NODE name="POST" type="common" />
    <NODE name="VACUUM" type="common" />
    <NODE name="VENTILATION" label="Ventilation analytique">
        <condition><![CDATA[

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

        ]]></condition>
        <NODE name="VENTILATION" label="Calcul des ventilations">
        <sqlcmd><![CDATA[

            -- Insertion du Plan Analytique.
            TRUNCATE rh.t_plan_analytique
            ;
            INSERT INTO rh.t_plan_analytique(oid, code, texte)
            VALUES ((SELECT valeur::bigint FROM rh.t_divers WHERE code = 'OCTIME_VENTILATION'), 'OCTIME', 'Ventilation analytique')
            ;

            -- Màj des sections analytiques.
            DELETE FROM rh.t_section_analytique
            WHERE oid != 0 -- Ne pas supprimer la section analytique N/R
            ;
            INSERT INTO rh.t_section_analytique(oid, code_original, code, texte, texte_court)
                select 
                    t_planning_niveau.oid * 1000000 + t_planning_type_absence.oid as oid,
                    t_planning_niveau.code_original||'|'::text||t_planning_type_absence.code_original as code_original,
                    t_planning_niveau.code||'|'::text||(case when t_planning_type_absence.oid = 0 then ''::text else t_planning_type_absence.code end) as code,
                    t_planning_niveau.texte||(case when t_planning_type_absence.oid = 0 then ''::text else ' -|- '::text||t_planning_type_absence.texte end) as texte,
                    t_planning_niveau.texte_court||(case when t_planning_type_absence.oid = 0 then ''::text else ' -|- '::text||t_planning_type_absence.texte_court end) as texte_court
                from rh.t_planning_niveau, rh.t_planning_type_absence
                where t_planning_niveau.oid * 1000000 + t_planning_type_absence.oid not in (select oid from rh.t_section_analytique group by 1)
                group by 1,2,3,4,5
            ;

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

            CREATE TEMP TABLE w_ven AS
                with base_hp as (
                        select
                            salarie_id,
                            date_debut,
                            date_fin
                        from rh.p_historique_paie
                        where true
                            -- and salarie_id in (select oid from rh.p_salaries where matricule = '1019')
                            -- and mois_paie = 201710
                        group by 1,2,3
                    ), unused as (
                    select p_planning_mouvement.*
                    from rh.p_planning_mouvement
                        left join base_hp on 1=1
                            and p_planning_mouvement.salarie_id = base_hp.salarie_id
                            and p_planning_mouvement.date between base_hp.date_debut and base_hp.date_fin
                    where true
                        and base_hp.salarie_id is null
                        -- and p_planning_mouvement.salarie_id in (select oid from rh.p_salaries where matricule = '1019')
                        -- and p_planning_mouvement.mois in (201710, 201709)
                    ), base as (
                        select
                            base_hp.salarie_id,
                            base_hp.date_debut,
                            base_hp.date_fin,
                            coalesce(t1.niveau_id * 1000000 + t1.type_absence_id, t2.niveau_id * 1000000 + t2.type_absence_id, 0) as section_analytique_id,
                            coalesce(sum(t1.temps_valide + t1.temps_absence), sum(t2.temps_valide + t2.temps_absence), 0) as temps_du
                        from base_hp
                            left join rh.p_planning_mouvement as t1 on 1=1
                                and t1.salarie_id = base_hp.salarie_id
                                and t1.date between base_hp.date_debut and base_hp.date_fin
                            left join unused as t2 on 1=1
                                and t2.salarie_id = base_hp.salarie_id
                                and t1.date is null
                                and to_char(t2.date + '1 month'::interval, 'YYYYMM')::int = to_char(base_hp.date_debut, 'YYYYMM')::int
                        group by 1,2,3,4
                        -- having sum(@temps_valide + @temps_absence) != 0 -- Pour avoir les sections ana. non attribuées.
                    ), ven_0 as (
                        select
                            salarie_id,
                            date_debut,
                            date_fin,
                            section_analytique_id,
                            base.cti_division(temps_du, sum(temps_du) over (partition by salarie_id, date_debut, date_fin)) as ratio
                        from base
                    ), ven as (
                        select
                            salarie_id,
                            date_debut,
                            date_fin,
                            section_analytique_id,
                            ratio
                        from ven_0  
                        where false -- Filtrage des sections ana. à 0 sauf lorsque section toute seule (future section non renseignée à 100%)
                            or section_analytique_id = 0 -- on garde les futures sections ana. à 0 futures non renseignées...
                            or ratio != 0 -- ...ou celles qui ont un ratio.
                    ), corr as (
                        select
                            salarie_id,
                            date_debut,
                            date_fin,
                            (max(array[ratio, section_analytique_id]))[2] as section_analytique_id,
                            1.0 - sum(ratio) as ratio
                        from ven
                        group by 1,2,3
                        having sum(ratio) != 1)
                select
                    salarie_id,
                    date_debut,
                    date_fin,
                    section_analytique_id,
                    t_section_analytique.code_original as section_analytique_code_original,
                    sum(ratio) as ratio
                from (select * from ven union all select * from corr) as subq
                    join rh.t_section_analytique on t_section_analytique.oid = section_analytique_id
                group by 1,2,3,4,5
            ;

            DROP TABLE IF EXISTS w_ven_agg
            ;

            CREATE TEMP TABLE w_ven_agg AS
                select
                    salarie_id,
                    date_debut,
                    date_fin,
                    dense_rank() over (order by array_agg(section_analytique_id order by section_analytique_id), array_agg(ratio order by section_analytique_id)) as ventilation_id,
                    array_to_string(array_agg(section_analytique_code_original||'@'||(round(ratio*100)) order by section_analytique_code_original), ', ') as ventilation_texte
                FROM w_ven
                group by 1,2,3
            ;

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

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

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

            -- Création des 3 classes de niveaux.
            DROP TABLE IF EXISTS w_classes
            ;

            CREATE TEMP TABLE w_classes AS
                with classe_table as (
                    select 'PLAANANIV1' as code, '[DICT.RH.NIVEAU1#1]' as texte, 1 as sequence
                UNION ALL
                    select 'PLAANANIV2' as code, '[DICT.RH.NIVEAU2#1]' as texte, 2 as sequence
                UNION ALL
                    select 'PLAANANIV3' as code, '[DICT.RH.NIVEAU3#1]' as texte, 3 as sequence
                UNION ALL
                    select 'PLAANATABS' as code, 'Type d''absence' as texte, 4 as sequence)
                SELECT code, texte, table_id, 0 as is_cti, sequence
                FROM classe_table, (select oid as table_id from rh.t_listes_tables where code = 'ANA' LIMIT 1) as subq
            ;

            insert into rh.t_classes (code, texte, table_id, is_cti, sequence)
                select code, texte, table_id, is_cti, sequence
                FROM w_classes
                where code NOT in (select code from rh.t_classes where code is not null)
            ;

            update rh.t_classes set
                texte = w_classes.texte
            FROM w_classes
            WHERE true
                and w_classes.code = t_classes.code
                and w_classes.texte is distinct from t_classes.texte
            ;

            -- Nettoyage du contenu
            delete from rh.t_classes_sections_elements
            where section_id in (
                select s.oid from rh.t_classes as c
                join rh.t_classes_sections as s on s.classe_id = c.oid
                where c.code IN ('PLAANANIV1', 'PLAANANIV2', 'PLAANANIV3', 'PLAANATABS'))
            ;

            -- Mise à jour des sections Niveau 1.
            DROP TABLE IF EXISTS w_clasec_1
            ;

            CREATE TEMP TABLE w_clasec_1 AS
                SELECT
                    niv_cod1 as code,
                    niv_lib1 as texte,
                    (select oid from rh.t_classes where code = 'PLAANANIV1') as classe_id
                FROM prod_octime_niveau1
                GROUP BY 1,2,3
            ;

            INSERT INTO rh.t_classes_sections(code, texte, classe_id)
                SELECT code, texte, classe_id
                from w_clasec_1
                where 1=1
                    and classe_id = (select oid from rh.t_classes where code = 'PLAANANIV1')
                    and code not in (select code from rh.t_classes_sections where t_classes_sections.classe_id = w_clasec_1.classe_id and code is not null)
                group by 1,2,3
            ;

            update rh.t_classes_sections set
                texte = w_clasec_1.texte
            FROM w_clasec_1
            WHERE true
                and w_clasec_1.classe_id = t_classes_sections.classe_id
                and w_clasec_1.code = t_classes_sections.code
                and w_clasec_1.texte is distinct from t_classes_sections.texte
            ;

            -- Mise à jour du contenu des sections Niveau 1.
            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_section_analytique.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join rh.t_section_analytique on split_part(code_original, '|', 1) = t_classes_sections.code
                WHERE t_classes.code = 'PLAANANIV1'
                group by 1,2
            ;

            -- Mise à jour des sections Niveau 2.
            DROP TABLE IF EXISTS w_clasec_2
            ;

            CREATE TEMP TABLE w_clasec_2 AS
                with nb_niv as (
                    select
                        niv_cod2, count(DISTINCT niv_lib2) as niv_count
                    from prod_octime_niveau2
                    group by 1
                    )
                SELECT
                    case when niv_count = 1 then niveau2.niv_cod2 else niveau2.niv_cod1 || '|' || niveau2.niv_cod2 end as code,
                    niveau2.niv_cod1 || '|' || niveau2.niv_cod2 as code_original,
                    niveau2.niv_lib2 as texte,
                    (select oid from rh.t_classes where code = 'PLAANANIV2') as classe_id
                from prod_octime_niveau2 as niveau2
                    JOIN nb_niv ON nb_niv.niv_cod2 = niveau2.niv_cod2
                group by 1,2,3
            ;

            INSERT INTO rh.t_classes_sections(code, texte, classe_id)
                SELECT code, texte, classe_id
                from w_clasec_2
                where 1=1
                    and classe_id = (select oid from rh.t_classes where code = 'PLAANANIV2')
                    and code not in (select code from rh.t_classes_sections where t_classes_sections.classe_id = w_clasec_2.classe_id and code is not null)
                group by 1,2,3
            ;

            update rh.t_classes_sections set
                texte = w_clasec_2.texte
            FROM w_clasec_2
            WHERE true
                and w_clasec_2.classe_id = t_classes_sections.classe_id
                and w_clasec_2.code = t_classes_sections.code
                and w_clasec_2.texte is distinct from t_classes_sections.texte
            ;

            -- Mise à jour du contenu des sections Niveau 2.
            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_section_analytique.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join w_clasec_2 on true
                        and w_clasec_2.classe_id = t_classes.oid
                        and w_clasec_2.code = t_classes_sections.code
                    join rh.t_section_analytique on split_part(t_section_analytique.code_original, '|', 1)||'|'||split_part(t_section_analytique.code_original, '|', 2) = w_clasec_2.code_original
                WHERE t_classes.code = 'PLAANANIV2'
                group by 1,2
            ;

            -- Mise à jour des sections Niveau 3.
            DROP TABLE IF EXISTS w_clasec_3
            ;

            CREATE TEMP TABLE w_clasec_3 AS
                with nb_niv as (
                    select
                        niv_cod3, count(DISTINCT niv_lib3) as niv_count
                    from prod_octime_niveau3
                    group by 1
                    )
                SELECT
                    case when niv_count = 1 then niveau3.niv_cod3 else niveau3.niv_cod1 || '|' || niveau3.niv_cod2|| '|' || niveau3.niv_cod3 end as code,
                    niveau3.niv_cod1 || '|' || niveau3.niv_cod2|| '|' || niveau3.niv_cod3 as code_original,
                    niveau3.niv_lib3 as texte,
                    (select oid from rh.t_classes where code = 'PLAANANIV3') as classe_id
                from prod_octime_niveau3 as niveau3
                    JOIN nb_niv ON nb_niv.niv_cod3 = niveau3.niv_cod3
                group by 1,2,3
            ;

            INSERT INTO rh.t_classes_sections(code, texte, classe_id)
                SELECT code, texte, classe_id
                from w_clasec_3
                where 1=1
                    and classe_id = (select oid from rh.t_classes where code = 'PLAANANIV3')
                    and code not in (select code from rh.t_classes_sections where t_classes_sections.classe_id = w_clasec_3.classe_id and code is not null)
                group by 1,2,3
            ;

            update rh.t_classes_sections set
                texte = w_clasec_3.texte
            FROM w_clasec_3
            WHERE true
                and w_clasec_3.classe_id = t_classes_sections.classe_id
                and w_clasec_3.code = t_classes_sections.code
                and w_clasec_3.texte is distinct from t_classes_sections.texte
            ;

            -- Mise à jour du contenu des sections Niveau 3.
            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_section_analytique.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join w_clasec_3 on true
                        and w_clasec_3.classe_id = t_classes.oid
                        and w_clasec_3.code = t_classes_sections.code
                    join rh.t_section_analytique on
                        split_part(t_section_analytique.code_original, '|', 1)||'|'||
                        split_part(t_section_analytique.code_original, '|', 2)||'|'||
                        split_part(t_section_analytique.code_original, '|', 3) = w_clasec_3.code_original
                WHERE t_classes.code = 'PLAANANIV3'
                group by 1,2
            ;

            -- Mise à jour des sections Niveau 4.
            DROP TABLE IF EXISTS w_clasec_4
            ;

            CREATE TEMP TABLE w_clasec_4 AS
                with nb_niv as (
                    select
                        niv_cod4, count(DISTINCT niv_lib4) as niv_count
                    from prod_octime_niveau4
                    group by 1
                    )
                SELECT
                    case when niv_count = 1 then niveau4.niv_cod4 else niveau4.niv_cod1 || '|' || niveau4.niv_cod2|| '|' || niveau4.niv_cod3|| '|' || niveau4.niv_cod4 end as code,
                    niveau4.niv_cod1 || '|' || niveau4.niv_cod2|| '|' || niveau4.niv_cod3|| '|' || niveau4.niv_cod4 as code_original,
                    niveau4.niv_lib4 as texte,
                    (select oid from rh.t_classes where code = 'PLAANANIV4') as classe_id
                from prod_octime_niveau4 as niveau4
                    JOIN nb_niv ON nb_niv.niv_cod4 = niveau4.niv_cod4
                group by 1,2,3
            ;

            INSERT INTO rh.t_classes_sections(code, texte, classe_id)
                SELECT code, texte, classe_id
                from w_clasec_4
                where 1=1
                    and classe_id = (select oid from rh.t_classes where code = 'PLAANANIV4')
                    and code not in (select code from rh.t_classes_sections where t_classes_sections.classe_id = w_clasec_4.classe_id and code is not null)
                group by 1,2,3
            ;

            update rh.t_classes_sections set
                texte = w_clasec_4.texte
            FROM w_clasec_4
            WHERE true
                and w_clasec_4.classe_id = t_classes_sections.classe_id
                and w_clasec_4.code = t_classes_sections.code
                and w_clasec_4.texte is distinct from t_classes_sections.texte
            ;

            -- Mise à jour du contenu des sections Niveau 4.
            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_section_analytique.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join w_clasec_4 on true
                        and w_clasec_4.classe_id = t_classes.oid
                        and w_clasec_4.code = t_classes_sections.code
                    join rh.t_section_analytique on
                        split_part(t_section_analytique.code_original, '|', 1)||'|'||
                        split_part(t_section_analytique.code_original, '|', 2)||'|'||
                        split_part(t_section_analytique.code_original, '|', 3)||'|'||
                        split_part(t_section_analytique.code_original, '|', 4) = w_clasec_4.code_original
                WHERE t_classes.code = 'PLAANANIV4'
                group by 1,2
            ;

            /**********************
             * CLASSES d'ABSENCES *
             **********************/
            -- Mise à jour des sections Niveau 4.
            DROP TABLE IF EXISTS w_clasec_4
            ;

            CREATE TEMP TABLE w_clasec_4 AS
                SELECT
                    abs_cod as code,
                    abs_cod as code_original,
                    abs_lib as texte,
                    (select oid from rh.t_classes where code = 'PLAANATABS') as classe_id
                from prod_octime_absence as absence
                group by 1,2,3
            ;

            INSERT INTO rh.t_classes_sections(code, texte, classe_id)
                SELECT code, texte, classe_id
                from w_clasec_4
                where 1=1
                    and classe_id = (select oid from rh.t_classes where code = 'PLAANATABS')
                    and code not in (select code from rh.t_classes_sections where t_classes_sections.classe_id = w_clasec_4.classe_id and code is not null)
                group by 1,2,3
            ;

            update rh.t_classes_sections set
                texte = w_clasec_4.texte
            FROM w_clasec_4
            WHERE true
                and w_clasec_4.classe_id = t_classes_sections.classe_id
                and w_clasec_4.code = t_classes_sections.code
                and w_clasec_4.texte is distinct from t_classes_sections.texte
            ;

            -- Mise à jour du contenu des sections Niveau 4.
            INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
                SELECT
                    t_classes_sections.oid AS section_id,
                    t_section_analytique.oid AS to_id
                FROM rh.t_classes
                    join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
                    join w_clasec_4 on true
                        and w_clasec_4.classe_id = t_classes.oid
                        and w_clasec_4.code = t_classes_sections.code
                    join rh.t_section_analytique on split_part(t_section_analytique.code_original, '|', 4) = w_clasec_4.code_original
                WHERE t_classes.code = 'PLAANATABS'
                group by 1,2
            ;

            SELECT rh.cti_update_schema_classes('*ALL')
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE name="VENTILATION" label="Application sur le Plan 1">
            <condition><![CDATA[

            SELECT valeur = 1
            FROM rh.t_divers
            WHERE code = 'OCTIME_VENTILATION'
            ;

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

            UPDATE rh.p_historique_paie
            SET ventilation_1_id = subq.ventilation_id
            FROM (
                select
                    p_historique_paie.oid,
                    coalesce(ventilation_id, 0) as ventilation_id
                from rh.p_historique_paie
                    left join w_ven_agg on 1=1
                        and w_ven_agg.salarie_id = p_historique_paie.salarie_id
                        and w_ven_agg.date_debut = p_historique_paie.date_debut
                        and w_ven_agg.date_fin = p_historique_paie.date_fin
                group by 1,2) as subq
            WHERE p_historique_paie.oid = subq.oid
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE name="VENTILATION" label="Application sur le Plan 2">
            <condition><![CDATA[

            SELECT valeur = 2
            FROM rh.t_divers
            WHERE code = 'OCTIME_VENTILATION'
            ;

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

            UPDATE rh.p_historique_paie
            SET ventilation_2_id = subq.ventilation_id
            FROM (
                select
                    p_historique_paie.oid,
                    coalesce(ventilation_id, 0) as ventilation_id
                from rh.p_historique_paie
                    left join w_ven_agg on 1=1
                        and w_ven_agg.salarie_id = p_historique_paie.salarie_id
                        and w_ven_agg.date_debut = p_historique_paie.date_debut
                        and w_ven_agg.date_fin = p_historique_paie.date_fin
                where true
                    -- and salarie_id in (select oid from rh.p_salaries where matricule = '0605')
                    -- and mois_paie = 201710
                group by 1,2) as subq
            WHERE p_historique_paie.oid = subq.oid
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE name="VENTILATION" label="Application sur le Plan 3">
            <condition><![CDATA[

            SELECT valeur = 3
            FROM rh.t_divers
            WHERE code = 'OCTIME_VENTILATION'
            ;

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

            UPDATE rh.p_historique_paie
            SET ventilation_3_id = subq.ventilation_id
            FROM (
                select
                    p_historique_paie.oid,
                    coalesce(ventilation_id, 0) as ventilation_id
                from rh.p_historique_paie
                    left join w_ven_agg on 1=1
                        and w_ven_agg.salarie_id = p_historique_paie.salarie_id
                        and w_ven_agg.date_debut = p_historique_paie.date_debut
                        and w_ven_agg.date_fin = p_historique_paie.date_fin
                group by 1,2) as subq
            WHERE p_historique_paie.oid = subq.oid
            ;

            ]]></sqlcmd>
        </NODE>
    </NODE>
</ROOT>