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

			-- Màj des Entreprises
			/*
			INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court)
				SELECT cpy_0, crn_0, cpynam_0, substr(cpynam_0, 1, 50)
				FROM prod_sagex3rhp.company
				WHERE 1=1
					AND crn_0 IN (SELECT substr(rhp('siren'), 1, 9)) -- SIREN
					AND cpy_0 NOT IN (SELECT code_original FROM rh.t_entreprises)
			;
			*/

			-- Màj des Etablissements
			/*INSERT INTO rh.t_etablissements(code_original, code, texte, texte_court, entreprise_id)
				SELECT fcy_0, facility.crn_0, substr(fcynam_0, 1, 50), fcynam_0, t_entreprises.oid
				from prod_sagex3rhp.company
					join prod_sagex3rhp.facility on facility.fcy_0 = company.maifcy_0
					join rh.t_entreprises on t_entreprises.code_original = company.cpy_0
				WHERE 1=1
					AND facility.crn_0 IN (SELECT rhp('siren')) -- SIRET
					AND fcy_0 NOT IN (SELECT code_original FROM rh.t_etablissements)
			;*/

			]]></sqlcmd>
		</NODE>
		<NODE label="Pre-traitements des tables prestataire">
			<sqlcmd><![CDATA[

			-- Remontée des fichiers CSV a01_compta.
			delete from prod_pleiades.a01_compta
			where periode_imputation < 1512
			;

			drop table if exists w_imp
			;
			create temp table w_imp as
				select
					''::text as societe,
					''::text as etablissement,
					''::text as matricule,
					''::text as contrat,
					''::text as num_ordre,
					''::text as ligne_budget,
					''::text as regroupement,
					''::text as critere_1,
					''::text as critere_2,
					''::text as critere_3,
					''::text as critere_4,
					''::text as periode_origine,
					''::text as sous_periode,
					''::text as date_debut_periode,
					''::text as date_fin_periode,
					''::text as periode_imputation,
					''::text as periode_annulation,
					''::text as type,
					''::text as date_comptable,
					''::text as critere_imputation_1,
					''::text as critere_imputation_2,
					''::text as critere_imputation_3,
					''::text as imputation,
					''::text as compte,
					''::text as mandatement,
					''::text as ecriture,
					''::text as poste,
					''::text as poste_nature,
					''::text as exercice,
					''::text as fournisseur,
					''::text as zone_libre,
					''::text as nombre,
					''::text as taux,
					''::text as credit,
					''::text as debit
				limit 0
			;

			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201501.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201502.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201503.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201504.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201505.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201506.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201507.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201508.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201509.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201510.csv' CSV HEADER delimiter ';';
			copy w_imp from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/201511.csv' CSV HEADER delimiter ';';

			insert into prod_pleiades.a01_compta
				select
					trim(societe),
					trim(etablissement),
					trim(matricule),
					trim(contrat),
					num_ordre::numeric,
					trim(ligne_budget),
					trim(regroupement),
					trim(critere_1),
					trim(critere_2),
					trim(critere_3),
					trim(critere_4),
					trim(periode_origine),
					trim(sous_periode),
					to_date(date_debut_periode, 'DD/MM/YY'),
					to_date(date_fin_periode, 'DD/MM/YY'),
					trim(periode_imputation),
					trim(periode_annulation),
					trim(type),
					to_date(date_comptable, 'DD/MM/YY'),
					trim(critere_imputation_1),
					trim(critere_imputation_2),
					trim(critere_imputation_3),
					trim(imputation),
					trim(compte),
					trim(mandatement),
					trim(ecriture),
					trim(poste),
					trim(poste_nature),
					trim(exercice),
					trim(fournisseur),
					trim(zone_libre),
					replace(nombre, ',', '.')::numeric,
					replace(taux, ',', '.')::numeric,
					replace(credit, ',', '.')::numeric + replace(debit, ',', '.')::numeric,
					replace(credit, ',', '.')::numeric,
					replace(debit, ',', '.')::numeric,
					''::text
				from w_imp
			;

			-- Création de période pour les CSP.
			drop table if exists w_cnt_csp
			;

			create temp table w_cnt_csp as
				select
					cb as mat,
					cb||'-'||(rank() over (partition by cb order by cf))::text as csp_num,
					cf::date as date_debut,
					coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
					lower(c01) as csp_code
				from prod_pleiades.d01v1_percsp
			;

			-- permet = métier.
			--select c01,C02,C03
			--from prod_pleiades.d01v1_permet
			-- by 1,2,3;


			/*select
				cb as mat,
				cf::date as date_debut,
				coalesce(c07::date, '20991231'::date) as date_fin,
				c02,
				c04,
				c06
			from prod_pleiades.d01v1_peremp
			;*/
			drop table if exists w_cnt_emp
			;

			create temp table w_cnt_emp as
				select
					cb as mat,
					cb||'-'||(rank() over (partition by cb order by cf))::text as emp_num,
					cf::date as date_debut,
					coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
					c02 as emp_code,
					c06 as sta_code,
					trim(substr(c08, 37, 3)) as qua_code
				from prod_pleiades.d01v1_peremp
			;

			drop table if exists w_cnt_aff
			;

			create temp table w_cnt_aff as
				select
					cb as mat,
					cb||'-'||(rank() over (partition by cb order by cf))::text as aff_num,
					cf::date as date_debut,
					coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
					ce as uf_code,
					trim(c03) as cec_code -- code emploi compta.
				from prod_pleiades.d01v1_peraff
				where c01 = 'P' -- uniquement l'affectation principale pour les services.
				-- Le salarié 09362 est ventilé à 50% sur l'UF RE18, 28% sur AN18 et 22% sur 1A18.
			;

			drop table if exists w_cnt_ttt
			;

			create temp table w_cnt_ttt as
				select
					cb as mat,
					cb||'-'||(rank() over (partition by cb order by cf))::text as ttt_num,
					cf::date as date_debut,
					coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
					case when @c03 >= 100 OR @c03 = 0 then 'TC' else 'TP'||(@c03)::text end as ttt_code
				from prod_pleiades.d01v1_perxhx
			;

			drop table if exists w_cnt_tho
			;

			create temp table w_cnt_tho as
				select
					cb as mat,
					cb||'-'||(rank() over (partition by cb order by cf))::text as tho_num,
					cf::date as date_debut,
					coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
					c07 as tho_code
				from prod_pleiades.d01v1_pereta
			;

			-- Relation 1 pour 1 entre le matricule et la spécialité.
			drop table if exists w_cnt_spe
			;

			create temp table w_cnt_spe as
				select
					cb as mat,
					max(c02)::text AS spe_code -- on enfonce le clou (1 pour 1) par sécurité.
				from prod_pleiades.d01v1_perxme
				group by 1
			;

			-- Création table des contrats.
			drop table if exists w_cnt
			;

			create temp table w_cnt as
				select
					d01v1_perctr.cb as mat,
					d01v1_perctr.cb||'-'||rank() over (partition by d01v1_perctr.cb order by d01v1_perctr.cf) as cnt,
					d01v1_perctr.cf::date as date_debut,
					coalesce(d01v1_perctr.c09::date, '20991231'::date) as date_fin,
					d01v1_perctr.c02 as motif_debut,
					d01v1_perctr.c08 as motif_fin,
					d01v1_perctr.c03 as nature_contrat, -- à concaténer avec le type de contrat
					d01v1_perctr.c04 as type_contrat,
					d01v1_percdd.c03 as mat_remp
				from prod_pleiades.d01v1_perctr
					left join prod_pleiades.d01v1_percdd on 1=1
						and d01v1_percdd.cb = d01v1_perctr.cb
						and d01v1_percdd.cf = d01v1_perctr.cf
			;

			-- Création table de compte comptables.
			drop table if exists w_compte
			;

			create temp table w_compte as
				select
					poste,
					matricule,
					compte,
					('20'||periode_imputation)::numeric as periode_imputation,
					sous_periode,
					periode_origine
				from prod_pleiades.a01_compta
				where 1=1
					and ecriture = 'C'
					and compte != '999999999'
				group by 1,2,3,4,5,6
			;

			-- Création d'une table brut de paie
			/*drop table if exists w_hp
			;

			create temp table w_hp as
				select
					trim(mat) as mat,
					mois,
					date1 as date_virement,
					trim(col1) as sous_periode,
					date_debut,
					date_fin,
					mois != to_char(date_debut, 'YYYYMM')::numeric as regul, -- true quand régulation.
					trim(nb1) as rub,
					to_number(mnt2, 'SG000000000D00') as base,
					to_number(mnt3, 'SG000000000D00') as tx,
					to_number(mnt4, 'SG000000000D00') as mt
				from prod_pleiades.cti_pfedis01
			;*/

			-- créer une vue  avec ca : vvvvvv
			DROP VIEW IF EXISTS public.w_hp
			;

			CREATE OR REPLACE VIEW public.w_hp AS 
				select
					ctid as hp_ctid,
					trim(matricule) as mat,
					date_compta::numeric as mois,
					date_comptable::date as date_virement,
					periode as sous_periode,
					debut_periode::date as date_debut,
					fin_periode::date as date_fin,
					date_compta != to_char(debut_periode, 'YYYYMM')::numeric as regul,
					trim(poste) as rub,
					nombre as base,
					taux as tx,
					montant as mt
				from prod_pleiades.a01_z_paic
			;

			-- Créer une table des bulletins.
			-- Les rubriques de régulation (en "R") seront affectées systématiquement au 1er bulletin du mois.
			DROP TABLE IF EXISTS w_bul
			;
			CREATE TEMP TABLE w_bul AS
				with bul_mois as (
				select
					mat,
					mois,
 					case when mois = to_char(date_debut, 'YYYYMM')::numeric then date_debut else (mois||'01')::date end as date_debut,
					case when mois = to_char(date_debut, 'YYYYMM')::numeric then date_fin else base.cti_last_day((mois||'01')::date) end as date_fin,
					count(*) over (partition by mat, mois) as nb_bul_month,
					count(case when mois = to_char(date_debut, 'YYYYMM')::numeric then date_debut else null end) as nb_lines_month
				from w_hp
				group by 1,2,3,4)
				--
				select
					mat||mois||lpad(rank() over (partition by mat, mois order by date_debut), 2, '0') as bul,
					*
				from bul_mois
				where case when nb_lines_month = 0 then nb_bul_month = 1 else  true end -- on ne conserve que les bulletins mois qui n'ont aucune ligne sur le mois d'imputation (100% de régul).
			;

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

			-- Màj des codes postaux.
			INSERT INTO rh.t_codes_postaux(oid, code, texte, texte_court, departement_id)
				select
					1000000000::numeric + c05::numeric,
					c05,
					max(c06),
					max(substr(c06, 1, 50)),
					coalesce(t_departements.oid, 0)
				from prod_pleiades.d01v1_perad1
					left join base.t_departements on t_departements.code = substr(c05, 1, 2)
				where c05 NOT IN (SELECT code FROM rh.t_codes_postaux)
				GROUP BY 1,2,5
			;

			UPDATE rh.t_codes_postaux
			SET departement_code = t_departements.code,
				departement_texte = t_departements.texte
			FROM base.t_departements
			WHERE 1=1
				AND t_codes_postaux.departement_texte = '' -- et pas IS NULL car il y a une valeur par défaut.
				AND t_codes_postaux.departement_id = t_departements.oid
			;

			-- Màj des catégories socio-professionnelles : à renseigner avec les données de prod.
			INSERT INTO rh.t_categories_socio_professionnelle (code_original, code, texte, texte_court)
				select lower(ce), lower(ce), max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'CATPRO'
					and lower(ce) NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
				GROUP BY 1,2
			;

			-- Màj des motifs de début de contrat.
			INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'MOTCTR'
					and ce NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
				GROUP BY 1,2
			;

			-- Màj des motifs de fin de contrat.
			INSERT INTO rh.t_motifs_fin_contrat(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'MOTCTR'
					and ce NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
				GROUP BY 1,2
			;

			-- Màj des nationalités.
			INSERT INTO rh.t_nationalites(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'NATION'
					and ce NOT IN (SELECT code_original FROM rh.t_nationalites)
				GROUP BY 1,2
			;

			-- Màj des qualifications.
			INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
				select trim(ce), trim(ce), max(trim(c01)), max(trim(substr(c02, 1, 50)))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'QUALIF'
					and trim(ce) NOT IN (SELECT code_original FROM rh.t_qualifications)
				GROUP BY 1,2
			;

			-- Màj des rubriques table rubrique
			INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
				SELECT d01v5_tdpnom.cb, d01v5_tdpnom.cb, min(d01v5_tdpnom.c01), substr(min(d01v5_tdpnom.c01), 1, 50), min(d01v5_tdpnom.cb)::numeric
				FROM prod_pleiades.d01v5_tdpnom
					--JOIN prod_pleiades.d01v5_tdpbul ON d01v5_tdpbul.cb = d01v5_tdpnom.cb
				WHERE d01v5_tdpnom.cb NOT IN (SELECT code_original FROM rh.t_rubriques)
				GROUP BY 1,2
			;

			-- Création des rubriques CTI de cumul.
			INSERT INTO rh.t_rubriques(code, texte, texte_court, code_original, rang_edition)
				SELECT 'C000', 'Ecart cumulé', 'Ecart cumulé', 'C000', -1
				WHERE 'C000' NOT IN (SELECT code_original FROM rh.t_rubriques)
			;

			-- Màj des comptes.
			INSERT INTO rh.t_compte(code_original, code, texte, texte_court)
				SELECT compte, compte, compte, compte
				FROM w_compte
				WHERE compte NOT IN (SELECT code_original FROM rh.t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
			;

			-- Màj des situations de famille.
			INSERT INTO rh.t_situations_famille(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'SITFAM'
					and ce NOT IN (SELECT code_original FROM rh.t_situations_famille)
				GROUP BY 1,2
			;

			-- Màj des types de contrat.
			INSERT INTO rh.t_types_contrat(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'TYPCTR' -- à peut-être concaténer avec NATCTR pour avoir plus de détail
					and ce NOT IN (SELECT code_original FROM rh.t_types_contrat)
				GROUP BY 1,2
			;

			-- Màj des statuts
			INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'XFBTYP'
					and ce NOT IN (SELECT code_original FROM rh.t_statuts)
				GROUP BY 1,2
			;

			-- Màj des types de temps de travail
			INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
				select
					ttt_code,
					ttt_code,
					case when ttt_code = 'TC' then 'Temps Complet' else 'Temps Partiel '||substr(ttt_code, 3)||'%' end,
					case when ttt_code = 'TC' then 'Temps Complet' else 'Temps Partiel '||substr(ttt_code, 3)||'%' end
				from w_cnt_ttt
				WHERE ttt_code NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
				group by 1,2,3,4
			;

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

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

			-- Màj des services
			INSERT INTO rh.t_services(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'UF'
					and ce NOT IN (SELECT code_original FROM rh.t_services)
				GROUP BY 1,2
			;

			-- Màj des spécialités
			INSERT INTO rh.t_specialites(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'SAEQ'
					and ce NOT IN (SELECT code_original FROM rh.t_specialites)
				GROUP BY 1,2
			;

			-- Màj des codes emploi
			INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'EMPLOI'
					and ce NOT IN (SELECT code_original FROM rh.t_codes_emploi)
				GROUP BY 1,2
			;

			-- Màj des types d'horaire.
			INSERT INTO rh.t_types_horaire(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'JOUNUI'
					and ce NOT IN (SELECT code_original FROM rh.t_types_horaire)
				GROUP BY 1,2
			;

			-- Màj des grilles (coeff de Sage).
			/*INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
				select
					grille,
					grille,
					grille,
					grille
				from (
						select grille from w_cnt
					UNION
						select coeff as grille from w_bul) as subq
				where 1=1
					and grille NOT IN (SELECT code_original FROM rh.t_grilles)
				group by 1,2,3,4
			;*/

			-- Màj des groupes de grilles
			/*INSERT INTO rh.t_grilles_groupes(code_original, code, texte, texte_court)
				select
					ident2_0,
					ident2_0,
					max(case when zone_0 = 'LNGDES' then texte_0 else '' end),
					max(case when zone_0 = 'SHODES' then texte_0 else '' end)
				from prod_sagex3rhp.atextra
				where 1=1
					and (select x_mode from w_gri) = false -- grille mode y
					and codfic_0 = 'ATABDIV'
					and ident1_0 = '1023'
					and ident2_0 NOT IN (SELECT code_original FROM rh.t_grilles_groupes)
				group by 1,2
			;*/

			-- Màj des codes emplois compta.
			INSERT INTO rh.t_sections_analytiques(code_original, code, texte, texte_court)
				select 
					trim(c03),
					trim(c03),
					trim(c03),
					trim(c03)
				from prod_pleiades.d01v1_peraff
				where true
					and c01 = 'P'
					and trim(c03) NOT IN (SELECT code_original FROM rh.t_sections_analytiques)
				group by 1,2,3,4
			;

			-- Màj des motifs d'arret
			INSERT INTO rh.t_motifs_arret(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'CODABS'
					and ce NOT IN (SELECT code_original FROM rh.t_motifs_arret)
				GROUP BY 1,2
			;

			-- Màj des motifs de visite médicale
			INSERT INTO rh.t_motifs_visite(code_original, code, texte, texte_court)
				select ce, ce, max(c01), max(substr(c02, 1, 50))
				from prod_pleiades.d01v3_tabdef
				where 1=1
					and cb = 'MEDICA'
					and ce NOT IN (SELECT code_original FROM rh.t_motifs_visite)
				GROUP BY 1,2
			;

			-- Insertion du Plan Analytique.
			TRUNCATE rh.t_plan_analytique
			;
			INSERT INTO rh.t_plan_analytique(oid, code, texte)
    		VALUES
    			(1, 'A01_COMPTA', 'Plan analytique a01_compta.')
    			--,(2, 'PERAFF', 'Plan analytique UF.')
    		;

			-- Màj des sections analytiques.
			INSERT INTO rh.t_section_analytique(code_original, code, texte, texte_court)
				select imputation, imputation, imputation, imputation
				from prod_pleiades.a01_compta
				where imputation NOT IN (SELECT code FROM rh.t_section_analytique)
				group by 1,2,3,4
			;

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

			DROP TABLE IF EXISTS w_chiffrier
			;
			CREATE TEMP TABLE w_chiffrier AS
				SELECT
					0 as entreprise_id,
					0 as etablissement_id,
					w_bul.mois,
					w_bul.date_fin as date_paie,
					w_bul.date_debut,
					w_bul.date_fin,
					w_bul.mat,
					w_bul.bul,
					sum(CASE WHEN rub = '6001' THEN mt ELSE 0 END) AS montant_brut,
					sum(CASE WHEN rub = '8792' THEN mt ELSE 0 END) AS montant_cotisation_salarie,
					sum(CASE WHEN rub = '8790' THEN mt ELSE 0 END) AS montant_cotisation_patronale, -- correction 6829 à intégrer (entre autres); 1er janvier 2016 : l'assiette est rentrée dans l'ordre.
					sum(CASE WHEN rub = '8805' THEN mt ELSE 0 END) AS montant_net_imposable_salarie,
					sum(CASE WHEN rub = '9700' THEN mt ELSE 0 END) AS montant_net_a_payer_salarie,
					sum(CASE WHEN rub = '6019' THEN mt ELSE 0 END) AS nombre_heures_p,
					sum(CASE WHEN rub = '9953' THEN mt ELSE 0 END) AS nombre_heures_w -- ou 6020 ?
				FROM w_hp
					JOIN w_bul on w_bul.bul = w_hp.mat||w_hp.mois||(case when to_char(w_hp.date_debut, 'YYYYMM')::numeric = w_hp.mois then substring(sous_periode, 8, 2) else '01' end)
				WHERE true
					and rub != '0457'
					and rub in ('0600','0610','4000','4682','6001','8792','8790','8805','9700','6019','9953','8898','9688')
				GROUP BY 1,2,3,4,5,6,7,8
				HAVING false
					OR sum(CASE WHEN rub = '0600' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '0610' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '4000' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '4682' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '6001' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '8792' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '8790' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '8805' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '9700' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '6019' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '9953' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '8898' THEN mt ELSE 0 END) != 0
					OR sum(CASE WHEN rub = '9688' THEN mt ELSE 0 END) != 0
			;

			TRUNCATE rh.p_chiffrier_production
			;

			INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
				SELECT
					entreprise_id,
					etablissement_id,
					mois,
					count(DISTINCT mat),
					sum(montant_brut),
					sum(nombre_heures_p)
				FROM w_chiffrier
				GROUP BY 1,2,3
			;

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

			-- Détermination des limites d'évènements salariés (utilisé uniquement pour la ventilation jusqu'à aujourd'hui).
			DROP TABLE IF EXISTS w_lmt
			;

			CREATE TEMP TABLE w_lmt AS
				WITH w_lmt_cnt AS (
			        SELECT
			        	mat,
			        	min(date_debut) as date_debut,
			        	max(date_fin) as date_fin
			        FROM w_cnt
			        GROUP BY 1),
				w_lmt_bul as (
					select
						mat,
						min(date_debut) as date_debut,
						max(date_fin) as date_fin
					from w_bul
					group by 1)
				SELECT
					coalesce(w_lmt_cnt.mat, w_lmt_bul.mat) as mat,
					min(least(w_lmt_cnt.date_debut, w_lmt_bul.date_debut)) as min_date,
					greatest(least(max(w_lmt_cnt.date_fin), current_date), max(w_lmt_bul.date_fin)) as max_date
				FROM prod_pleiades.d01v1_per
					left JOIN w_lmt_cnt ON w_lmt_cnt.mat = d01v1_per.ce
					left join w_lmt_bul on w_lmt_bul.mat = d01v1_per.ce
				group by 1
			;

			-- Table des évènements salarié.
			DROP TABLE IF EXISTS w_evt
			;

			CREATE TEMP TABLE w_evt AS
				select
					w_lmt.mat,
					min(cal.date) as date_debut,
					max(cal.date) as date_fin,
					cal.mois,
					w_cnt.cnt,
					w_cnt.date_debut as cnt_date_debut,
					w_cnt.date_fin as cnt_date_fin,
					w_cnt_csp.csp_num,
					w_cnt_emp.emp_num,
					w_cnt_aff.aff_num,
					w_cnt_ttt.ttt_num,
					w_cnt_tho.tho_num,
					w_cnt_spe.spe_code,
					w_bul.bul,
					w_bul.date_debut as bul_date_debut,
					w_bul.date_fin as bul_date_fin,
					case when w_cnt is NULL then 1 else 0 end as est_hors_periode
				from base.p_calendrier as cal
					JOIN w_lmt on cal.date BETWEEN min_date and max_date
					left join w_cnt on 1=1
						and w_cnt.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt.date_debut and w_cnt.date_fin
					left join w_cnt_csp on 1=1
						and w_cnt_csp.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt_csp.date_debut and w_cnt_csp.date_fin
					left join w_cnt_emp on 1=1
						and w_cnt_emp.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt_emp.date_debut and w_cnt_emp.date_fin
					left join w_cnt_aff on 1=1
						and w_cnt_aff.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt_aff.date_debut and w_cnt_aff.date_fin
					left join w_cnt_ttt on 1=1
						and w_cnt_ttt.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt_ttt.date_debut and w_cnt_ttt.date_fin
					left join w_cnt_tho on 1=1
						and w_cnt_tho.mat = w_lmt.mat
						and cal.date BETWEEN w_cnt_tho.date_debut and w_cnt_tho.date_fin
					left join w_cnt_spe on w_cnt_spe.mat = w_lmt.mat -- relation 1 pour 1.
					left join w_bul on 1=1
						and w_bul.mat = w_lmt.mat
						and cal.date BETWEEN w_bul.date_debut and w_bul.date_fin
				WHERE 1=1
					AND to_char(cal.date, 'YYYY') >= 2009
					AND (1!=1
						OR w_cnt is not NULL
						OR w_cnt_csp is not null
						OR w_cnt_emp is not null
						OR w_cnt_aff is not null
						OR w_cnt_ttt is not null
						OR w_bul is not null)
				group by 1,4,5,6,7,8,9,10,11,12,13,14,15,16,17
			;

			-- Associer le dernier contrat aux bulletins hors période de contrat.
		/*	UPDATE w_evt
			SET cnt = subq.cnt,
				cnt_date_debut = subq.cnt_date_debut,
				cnt_date_fin = subq.cnt_date_fin
			FROM (
				select
					t1.mat,
					t1.date_debut,
					t1.bul_0,
					(max(ARRAY[t2.date_fin::text, t2.cnt::text]))[2] as cnt,
					max(t2.date_debut) AS cnt_date_debut,
					max(t2.date_fin) AS cnt_date_fin
				from w_evt AS t1
					left JOIN w_cnt AS t2 on 1=1
						and t2.mat = t1.mat
						and t2.date_fin < t1.date_debut
				and t1.cnt is null
				group by 1,2,3
				having (max(ARRAY[t2.date_fin::text, t2.cnt::text]))[2] is not null
				) AS subq
			WHERE 1=1
				AND w_evt.mat = subq.mat
				AND w_evt.date_debut = subq.date_debut
				AND w_evt.bul_0 = subq.bul_0
			;*/

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

			DROP TABLE IF EXISTS w_profils
			;

			CREATE TEMP TABLE w_profils AS
				SELECT
					0 AS profil_id, -- Identifiant CTI du profil CTI
					0 AS last_profil, -- Profil le + récent = 1, sinon à 0
					-- Cléfs naturelles permettant le matching du profil CTI au données prestataire.
					w_evt.mat,
					w_evt.cnt,
					w_evt.mois,
					w_evt.date_debut,
					w_evt.date_fin,
					w_evt.cnt_date_debut,
					w_evt.cnt_date_fin,
					w_evt.bul,
					w_evt.bul_date_debut,
					w_evt.bul_date_fin,
					w_evt.est_hors_periode,

					-- Données du Profil CTI
					coalesce(w_cnt_csp.csp_code, chr(1)||'*') AS categorie_socio_professionnelle_code_original,
					coalesce(w_cnt_emp.emp_code, chr(1)||'*') AS code_emploi_code_original,
					chr(1)||'*' as grille_code_original, -- Dans le cas où le coeff contrat n'est pas juste, utiliser celui issu des bulletins (x_mode à true).
					chr(1)||'*' AS grille_groupe_code_original,
					chr(1)||'*' AS groupe_cotisant_code_original,
					coalesce(w_cnt.motif_debut, chr(1)||'*') AS motif_debut_code_original,
					coalesce(w_cnt.motif_fin, chr(1)||'*') AS motif_fin_code_original,
					coalesce(w_cnt_emp.qua_code, chr(1)||'*') AS qualification_code_original,
					coalesce(w_cnt_aff.uf_code, chr(1)||'*') AS service_code_original,
					chr(1)||'*' AS societe_interim_code_original,
					coalesce(w_evt.spe_code, chr(1)||'*') AS specialite_code_original,
					coalesce(w_cnt_emp.sta_code, chr(1)||'*') AS statut_code_original,
					coalesce(w_cnt.type_contrat, chr(1)||'*') AS type_contrat_code_original,
					coalesce(w_cnt_tho.tho_code, chr(1)||'*') AS type_horaire_code_original,
					coalesce(w_cnt_ttt.ttt_code, chr(1)||'*') AS type_temps_travail_code_original,
					coalesce(w_cnt_aff.cec_code, chr(1)||'*') AS section_analytique_code_original,
					chr(1)||'*' AS section_analytique_paie_code_original,
					-- Champs dédiés au public.
					chr(1)||'*' AS unite_fonctionnelle_code_original,
					chr(1)||'*' AS categorie_conge_code_original,
					chr(1)||'*' AS compte_salarie_code_original,
					chr(1)||'*' AS commission_paritaire_code_original,
					chr(1)||'*' AS lettre_budgetaire_code_original,
					chr(1)||'*' AS cadre_emploi_code_original,
					chr(1)||'*' AS filiere_code_original,
					chr(1)||'*' AS categorie_statutaire_code_original
				FROM w_evt
					LEFT JOIN w_cnt ON w_cnt.cnt = w_evt.cnt
					LEFT join w_cnt_csp on w_cnt_csp.csp_num = w_evt.csp_num
					LEFT join w_cnt_emp on w_cnt_emp.emp_num = w_evt.emp_num
					LEFT join w_cnt_aff on w_cnt_aff.aff_num = w_evt.aff_num
					LEFT join w_cnt_ttt on w_cnt_ttt.ttt_num = w_evt.ttt_num
					LEFT join w_cnt_tho on w_cnt_tho.tho_num = w_evt.tho_num
				WHERE 1=1
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35--,36,37
			;

			-- Marquage du profil le plus récent pour chaque salarié
			UPDATE w_profils
			SET last_profil = 1
			FROM
				(
				SELECT
					mat,
					max(date_fin) AS date_fin,
					(max(ARRAY[date_fin::text, cnt::text]))[2] AS cnt
				FROM w_profils
				GROUP BY 1
				) AS subq
			WHERE 1=1
				AND w_profils.mat = subq.mat
				AND w_profils.date_fin = subq.date_fin
				AND w_profils.cnt = subq.cnt
			;

			]]></sqlcmd>
		</NODE>
		<NODE name="PROFIL" type="common" />
		<NODE label="Salariés">
			<sqlcmd><![CDATA[


			DROP TABLE IF EXISTS w_salaries
			;

			CREATE TEMP TABLE w_salaries AS
				select
					rhp('finess') AS finess,
					d01v1_pernom.c03 as prenom,
					d01v1_pernom.c02 as nom,
					d01v1_pernom.c04 as nom_naissance,
					d01v1_pernai.c01::date as date_naissance,
					case when d01v1_pernai.c09 = 'F' then 'F' else 'M' end as sexe,
					d01v1_pernom.cb as matricule,
					d01v1_pernom.cb as code,
					d01v1_pernom.cb as code_original,
					0 as entreprise_id,
					coalesce(t_nationalites.oid, 0) as nationalite_id,
					coalesce((max(ARRAY[extract(epoch from d01v1_perfam.cf), t_codes_postaux.oid]))[2], 0) as code_postal_id,
					coalesce((max(ARRAY[extract(epoch from d01v1_perfam.cf), t_situations_famille.oid]))[2], 0) as situation_famille_id,
					coalesce((max(ARRAY[extract(epoch from date_fin), profil_id]))[2], 0) as profil_id,
					max(cnt_date_debut) as date_debut,
					max(cnt_date_fin) as date_fin,
					min(cnt_date_debut) as date_entree_ets,
					max(cnt_date_fin) as date_sortie_ets,
					-- Champs dédiés au public.
					null::date AS date_entree_fp,
					null::date AS date_entree_fph,
					0 AS no_adeli,
					0 AS code_cotisation_id,
					0 AS matricule_retraite
				from prod_pleiades.d01v1_per
					left join prod_pleiades.d01v1_pernom on d01v1_pernom.cb = d01v1_per.ce
					left join prod_pleiades.d01v1_pernai on d01v1_pernai.cb = d01v1_per.ce
					left join prod_pleiades.d01v1_perfam on d01v1_perfam.cb = d01v1_per.ce
					left join rh.t_situations_famille on t_situations_famille.code_original = d01v1_perfam.c01
					left join rh.t_nationalites on t_nationalites.code_original = d01v1_pernai.c05
					left join prod_pleiades.d01v1_perad1 on d01v1_perad1.cb = d01v1_per.ce
					left join rh.t_codes_postaux ON t_codes_postaux.code = d01v1_perad1.c05
					left join w_profils on w_profils.mat = d01v1_pernom.cb
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11
			;

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

			TRUNCATE rh.p_contrats
			;

			ALTER SEQUENCE rh.s_contrats RESTART WITH 1
			;

			INSERT INTO rh.p_contrats (
				salarie_id,
				date_debut,
				date_fin,
				numero_contrat,
				code_original,
				etablissement_id,
				salarie_remplace_id,
				profil_id) -- dernier profil connu.
				SELECT
					p_salaries.oid AS salarie_id,
					w_cnt.date_debut,
					w_cnt.date_fin,
					w_cnt.cnt as numero_contrat,
					w_cnt.cnt AS code_original,
					0 AS etablissement_id,
					coalesce(rmp.oid, 0) as salarie_remplace_id,
                    coalesce((max(ARRAY[extract(epoch from w_profils.date_fin), w_profils.profil_id]))[2], 0) AS profil_id
				FROM w_cnt
					JOIN rh.p_salaries ON p_salaries.matricule = w_cnt.mat
					LEFT JOIN rh.p_salaries as rmp ON rmp.matricule = w_cnt.mat_remp
					LEFT JOIN w_profils ON w_profils.cnt = w_cnt.cnt
				GROUP BY 1,2,3,4,5,6,7
			;

			-- Calcul ancienneté.
			-- il nous faut absoluement 1 ligne = 1 contrat.
			/*DROP TABLE IF EXISTS w_cnt1
			;

			CREATE TEMP TABLE w_cnt1 AS
				SELECT
					mat,
					real_cnt,
					sum(duree) as duree,
					max(rang) as rang,
					bool_or(acc_anc) as acc_anc
				FROM w_cnt
				GROUP BY 1,2
			;

			UPDATE rh.p_contrats
			SET
				anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
				anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_calculee_mois
			FROM (
				SELECT
					t1.real_cnt,
					sum(t2.duree) AS anciennete_anterieure_jours,
					sum(t2.duree) / 30 AS anciennete_anterieure_calculee_mois
				FROM w_cnt1 AS t1
					JOIN w_cnt1 AS t2 ON 1=1
						AND t2.mat = t1.mat
						AND t2.rang < t1.rang
						AND t2.acc_anc -- on cumule de l'ancienneté uniquement lorsque le contrat dépasse la date d'ancienneté.
				group by 1
				) AS subq
			WHERE 1=1
				AND p_contrats.numero_contrat = subq.real_cnt
			;*/

			-- Ventilation des contrats par mois
			TRUNCATE rh.p_contrats_mois
			;

			ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
			;

			INSERT INTO rh.p_contrats_mois(
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				nombre_entrees,
				nombre_departs,
				nombre_debut_contrat,
				nombre_fin_contrat,
				est_hors_periode,
				present_debut_mois,
				present_fin_mois,
				equivalent_temps_plein,
				age_id,
				age_jours,
				anciennete_jours,
				anciennete_mois,
				anciennete_annee_id,
				profil_id
				)
				SELECT
					p_contrats.salarie_id AS salarie_id,
					p_contrats.oid AS contrat_id,
					w_profils.mois AS mois,
					w_profils.date_debut,
					w_profils.date_fin,
					CASE WHEN p_salaries.date_entree_ets BETWEEN w_profils.date_debut AND w_profils.date_fin THEN 1 ELSE 0 END AS nombre_entrees,
					CASE WHEN p_salaries.date_sortie_ets BETWEEN w_profils.date_debut AND w_profils.date_fin THEN 1 ELSE 0 END AS nombre_departs,
					CASE WHEN p_contrats.date_debut BETWEEN w_profils.date_debut AND w_profils.date_fin THEN 1 ELSE 0 END AS nombre_debut_contrat,
					CASE WHEN p_contrats.date_fin BETWEEN w_profils.date_debut AND w_profils.date_fin THEN 1 ELSE 0 END AS nombre_fin_contrat,
					est_hors_periode,
					CASE WHEN base.cti_first_day(w_profils.date_debut) BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_debut_mois,
					CASE WHEN base.cti_last_day(w_profils.date_fin) BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_fin_mois,
					0 AS equivalent_temps_plein,
					base.cti_age(LEAST(w_profils.date_fin, p_contrats.date_fin), COALESCE(p_salaries.date_naissance, '1962-04-18'::date), 'ny')  AS age_id,
					LEAST(w_profils.date_fin, p_contrats.date_fin)::date - COALESCE(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
					-- Ancienneté en jours
					p_contrats.anciennete_anterieure_jours
						+ (w_profils.date_fin - p_contrats.date_debut)
						+ 1 AS anciennete_jours,
					-- Ancienneté en mois
					GREATEST(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois)
					    + base.cti_age(date_trunc('month', w_profils.date_fin::date)::date, date_trunc('month', p_contrats.date_debut)::date, 'nm')
					    + 1 AS anciennete_mois,
					-- Ancienneté en années
					floor(
						(GREATEST(p_contrats.anciennete_anterieure_mois, p_contrats.anciennete_anterieure_calculee_mois) / 12)
						    + (base.cti_age(date_trunc('month',w_profils.date_fin::date)::date, date_trunc('month',p_contrats.date_debut)::date, 'nm') + 1) / 12
						 ) AS anciennete_annee_id,
					0
				FROM w_profils
					JOIN w_cnt ON w_cnt.cnt = w_profils.cnt
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_cnt.cnt
					JOIN rh.p_salaries ON p_contrats.salarie_id = p_salaries.oid
					JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
					--JOIN rh.t_entreprises ON t_etablissements.entreprise_id = t_entreprises.oid
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19
			;

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

			-- Création des tables listant les rubriques de brut, cot, ...
			DROP TABLE IF EXISTS w_rub_brut
			;
			CREATE TEMP TABLE w_rub_brut AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '001'
						and c02 != '0') -- on ne veut pas de ligne de paie lorsque la rubrique est inactive.
				select
					rub,
					signe,
					date as date_debut,
					coalesce(lead(date::date) over (partition by rub order by date) - 1, '20991231'::date) as date_fin
				from rub
				where rub != '0965' -- il ne faut pas remonter le complément de gratification qui n'est pas compté dans le brut (6001).
			;

			DROP TABLE IF EXISTS w_rub_cotsal
			;
			CREATE TEMP TABLE w_rub_cotsal AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '015'
						and c02 != '0')
				select
					rub,
					signe,
					date as date_debut,
					coalesce(lead(date::date) over (partition by rub order by date) - 1, '20991231'::date) as date_fin
				from rub
			;

			DROP TABLE IF EXISTS w_rub_cotpat
			;
			CREATE TEMP TABLE w_rub_cotpat AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '014'
						and c02 != '0'),
				rub_ts as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '225'
						and c02 != '0')
					select
						rub,
						signe,
						date as date_debut,
						coalesce(lead(date::date) over (partition by rub order by date) - 1, '20991231'::date) as date_fin
					from rub
					where true
						and rub != '8690' -- on veut le détail de la 8690 "Autres ch. patronales".
						and rub != '6829' -- La 6829 contient une erreur de paramétrage (oubli de pleiades). On la force sur toute la période à la suite de cette même requête. @todo corrigée depuis janvier 2016.
						and rub not in ('6790', '7208') -- on ne veut pas remonter ces charges patronales. @todo corrigée depuis janvier 2016.
				UNION
					select
						rub,
						signe,
						date as date_debut,
						coalesce(lead(date::date) over (partition by rub order by date) - 1, '20991231'::date) as date_fin
					from rub_ts
					where rub != '8569' -- on veut le détail de la 8569 "TOTAL Taxe sur les salaires".
				UNION
					select
						unnest(array['8562', '8565', '8567', '8568']) as rub, -- Détail de la taxe sur les salaires.
						1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
				UNION
					select
						'6829' as rub, -- 6829 "majoration allocations familiales" forcées sur toute la période car erreur de paramétrage dans pleiades. @todo corrigée depuis janvier 2016.
						1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
				UNION
					select
						'6795' as rub, -- 6795 ou 6780 "Allégement Fillon". @todo corrigée depuis janvier 2016
						1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
			;

			DROP TABLE IF EXISTS w_rub_netimpos
			;
			CREATE TEMP TABLE w_rub_netimpos AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '002'
						and c02 != '0')
					select
						rub.rub,
						rub.signe,
						rub.date as date_debut,
						coalesce(lead(rub.date::date) over (partition by rub.rub order by rub.date) - 1, '20991231'::date) as date_fin
					from rub
						left join w_rub_brut on w_rub_brut.rub = rub.rub
					where true
						and w_rub_brut.rub is null -- on sélectionne uniquement les rubriques pas déjà prises du brut.
						and rub.rub not in ('6000', '6001', '5613') -- on sort les rubriques de cumul du brut ainsi que la 5613 qui n'est pas imposable.
				UNION
					select
						rub,
						signe,
						date_debut,
						date_fin
					from w_rub_brut
					where rub != '5613'
			;

			DROP TABLE IF EXISTS w_rub_netpayer
			;
			CREATE TEMP TABLE w_rub_netpayer AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '003'
						and c02 != '0')
					select
						rub.rub,
						rub.signe,
						rub.date as date_debut,
						coalesce(lead(rub.date::date) over (partition by rub.rub order by rub.date) - 1, '20991231'::date) as date_fin
					from rub
						left join w_rub_brut on w_rub_brut.rub = rub.rub
					where true
						and w_rub_brut.rub is null -- on sélectionne uniquement les rubriques pas déjà prises du brut.
						and rub.rub not in ('6000', '6001') -- on sort les rubriques de cumul du brut.
				UNION
					select
						rub,
						signe,
						date_debut,
						date_fin
					from w_rub_brut
			;

			DROP TABLE IF EXISTS w_rub_heures
			;
			CREATE TEMP TABLE w_rub_heures AS
				with rub as (
					select
						cf::date as date,
						ce as rub,
						c01 = 'M' as montant, -- true = montant; false = base.
						case c02
							when '+' then 1
							when '-' then -1
							when '0' then 0
						end as signe,
						rank() over (partition by ce order by cf) as rang
					from prod_pleiades.d01v5_asstdp
					where true
						and cb = '210'
						and c02 != '0')
					select
						rub,
						montant,
						signe,
						date as date_debut,
						coalesce(lead(date::date) over (partition by rub order by date) - 1, '20991231'::date) as date_fin
					from rub
					where rub != '6033' -- il faut retirer "PLAFOND ETUDIANT INTERNE" pour être juste.
				UNION
					select
						'9953'::text as rub,
						true as montant,
						1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
				UNION
					select
						unnest(array[
						--	'4599',
						--	'4600',
							'4601',
						--	'4602',
						--	'4603',
							'4604',
							'4621',
							'4622',
							'4623',
							'4624',
							'4625',
							'4626'
							]) as rub,
						false as montant,
						-1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
				UNION
					select
						'5439' as rub,
						true as montant,
						-1 as signe,
						'19700101'::date as date_debut,
						'20991231'::date as date_fin
			;

			drop table if exists w_rub_h_2
			;
			create temp table w_rub_h_2 as 
				select
					null::text as rub,
					null::boolean as is_montant,
					null::int as signe
				limit 0
			;
			insert into w_rub_h_2 values
				('0300',true,'1'),
				('0301',true,'1'),
				('0340',true,'1'),
				('0341',true,'1'),
				('0859',true,'1'),
				('3047',true,'1'),
				('4674',false,'-1'),
				('4676',false,'-1'),
				('4678',false,'-1'),
				('4702',false,'-1'),
				('4704',false,'-1'),
				('4794',false,'-1'),
				('4796',false,'1'),
				('4800',false,'-1'),
				('4803',false,'1'),
				('5203',true,'1'),
				('5206',true,'1'),
				('5208',true,'-1'),
				('5217',true,'1'),
				('5218',true,'1'),
				('5415',false,'1'),
				('5416',false,'1'),
				('5417',false,'1'),
				('5418',false,'1'),
				('5419',false,'1'),
				('5425',false,'1'),
				('5426',false,'1'),
				('5427',false,'1'),
				('5434',false,'1'),
				('5436',false,'1'),
				('5439',true,'-1')
			;

			ALTER SEQUENCE rh.s_historique_paie RESTART WITH 1
			;

			DROP TABLE IF EXISTS w_historique_paie
			;

			CREATE TEMP TABLE w_historique_paie AS
				select
					w_hp.hp_ctid, -- permet d'être sûr qu'on n'agrège pas à tort des lignes de paie w_hp.
					date_part('year', age(w_bul.date_fin, date_naissance)) AS age_id,
					w_hp.mat||w_hp.mois||(case when to_char(w_hp.date_debut, 'YYYYMM')::numeric = w_hp.mois then substring(w_hp.sous_periode, 8, 2) else '01' end), -- numero fictif de bulletin. Rang 01 lorsque régulation.
					w_hp.mat,
					w_hp.mois::numeric as mois_paie,
					w_bul.date_debut,
					w_bul.date_fin,
					w_bul.date_fin as date_paie,
					substring(w_hp.sous_periode, 1, 6)::numeric as mois_activite,
					date_virement,
					t_rubriques.oid AS rubrique_id,
					p_salaries.oid AS salarie_id,
					w_hp.sous_periode,
					w_hp.date_debut as date_debut_ori,
					w_hp.date_fin as date_fin_ori,
					w_hp.rub,
					w_bul.bul,
					case
						when w_rub_h_2.rub is not null then 
							--(case when w_rub_heures.montant then w_hp.mt else w_hp.base end) * w_rub_heures.signe else w_hp.base end 
							case w_rub_h_2.is_montant
								when true then w_hp.mt * w_rub_h_2.signe
								when false then (case when w_hp.mt = 0 then 0 else w_hp.base end)
							end
						else w_hp.base
					end as base,
					case when w_rub_brut.rub is not null then w_hp.mt * w_rub_brut.signe else 0 end as montant_brut,
					case when w_rub_cotsal.rub is not null then w_hp.tx else 0 end as taux_cotisation_salarie,
					case when w_rub_cotsal.rub is not null then w_hp.mt * w_rub_cotsal.signe else 0 end as montant_cotisation_salarie,
					case when w_rub_cotpat.rub is not null then w_hp.tx else 0 end as taux_cotisation_patronale,
					case when w_rub_cotpat.rub is not null then w_hp.mt * w_rub_cotpat.signe else 0 end as montant_cotisation_patronale,
					0 as montant_avantage_nature,
					0 as montant_frais_imposables,
					case when w_rub_netpayer.rub is not null then w_hp.mt * w_rub_netpayer.signe else 0 end as montant_net_a_payer_salarie,
					case when w_rub_netimpos.rub is not null then w_hp.mt * w_rub_netimpos.signe else 0 end as montant_net_imposable_salarie,
					0 as montant_od_net_salarie,
					0 as organisme_cotisation_id,
					(max(array[extract(epoch from w_profils.date_debut), p_contrats.oid]))[2] AS contrat_id,
					(max(array[extract(epoch from w_profils.date_debut), p_contrats_mois.oid]))[2] AS contrat_mois_id,
					(max(array[extract(epoch from w_profils.date_debut), w_profils.profil_id]))[2] AS profil_id,
					nextval('rh.s_historique_paie'::regclass) as oid,
					coalesce(t_compte.oid, 0) as compte_id
				from w_hp
					JOIN w_bul on w_bul.bul = w_hp.mat||w_hp.mois||(case when to_char(w_hp.date_debut, 'YYYYMM')::numeric = w_hp.mois then substring(sous_periode, 8, 2) else '01' end)
					JOIN rh.t_rubriques ON t_rubriques.code_original = w_hp.rub
					JOIN rh.p_salaries ON p_salaries.code_original = w_bul.mat
					JOIN w_profils ON 1=1
						AND w_profils.bul = w_bul.bul
						AND w_profils.bul_date_debut = w_bul.date_debut
					left join w_rub_brut on true
						and w_rub_brut.rub = w_hp.rub
						and w_hp.date_fin between w_rub_brut.date_debut and w_rub_brut.date_fin
					left join w_rub_cotsal on true
						and w_rub_cotsal.rub = w_hp.rub
						and w_hp.date_fin between w_rub_cotsal.date_debut and w_rub_cotsal.date_fin
					left join w_rub_cotpat on true
						and w_rub_cotpat.rub = w_hp.rub
						and w_hp.date_fin between w_rub_cotpat.date_debut and w_rub_cotpat.date_fin
					left join w_rub_netimpos on true
						and w_rub_netimpos.rub = w_hp.rub
						and w_hp.date_fin between w_rub_netimpos.date_debut and w_rub_netimpos.date_fin
					left join w_rub_netpayer on true
						and w_rub_netpayer.rub = w_hp.rub
						and w_hp.date_fin between w_rub_netpayer.date_debut and w_rub_netpayer.date_fin
					left join w_rub_h_2 on true
						and w_rub_h_2.rub = w_hp.rub
						--and w_hp.date_fin between w_rub_heures.date_debut and w_rub_heures.date_fin
					left join w_compte on true
						and w_compte.matricule = w_hp.mat
						and w_compte.poste = w_hp.rub
						and w_compte.periode_imputation = w_hp.mois
						and w_compte.periode_origine||w_compte.sous_periode = substr(w_hp.sous_periode, 3, 4)||substr(w_hp.sous_periode, 8, 2)
					left join rh.t_compte on t_compte.code_original = w_compte.compte
					LEFT JOIN rh.p_contrats on p_contrats.numero_contrat = w_profils.cnt
					LEFT JOIN rh.p_contrats_mois on 1=1
						AND p_contrats_mois.contrat_id = p_contrats.oid
						AND p_contrats_mois.mois_activite = w_bul.mois
				where true
				group by 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,34,
					w_rub_h_2.rub, w_rub_h_2.is_montant, w_rub_brut.rub, w_rub_cotsal.rub, w_rub_cotpat.rub, w_rub_netpayer.rub, w_rub_netimpos.rub, w_hp.mt, w_hp.base
				HAVING 1!=1
					OR case when w_rub_h_2.rub is not null then 1 else 0 end != 0
					OR case when w_rub_brut.rub is not null then w_hp.mt else 0 end != 0
					OR case when w_rub_cotpat.rub is not null then w_hp.mt else 0 end != 0
					OR case when w_rub_cotsal.rub is not null then w_hp.mt else 0 end != 0
					OR case when w_rub_netpayer.rub is not null then w_hp.mt else 0 end != 0
					OR case when w_rub_netimpos.rub is not null then w_hp.mt else 0 end != 0
			;

			-- Associer les bulletins hors contrat (is null) avec le contrat précédent.
			UPDATE w_historique_paie
			SET contrat_id = subq.contrat_id,
				contrat_mois_id = subq.contrat_mois_id
			FROM (
				select
					w_historique_paie.oid,
					(max(array[extract(epoch from p_contrats_mois.date_fin), p_contrats_mois.contrat_id]))[2] as contrat_id,
					(max(array[extract(epoch from p_contrats_mois.date_fin), p_contrats_mois.oid]))[2] as contrat_mois_id
				from w_historique_paie
					join rh.p_contrats_mois on true
						and p_contrats_mois.salarie_id = w_historique_paie.salarie_id
						and p_contrats_mois.date_fin < w_historique_paie.date_debut
				where contrat_mois_id is null
				group by 1) as subq
			WHERE true
				AND w_historique_paie.oid = subq.oid
				AND w_historique_paie.contrat_mois_id is null
			;

			SELECT base.cti_stash_table_constraints('rh.p_historique_paie')
			;
			
			SELECT base.cti_stash_table_indexes('rh.p_historique_paie')
			;

			TRUNCATE rh.p_historique_paie
			;

			INSERT INTO rh.p_historique_paie (
				oid,
				age_id,
				base,
				contrat_id,
				contrat_mois_id,
				date_debut,
				date_fin,
				date_paie,
				mois_activite,
				mois_paie,
				montant_avantage_nature,
				montant_brut,
				montant_cotisation_patronale,
				montant_cotisation_salarie,
				montant_frais_imposables,
				montant_net_a_payer_salarie,
				montant_net_imposable_salarie,
				montant_od_net_salarie,
				organisme_cotisation_id,
				profil_id,
				rubrique_id,
				salarie_id,
				taux_cotisation_patronale,
				taux_cotisation_salarie,
				compte_id)
				SELECT
					oid,
					age_id,
					base,
					contrat_id,
					contrat_mois_id,
					date_debut,
					date_fin,
					date_paie,
					mois_activite,
					mois_paie,
					montant_avantage_nature,
					montant_brut,
					montant_cotisation_patronale,
					montant_cotisation_salarie,
					montant_frais_imposables,
					montant_net_a_payer_salarie,
					montant_net_imposable_salarie,
					montant_od_net_salarie,
					organisme_cotisation_id,
					profil_id,
					rubrique_id,
					salarie_id,
					taux_cotisation_patronale,
					taux_cotisation_salarie,
					compte_id
				FROM w_historique_paie
			;

			-- Inserer pour chaque bulletin une ligne qui va faire le compte avec le total
			INSERT INTO rh.p_historique_paie (
				age_id,
				base,
				contrat_id,
				contrat_mois_id,
				date_debut,
				date_fin,
				date_paie,
				mois_activite,
				mois_paie,
				montant_avantage_nature,
				montant_brut,
				montant_cotisation_patronale,
				montant_cotisation_salarie,
				montant_frais_imposables,
				montant_net_a_payer_salarie,
				montant_net_imposable_salarie,
				montant_od_net_salarie,
				organisme_cotisation_id,
				profil_id,
				rubrique_id,
				salarie_id,
				taux_cotisation_patronale,
				taux_cotisation_salarie,
				compte_id)
				SELECT
					age_id,
					0,
					contrat_id,
					contrat_mois_id,
					subq.date_debut,
					subq.date_fin,
					subq.date_paie,
					subq.mois_activite,
					subq.mois_paie,
					0,
					sum(chi.montant_brut - subq.montant_brut),
					0, -- sum(chi.montant_cotisation_patronale - subq.montant_cotisation_patronale), désactivé pour l'instant.
					sum(chi.montant_cotisation_salarie - subq.montant_cotisation_salarie),
					0,
					sum(chi.montant_net_a_payer_salarie - subq.montant_net_a_payer_salarie),
					sum(chi.montant_net_imposable_salarie - subq.montant_net_imposable_salarie),
					0,
					subq.organisme_cotisation_id,
					subq.profil_id,
					(SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
					subq.salarie_id,
					0,
					0,
					0
				FROM (
					SELECT
						hp.age_id,
						hp.contrat_id,
						hp.contrat_mois_id,
						hp.date_debut,
						hp.date_fin,
						hp.date_paie,
						hp.mois_paie as mois_activite, -- il ne faut pas mettre le mois d'activite sinon on a plusieurs lignes et la C000 est mal calculée.
						hp.mois_paie,
						sum(montant_brut) as montant_brut,
						sum(montant_cotisation_patronale) as montant_cotisation_patronale,
						sum(montant_cotisation_salarie) as montant_cotisation_salarie,
						sum(montant_net_a_payer_salarie) as montant_net_a_payer_salarie,
						sum(montant_net_imposable_salarie) as montant_net_imposable_salarie,
						hp.organisme_cotisation_id,
						hp.profil_id,
						(SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
						hp.salarie_id,
						hp.bul
					FROM w_historique_paie AS hp
						JOIN rh.p_salaries ON p_salaries.oid = hp.salarie_id
					GROUP BY 1,2,3,4,5,6,7,8, 14,15,16,17,18) as subq
					JOIN rh.p_salaries ON p_salaries.oid = subq.salarie_id
					JOIN w_chiffrier AS chi ON 1=1
						AND chi.mat = p_salaries.matricule
						AND chi.bul = subq.bul
						AND chi.date_debut = subq.date_debut
						AND chi.date_fin = subq.date_fin
				GROUP BY 1,2,3,4,5,6,7,8,9,10, 14, 17,18,19,20,21,22,23
				HAVING 1!=1
					OR sum(chi.montant_brut - subq.montant_brut) != 0
					-- OR sum(chi.montant_cotisation_patronale - subq.montant_cotisation_patronale) != 0 -- désactivé pour l'instant.
					OR sum(chi.montant_cotisation_salarie - subq.montant_cotisation_salarie) != 0
					OR sum(chi.montant_net_a_payer_salarie - subq.montant_net_a_payer_salarie) != 0
					OR sum(chi.montant_net_imposable_salarie - subq.montant_net_imposable_salarie) != 0
			;

			-- Le pop est fait plus tard.
			--SELECT base.cti_stash_pop_table_constraints('rh.p_historique_paie')
			--;
			
			--SELECT base.cti_stash_pop_table_indexes('rh.p_historique_paie')
			--;

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

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

			INSERT INTO rh.p_profil_contrat_mois (
				profil_id,
				contrat_mois_id,
				salarie_id,
				ratio,
				mois
				)
				SELECT
					coalesce(w_profils.profil_id, 0) AS profil_id,
					p_contrats_mois.oid AS contrat_mois_id,
					p_contrats_mois.salarie_id,
					1 AS ratio,
					p_contrats_mois.mois_activite
				FROM rh.p_contrats_mois
					JOIN rh.p_salaries ON p_salaries.oid = p_contrats_mois.salarie_id
					JOIN w_profils ON 1=1
						--AND w_profils.profil_id = p_contrats_mois.profil_id
						AND w_profils.mat = p_salaries.code_original
						AND w_profils.date_debut = p_contrats_mois.date_debut
						AND w_profils.date_fin = p_contrats_mois.date_fin
						--and base.cti_overlaps
				GROUP BY 1,2,3,4,5
			;

			-- Correction des ratios != 1.
			/*UPDATE rh.p_profil_contrat_mois
			SET ratio = subq1.nv_ratio
			FROM (
					SELECT
						p_profil_contrat_mois.profil_id,
						p_profil_contrat_mois.contrat_mois_id,
						p_profil_contrat_mois.ratio as anc_ratio,
						ratio / ratio_total as nv_ratio
					FROM rh.p_profil_contrat_mois
					JOIN (
						SELECT
							contrat_mois_id,
							sum(ratio) as ratio_total
						FROM rh.p_profil_contrat_mois
						GROUP BY 1
						HAVING sum(ratio) != 1
					) AS subq on subq.contrat_mois_id = p_profil_contrat_mois.contrat_mois_id
				) AS subq1
			WHERE 1=1
				AND p_profil_contrat_mois.profil_id = subq1.profil_id
				AND p_profil_contrat_mois.contrat_mois_id = subq1.contrat_mois_id
				AND p_profil_contrat_mois.ratio = subq1.anc_ratio
				AND p_profil_contrat_mois.mois < (SELECT max(mois) FROM w_bul) -- uniquement pour les mois clôturés.
			;

			-- Ajouter le restant pour faire 1 à une des rubriques ventilées (sacrés nombres inexacts).
			UPDATE rh.p_profil_contrat_mois
			SET ratio = subq1.nv_ratio
			FROM (
					SELECT
						contrat_mois_id,
						(max(ARRAY[profil_id, ratio]))[2] + 1 - sum(ratio) as nv_ratio,
						max(profil_id) as profil_id,
						(max(ARRAY[profil_id, ratio]))[2] as anc_ratio
					FROM rh.p_profil_contrat_mois
					GROUP BY 1
					HAVING sum(ratio) != 1
				) AS subq1
			WHERE 1=1
				AND p_profil_contrat_mois.profil_id = subq1.profil_id
				AND p_profil_contrat_mois.contrat_mois_id = subq1.contrat_mois_id
				AND p_profil_contrat_mois.ratio = subq1.anc_ratio
				AND p_profil_contrat_mois.mois < (SELECT max(mois) FROM w_bul) -- uniquement pour les mois clôturés.
			;*/

			-- @todo Calcul ETP théorique, Il faudra sans doute optimiser.
			/*DROP TABLE IF EXISTS maj_etp
			;
			CREATE TEMP TABLE maj_etp AS
				SELECT
					contrat_mois_id,
					(CASE
						WHEN type_temps_travail_id = 0 THEN 100 -- lorsque le TTT pas renseigné -> 100%
						WHEN type_temps_travail_code = 'TC' THEN 100 -- lorsque TC -> 100%
						WHEN base.cti_to_number(substr(type_temps_travail_code, 2)) = 0 THEN 1 -- lorsque TP à 0% -> 1%
						ELSE base.cti_to_number(substr(type_temps_travail_code, 2)) -- n%
					END)::numeric AS pct_temps_travail,
					(date_fin - date_debut + 1)::numeric AS duree,
					(CASE date_part('month', date_fin)
						WHEN 02 THEN CASE WHEN date_part('year', date_fin) IN (2000, 2004, 2008, 2012) THEN 29 ELSE 28 END
						WHEN 04 THEN 30
						WHEN 06 THEN 30
						WHEN 09 THEN 30
						WHEN 11 THEN 30
						ELSE 31
					END)::numeric AS duree_mois
				FROM rh.p_contrats_mois
					JOIN rh.p_profil_contrat_mois ON p_profil_contrat_mois.contrat_mois_id = p_contrats_mois.oid
					JOIN rh.p_profils ON p_profils.oid = p_profil_contrat_mois.profil_id
			;

			UPDATE rh.p_contrats_mois
			SET	equivalent_temps_plein = round((duree / duree_mois) * (pct_temps_travail / 100), 7)
			FROM maj_etp
			WHERE 1=1
				AND p_contrats_mois.oid = maj_etp.contrat_mois_id
				AND equivalent_temps_plein IS DISTINCT FROM round((duree / duree_mois) * (pct_temps_travail / 100), 7)
			;
*/
			]]></sqlcmd>
		</NODE>
		<NODE label="Ventilation Analytique">
			<sqlcmd><![CDATA[

			-- Liste exhaustive des rubriques pouvant faire l'objet d'une affectation forcée (fournie par M. Chastre).
			DROP TABLE IF EXISTS w_exc_rub
			;

			CREATE TEMP TABLE w_exc_rub AS
				SELECT unnest(ARRAY['5390', '5392', '5394', '5328', '5332', '5336', '5340', '5384', '5386', '5388', '5272', '5276', '5280', '5271', '5275', '5279']) as rub
			;

			-- Création de la table des ventilations corrigées.
			DROP TABLE IF EXISTS w_ven
			;

			CREATE TEMP TABLE w_ven AS
				with ven_0 as (
						select
							imputation,
							('20'||periode_imputation)::numeric as periode_imputation,
							matricule,
							poste,
							sum(@montant) as montant
						from prod_pleiades.a01_compta
						where ecriture = 'C'
						group by 1,2,3,4
						having sum(@montant) is not null),
					ven_1 as (
						select
							imputation,
							periode_imputation,
							matricule,
							poste,
							montant,
							round(base.cti_division(montant, sum(montant) over (partition by matricule, periode_imputation, poste)), 2) as ratio,
							row_number() over (partition by matricule, periode_imputation, poste order by montant desc) as rang
						from ven_0),
					ven_corr as (
						select
							matricule,
							periode_imputation,
							poste,
							1.0 - sum(ratio) as corr
						from ven_1
						group by 1,2,3
						having sum(ratio) != 1)
				select
					ven_1.periode_imputation,
					ven_1.matricule,
					ven_1.poste,
					array_agg(ven_1.imputation order by ven_1.imputation) as imp,
					array_agg(case when corr is not null and ven_1.rang = 1 then ven_1.ratio + ven_corr.corr else ven_1.ratio end order by ven_1.imputation) as rat,
					dense_rank() over (order by array_agg(ven_1.imputation order by ven_1.imputation), array_agg(case when corr is not null and ven_1.rang = 1 then ven_1.ratio + ven_corr.corr else ven_1.ratio end order by ven_1.imputation)) as ventilation_id
				from ven_1
					left join ven_corr on 1=1
						and ven_corr.matricule = ven_1.matricule
						and ven_corr.periode_imputation = ven_1.periode_imputation
						and ven_corr.poste = ven_1.poste
				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,
	    				array_to_string(imp, ',')||' @ '||array_to_string(rat, ','),
	    				1
	    			FROM w_ven
	    			group by 1,2,3,4
    			UNION ALL
    				SELECT
    					0,
    					'N/R',
    					'Non renseignée',
    					1
    		;

    		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,
	    				rat
	    			FROM (
		    			SELECT
		    				ventilation_id,
		    				unnest(imp) as imp,
		    				unnest(rat) as rat
		    			FROM w_ven
		    			group by 1,2,3) as subq
	    			JOIN rh.t_section_analytique on t_section_analytique.code_original = imp
	    		UNION ALL
	    			SELECT
	    				0,
	    				oid,
	    				code,
	    				texte,
	    				1
	    			FROM rh.t_section_analytique
	    			WHERE oid = 0
    		;

    		-- Alimentation du plan anlytique 1
    		--SELECT base.cti_stash_table_constraints('rh.p_historique_paie')
			--;
			
			--SELECT base.cti_stash_table_indexes('rh.p_historique_paie')
			--;

    		-- Ventilation standard (selon postes dans top_rub) pour toutes les rubriques à l'exception de w_exc_rub.
    		with top_rub as (
				select 1 as pref, '6585' as rub
				UNION select 2, '0301'
				UNION select 3, '9700'
				UNION select 4, '8565'
				UNION select 5, '8894')
    		UPDATE rh.p_historique_paie
    		SET ventilation_1_id = subq.ventilation_id
    		FROM (
    			select
    				p_historique_paie.oid,
    				coalesce((min(ARRAY[pref::int, w_ven.ventilation_id]))[2], (min(ARRAY[w_ven.poste::bigint, w_ven.ventilation_id]))[2]) as ventilation_id -- on privilégie la ventilation du poste avec min(pref) ou à défaut en prend le plus grand poste.
				from rh.p_historique_paie
					join rh.p_salaries on p_salaries.oid = p_historique_paie.salarie_id
					join rh.t_rubriques on t_rubriques.oid = p_historique_paie.rubrique_id
					join w_ven on 1=1
					 	and w_ven.matricule = p_salaries.matricule
					 	and w_ven.periode_imputation = p_historique_paie.mois_paie
					left join top_rub on top_rub.rub = w_ven.poste
				where 1=1
					--and poste in ('0301', '6585')
					and t_rubriques.code_original not in (select rub from w_exc_rub)
				group by 1) as subq
    		WHERE p_historique_paie.oid = subq.oid
    		;

    		-- Ventilation spécifique pour postes spécifique w_exc_rub faisant l'association avec le code rubrique.
    		-- Toutes les rubriques restantes non ventilées sont par défaut à 0 (définition de la colonne SQL).
    		UPDATE rh.p_historique_paie
    		SET ventilation_1_id = subq.ventilation_id
    		FROM (
    			select
    				w_historique_paie.oid,
    				w_ven.ventilation_id
				from w_historique_paie
					join w_ven on 1=1
					 	and w_ven.matricule = w_historique_paie.mat
					 	and w_ven.periode_imputation = w_historique_paie.mois_paie
					 	and w_ven.poste = w_historique_paie.rub
				where rub in (select rub from w_exc_rub)) as subq
    		WHERE 1=1
    			AND p_historique_paie.oid = subq.oid
    		;

    		-- Ventilation sur les UFs.
    		-- Pas actif car gros pbs de saisie. A voir avec Mme Crépet.
    		/*


			select
				dense_rank() over (order by imp, rat) as ventilation_id,
				imp,
				rat,
				total,
				mat,
				date_debut,
				date_fin
			from (
			 select
			 	mat,
			 	date_debut,
			 	coalesce(lead(date_debut) over (partition by mat order by date_debut) - 1, '20991231'::date) as date_fin,
			 	array_agg(imp order by imp) as imp,
			 	array_agg(rat order by imp) as rat,
			 	sum(rat) as total
			 from (
			 select
				cb as mat,
				--cb||'-'||(rank() over (partition by cb order by cf))::text as aff_num,
				cf::date as date_debut,
				--coalesce(lead(cf::date) over (partition by cb order by cf) - 1, '20991231'::date) as date_fin,
				trim(ce) as imp,
				c08 as rat
			from prod_pleiades.d01v1_peraff
			--where cb = '09362'
			) as subq
			group by 1,2) as subqq
			;

    		*/

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

			-- Nettoyage de la table a01_comtpa.
			delete from prod_pleiades.a01_compta
			where periode_imputation < 1512
			;

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

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

			CREATE TEMP TABLE w_arrets_0 AS
				-- Maladie.
					SELECT
						src.cb||'-'||src.ce||'-'||rank() over (partition by src.cb order by src.cf) as uid,
						to_char(src.cf, 'YYYYMM')::numeric AS mois,
						src.cf::date AS date_debut,
						src.c01::date AS date_fin,
						src.c03 AS nb_jours,
						coalesce(hrs.c01, 0) as nb_heures,
						src.ce AS motif,
						src.cb AS mat
					FROM prod_pleiades.d01v1_perama as src
						LEFT JOIN prod_pleiades.d01v1_perxml as hrs ON true
							and src.cb = hrs.cb
							and src.ce = hrs.ce
							and src.cf = hrs.cf
							--and src.cg = hrs.cg -- Ne pas utiliser cette condition.
					GROUP BY src.cf,2,3,4,5,6,7,8
				UNION
				-- Maternité/Paternité.
					SELECT
						src.cb||'-'||src.ce||'-'||rank() over (partition by src.cb order by src.cf) as uid,
						to_char(src.cf, 'YYYYMM')::numeric AS mois,
						src.cf::date AS date_debut,
						src.c01::date AS date_fin,
						src.c03 AS nb_jours,
						src.c06 as nb_heures,
						src.ce AS motif,
						src.cb AS mat
					FROM prod_pleiades.d01v1_permat as src
					GROUP BY src.cf,2,3,4,5,6,7,8
				UNION
				-- Accidents du travail.
					SELECT
						src.cb||'-'||src.ce||'-'||rank() over (partition by src.cb order by src.cf) as uid,
						to_char(src.cf, 'YYYYMM')::numeric AS mois,
						src.cf::date AS date_debut,
						src.c01::date AS date_fin,
						src.c03 AS nb_jours,
						src.c04 as nb_heures,
						src.ce AS motif,
						src.cb AS mat
					FROM prod_pleiades.d01v1_perxac as src
					GROUP BY src.cf,2,3,4,5,6,7,8
				UNION
				-- Congés rémunérés. (JOUR SOLIDARITE, CONGE DECES, CONGE MARIAGE, ENFANT MALADE, FORMATION COURTE).
					SELECT
						src.cb||'-'||src.ce||'-'||rank() over (partition by src.cb order by src.cf) as uid,
						to_char(src.cf, 'YYYYMM')::numeric AS mois,
						src.cf::date AS date_debut,
						src.c01::date AS date_fin,
						src.c03 AS nb_jours,
						src.c06 as nb_heures,
						src.ce AS motif,
						src.cb AS mat
					FROM prod_pleiades.d01v1_peraup as src
					GROUP BY src.cf,2,3,4,5,6,7,8
				UNION
				-- Congés non rémunérés.
					SELECT
						src.cb||'-'||src.ce||'-'||rank() over (partition by src.cb order by src.cf) as uid,
						to_char(src.cf, 'YYYYMM')::numeric AS mois,
						src.cf::date AS date_debut,
						src.c01::date AS date_fin,
						src.c03 AS nb_jours,
						src.c06 as nb_heures,
						src.ce AS motif,
						src.cb AS mat
					FROM prod_pleiades.d01v1_peranp as src
						LEFT JOIN prod_pleiades.d01v1_perxml as hrs ON true
							and src.cb = hrs.cb
							and src.ce = hrs.ce
							and src.cf = hrs.cf
					GROUP BY src.cf,2,3,4,5,6,7,8
			;

			DROP TABLE IF EXISTS w_arrets_mois -- version retravaillée (aggrégation des arrêts de même type continus sur un même mois).
			;

			CREATE TEMP TABLE w_arrets_mois AS
				with clustering as (
					select 
						*,
						case when lag(date_fin) over (partition by mat, motif order by date_debut) = date_debut - '1 day'::interval then null else true end as new_cluster
					from w_arrets_0
					order by mat, motif, date_debut),
				assigned_clustering as (
					select
						*,
						mat||'-'||count(new_cluster) over (order by mat, motif, date_debut) as cluster_id
					from clustering
				)
				select
					mat as matricule,
					motif,
					cluster_id,
					array_agg(uid) as uid, -- uid d'origine potentiellement dédoublé (inutilisable).
					mat||'-'||row_number() over (order by mois) as uid2, -- uid ventilé.
					min(date_debut) as date_debut,
					max(date_fin) as date_fin,
					mois as mois,
					sum(nb_jours) as nb_jours,
					sum(nb_heures) as nb_heures
				from assigned_clustering
				group by mat, motif, cluster_id, mois
			;

			DROP TABLE IF EXISTS w_arrets_mois_1 -- ventilation retravaillée + id de contrats.
			;

			CREATE TEMP TABLE w_arrets_mois_1 AS
				select
					w_arrets_mois.*,
					p_salaries.oid as salarie_id,
					p_contrats_mois.contrat_id,
					p_contrats_mois.oid as contrat_mois_id
				from w_arrets_mois
					join rh.p_salaries on p_salaries.matricule = w_arrets_mois.matricule
					join rh.p_contrats_mois on 1=1
						and p_contrats_mois.salarie_id = p_salaries.oid
						and base.cti_overlaps(p_contrats_mois.date_debut, p_contrats_mois.date_fin, w_arrets_mois.date_debut, w_arrets_mois.date_fin)
			;

			-- Agrégation des arrêts de travail.
			DROP TABLE IF EXISTS w_arrets
			;

			CREATE TEMP TABLE w_arrets AS
				select
					matricule,
					motif,
					cluster_id,
					matricule||'-'||motif||'-'||cluster_id as uid3, -- un uid3 par arrêt
					--array_agg(uid) as uid,
					array_agg(uid2) as uid2, -- plusieurs uid2 par uid3
					min(date_debut) as date_debut,
					max(date_fin) as date_fin,
					max(mois) as mois,
					sum(nb_jours) as nb_jours,
					sum(nb_heures) as nb_heures
				from w_arrets_mois
				group by matricule, motif, cluster_id
			;

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

			ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
			;

			DROP TABLE IF EXISTS w_arrets_travail
			;

			CREATE TEMP TABLE w_arrets_travail AS
				SELECT p_salaries.oid as salarie_id,
					   (max(ARRAY[extract(EPOCH from p_contrats.date_fin), p_contrats.oid]))[2] as contrat_id,
					   w_arrets.mois as mois_activite,
					   w_arrets.date_debut,
					   w_arrets.date_fin,
					   CASE WHEN w_arrets.date_fin = '2099-12-31'::date THEN '2099-12-31'::date ELSE (w_arrets.date_fin + INTERVAL '1 day')::date END AS date_reprise,
					   coalesce(t_motifs_arret.oid, 0) AS motif_arret_id,
					   0 AS precision_motif_arret_id,
					   w_arrets.nb_jours,
					   w_arrets.nb_heures,
					   w_arrets.cluster_id,
					   w_arrets.uid2,
					   w_arrets.uid3,
					   nextval('rh.s_arrets_travail'::regclass) as oid
				FROM w_arrets
					JOIN rh.p_salaries ON p_salaries.matricule = w_arrets.matricule
					LEFT JOIN rh.t_motifs_arret ON t_motifs_arret.code_original = w_arrets.motif
					JOIN rh.p_contrats ON 1=1 -- Ne pas s'inquièter si cetains arrets ne sont pas remontés faute d'association avec un contrat car il doit OBLIGRATOIREMENT avoir un contrat associé dans PLEIADES.
						and p_contrats.salarie_id = p_salaries.oid
						and base.cti_overlaps(p_contrats.date_debut, p_contrats.date_fin, w_arrets.date_debut, w_arrets.date_fin)
				GROUP BY 1,3,4,5,6,7,8,9,10,11,12,13
			;

			INSERT INTO rh.p_arrets_travail(
				oid,
				salarie_id,
				contrat_id,
				mois_activite,
				date_debut,
				date_fin,
				date_reprise,
				motif_arret_id,
				precision_motif_arret_id,
				nb_jours,
				nb_heures
				)
				select
					oid,
					salarie_id,
					contrat_id,
					mois_activite,
					date_debut,
					date_fin,
					date_reprise,
					motif_arret_id,
					precision_motif_arret_id,
					nb_jours,
					nb_heures
				from w_arrets_travail
			;

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

			INSERT INTO rh.p_arrets_travail_mois(
				arret_travail_id,
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				nb_debut_arret,
				nb_fin_arret,
				nb_reprise_apres_arret,
				date_debut,
				date_fin,
				nb_jours,
				nb_heures,
				nb_arret
				)
				SELECT
					subq.oid AS arret_travail_id,
					w_arrets_mois_1.salarie_id AS salarie_id,
					w_arrets_mois_1.contrat_id AS contrat_id,
					w_arrets_mois_1.contrat_mois_id AS contrat_mois_id,
					p_contrats_mois.mois_activite,
					CASE WHEN w_arrets_mois_1.date_debut BETWEEN min(p_contrats_mois.date_debut) AND max(p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nombre_debut_arret,
					CASE WHEN w_arrets_mois_1.date_fin BETWEEN min(p_contrats_mois.date_debut) AND max(p_contrats_mois.date_fin) THEN 1 ELSE 0 END AS nombre_fin_arret,
					0 AS nb_reprise_apres_arret,
					w_arrets_mois_1.date_debut,
					w_arrets_mois_1.date_fin,
					nb_jours,
					nb_heures,
					1
				FROM (select
						unnest(uid2) as uid2,
						salarie_id,
						contrat_id,
						cluster_id,
						oid
					from w_arrets_travail) as subq
					join w_arrets_mois_1 on w_arrets_mois_1.uid2 = subq.uid2
					join rh.p_contrats_mois on p_contrats_mois.oid = w_arrets_mois_1.contrat_mois_id
				group by 1,2,3,4,5,8,9,10,11,12,13,w_arrets_mois_1.date_debut,w_arrets_mois_1.date_fin
			;

			-- Calcul de l'indicateur 'nb reprise après arrêt'.
			update rh.p_arrets_travail_mois
			set nb_reprise_apres_arret = subq.nb_reprise_apres_arret
			from (
				select
					t1.arret_travail_id,
					t1.mois_activite,
					min(case when p_arrets_travail.date_reprise between t2.date_debut and t2.date_fin then 0 else 1 end) as nb_reprise_apres_arret
				from rh.p_arrets_travail_mois as t1
					join rh.p_arrets_travail ON p_arrets_travail.oid = t1.arret_travail_id
					left join rh.p_arrets_travail_mois as t2 ON 1=1
						AND t1.salarie_id = t2.salarie_id
						AND t1.date_debut != t2.date_debut
						AND t1.date_fin != t2.date_fin
				GROUP BY t1.arret_travail_id, t1.mois_activite
				order by 2 desc
				) as subq
			where 1=1
				and p_arrets_travail_mois.arret_travail_id = subq.arret_travail_id
				and p_arrets_travail_mois.mois_activite = subq.mois_activite
			;

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

				-- select *  from prod_pleiades.d01v1_permed;
			-- Création d'une table temporaire
			DROP TABLE IF EXISTS w_visites
			;
			CREATE TEMP TABLE w_visites AS
				SELECT
					cb as mat,
					ce as motif,
					to_char(cf, 'YYYYMM')::numeric AS mois_activite,
					cf::date as date,
					max(cnt) as cnt
				FROM prod_pleiades.d01v1_permed
					LEFT JOIN w_cnt ON true
						AND mat = cb
						AND cf between date_debut AND date_fin
				WHERE 1=1
					--AND cf >= '2008-01-01'
				GROUP BY 1,2,3,4
			;

			-- Associer les visites hors contrat au plus récent existant précédemment (en amont) ...
			UPDATE w_visites
			SET cnt = subq.cnt
			FROM (
				select
					w_visites.mat,
					w_visites.date,
					(max(array[w_cnt.date_fin::text, w_cnt.cnt]))[2] as cnt
				from w_visites
					JOIN w_cnt ON true
							AND w_cnt.mat = w_visites.mat
							and w_cnt.date_fin < w_visites.date
				where w_visites.cnt is null
				group by 1,2
				) as subq
			WHERE true
				AND w_visites.mat = subq.mat
				AND w_visites.date = subq.date
			;

			-- ... Puis en aval.
			UPDATE w_visites
			SET cnt = subq.cnt
			FROM (
				select
					w_visites.mat,
					w_visites.date,
					(min(array[w_cnt.date_debut::text, w_cnt.cnt]))[2] as cnt
				from w_visites
					JOIN w_cnt ON true
							AND w_cnt.mat = w_visites.mat
							and w_visites.date < w_cnt.date_debut
				where w_visites.cnt is null
				group by 1,2
				) as subq
			WHERE true
				AND w_visites.mat = subq.mat
				AND w_visites.date = subq.date
			;

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

			ALTER SEQUENCE rh.s_visites_medicales RESTART WITH 1
			;

			INSERT INTO rh.p_visites_medicales(
				salarie_id,
				contrat_id,
				contrat_mois_id,
				mois_activite,
				date,
				motif_visite_id)
				SELECT p_salaries.oid,
					   p_contrats.oid,
					   p_contrats_mois.oid,
					   w_visites.mois_activite,
					   w_visites.date,
					   t_motifs_visite.oid
				FROM w_visites
					JOIN rh.p_salaries ON p_salaries.matricule = w_visites.mat
					JOIN rh.p_contrats ON p_contrats.numero_contrat = w_visites.cnt
					JOIN rh.p_contrats_mois ON true
						AND p_contrats_mois.contrat_id = p_contrats.oid
						AND	w_visites.date between p_contrats_mois.date_debut AND p_contrats_mois.date_fin
					JOIN rh.t_motifs_visite ON t_motifs_visite.code_original = w_visites.motif
			;

			]]></sqlcmd>
		</NODE>
		<NODE label="Mise à jour des libellés et classes (FICOM et Codes emploi comptables)">
			<sqlcmd><![CDATA[

			-- Chargement des données CSV CEC.
			drop table if EXISTS w_cec
			;

			create temp table w_cec as 
			select
				''::text as code,
				''::text as texte
			limit 0
			;

			copy w_cec from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/codes_emploi_comptables.csv' CSV delimiter '|'
			;

			-- Chargement des données CSV FICOM.
			drop table if EXISTS w_ficom
			;

			create temp table w_ficom as 
				select
					''::text as cdr_code,
					''::text as cdr_texte,
					''::text as spe_code,
					''::text as spe_texte,
					''::text as ssp_code,
					''::text as ssp_texte,
					''::text as uf_code,
					''::text as uf_texte
				limit 0
			;

			copy w_ficom from 'D:/CTI/iCTI_377/modules/rh/sjsl-data/ficom.csv' CSV delimiter ';'
			;

			-- Màj des libellés d'UF principales.
			update rh.t_services 
			set texte = w_ficom.uf_texte,
				texte_court = substr(w_ficom.uf_texte, 1, 50)
			from w_ficom
			where w_ficom.uf_code = code_original
			;

			-- Màj des libellés de CEC principaux.
			update rh.t_sections_analytiques 
			set texte = w_cec.texte,
				texte_court = substr(w_cec.texte, 1, 50)
			from w_cec
			where w_cec.code = code_original
			;

			-- Suppression des 5 classes si elles existent.
			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 ('ANAUFS', 'ANACDR', 'ANASPE', 'ANASSP', 'ANACEC'))
			;

			delete from rh.t_classes_sections
			where classe_id in (
				select c.oid from rh.t_classes as c
				where c.code IN ('ANAUFS', 'ANACDR', 'ANASPE', 'ANASSP', 'ANACEC'))
			;

			delete from rh.t_classes
			where code IN ('ANAUFS', 'ANACDR', 'ANASPE', 'ANASSP', 'ANACEC')
			;

			-- Création des classes.
			insert into rh.t_classes (code, texte, table_id, is_cti, sequence)
				with classe_table as (
					select 'ANAUFS' as code, 'UF (ventilées)' as texte, 1 as sequence
				UNION ALL
					select 'ANACDR', 'CDR (ventilés)', 2
				UNION ALL
					select 'ANASPE', 'Spécialités (ventilées)', 3
				UNION ALL
					select 'ANASSP', 'Sous-spécialités (ventilées)', 4
				UNION ALL
					select 'ANACEC', 'Codes emploi comptables (ventilés)', 5)
				SELECT code, texte, table_id, 0, sequence
				FROM classe_table, (select oid as table_id from rh.t_listes_tables where code = 'ANA' LIMIT 1) as subq
			;

			-- Alimentation des classes.
			-- Classe d'UF (liée aux ventilations).
			INSERT INTO rh.t_classes_sections(code, texte, classe_id)
			    select
			    	substr(section_analytique_code, 1, 4),
			    	coalesce(w_ficom.uf_texte, substr(section_analytique_code, 1, 4)),
			    	(select oid from rh.t_classes where code = 'ANAUFS')
			    from rh.p_ventilation_section
			    	LEFT JOIN w_ficom on w_ficom.uf_code = substr(section_analytique_code, 1, 4)
			    where ventilation_id != 0
			    group by 1,2,3
			;

			INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
				SELECT
					t_classes_sections.oid AS section_id,
					section_analytique_id AS to_id
				FROM rh.t_classes
					join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
					join rh.p_ventilation_section on substr(p_ventilation_section.section_analytique_code, 1, 4) = t_classes_sections.code
				WHERE t_classes.code = 'ANAUFS'
				group by 1,2
			;

			-- Classe CDR (tiré uniquement du FICOM).
			INSERT INTO rh.t_classes_sections(code, texte, classe_id)
			    select
			    	cdr_code,
			    	cdr_texte,
			    	(select oid from rh.t_classes where code = 'ANACDR')
			    from w_ficom
			    group by 1,2,3
			;

			INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
				SELECT
					t_classes_sections.oid AS section_id,
					section_analytique_id AS to_id
				FROM rh.t_classes
					join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
					join w_ficom on w_ficom.cdr_code = t_classes_sections.code
					join rh.p_ventilation_section on substr(p_ventilation_section.section_analytique_code, 1, 4) = w_ficom.uf_code
				WHERE t_classes.code = 'ANACDR'
				group by 1,2
			;

			-- Classe Spé
			INSERT INTO rh.t_classes_sections(code, texte, classe_id)
			    select
			    	spe_code,
			    	spe_texte,
			    	(select oid from rh.t_classes where code = 'ANASPE')
			    from w_ficom
			    group by 1,2,3
			;

			INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
				SELECT
					t_classes_sections.oid AS section_id,
					section_analytique_id AS to_id
				FROM rh.t_classes
					join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
					join w_ficom on w_ficom.spe_code = t_classes_sections.code
					join rh.p_ventilation_section on substr(p_ventilation_section.section_analytique_code, 1, 4) = w_ficom.uf_code
				WHERE t_classes.code = 'ANASPE'
				group by 1,2
			;

			-- Classe Sous-Spé
			INSERT INTO rh.t_classes_sections(code, texte, classe_id)
			    select
			    	ssp_code,
			    	ssp_texte,
			    	(select oid from rh.t_classes where code = 'ANASSP')
			    from w_ficom
			    group by 1,2,3
			;

			INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
				SELECT
					t_classes_sections.oid AS section_id,
					section_analytique_id AS to_id
				FROM rh.t_classes
					join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
					join w_ficom on w_ficom.ssp_code = t_classes_sections.code
					join rh.p_ventilation_section on substr(p_ventilation_section.section_analytique_code, 1, 4) = w_ficom.uf_code
				WHERE t_classes.code = 'ANASSP'
				group by 1,2
			;

			-- Classe de CEC.
			INSERT INTO rh.t_classes_sections(code, texte, classe_id)
			    select
			    	substr(section_analytique_code, 7, 4),
			    	coalesce(w_cec.texte, substr(section_analytique_code, 7, 4)),
			    	(select oid from rh.t_classes where code = 'ANACEC')
			    from rh.p_ventilation_section
			    	LEFT JOIN w_cec on w_cec.code = substr(section_analytique_code, 7, 4)
			    where ventilation_id != 0
			    group by 1,2,3
			;

			INSERT INTO rh.t_classes_sections_elements (section_id, to_id)
				SELECT
					t_classes_sections.oid AS section_id,
					section_analytique_id AS to_id
				FROM rh.t_classes
					join rh.t_classes_sections on t_classes_sections.classe_id = t_classes.oid
					join rh.p_ventilation_section on substr(p_ventilation_section.section_analytique_code, 7, 4) = t_classes_sections.code
				WHERE t_classes.code = 'ANACEC'
				group by 1,2
			;

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

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

			/*INSERT INTO rh.t_divers(
				code,
  				texte,
  				valeur,
  				valeur_date,
  				description)
			VALUES(
				'MOIS_EN_COURS',
				'Mois en cours (non clôturé).',
				(SELECT max(mois) FROM w_bul),
				(SELECT (max(mois)||'01')::date FROM w_bul),
				'Mois en cours (non clôturé).'
				)
			;*/

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