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

            -- Màj des Entreprises
            INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court)
                SELECT
                    niv_cod1,
                    niv_cod1,
                    niv_lib1,
                    substr(niv_lib1, 1, 50)
                FROM prod_octime.niveau1
                WHERE 1=1
                    AND niv_cod1 = '01'
                    AND niv_cod1 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
                    niv_cod1,
                    niv_cod1,
                    niv_lib1,
                    substr(niv_lib1, 1, 50),
                    t_entreprises.oid
                FROM prod_octime.niveau1
                    JOIN rh.t_entreprises ON t_entreprises.code_original = niv_cod1
                WHERE 1=1
                    AND niv_cod1 = '01'
                    AND niv_cod1 NOT IN (SELECT code_original FROM rh.t_etablissements)
            ;

            -- 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 cont_cod NOT IN (SELECT code_original FROM rh.t_types_contrat)
            ;

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

            TRUNCATE rh.p_chiffrier_production
            ;

            INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
                SELECT
                    t_etablissements.entreprise_id,
                    t_etablissements.oid,
                    to_char(cal_dat, 'YYYYMM')::numeric,
                    count(distinct pers_mat),
                    0,
                    0
                FROM prod_octime.cptres1
                    JOIN rh.t_etablissements ON t_etablissements.code_original = cptres1.niv_cod1
                WHERE 1=1
                    AND niv_cod1 = '01'
                    AND cal_dat >= '2014-01-01'::date
                GROUP BY 1,2,3
            ;

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

            -- Identification des salariés présents dans un établissement.
            DROP TABLE IF EXISTS w_sal_ets
            ;

            CREATE TEMP TABLE w_sal_ets AS
                select
                    pers.pers_mat as pers_mat,
                    coalesce(nullif(pers.pers_matp, ''), pers.pers_mat) as code_original_w,
                    min(cal_dat) as date_debut,
                    max(cal_dat) as date_fin
                from prod_octime.cptres1
                    join prod_octime.pers on pers.pers_mat = cptres1.pers_mat
                where niv_cod1 = '01'
                group by 1,2
            ;

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

            DROP TABLE IF EXISTS w_profils
            ;

            CREATE TEMP TABLE w_profils AS
                select
                    0 as profil_id,
                    w_sal_ets.pers_mat,
                    w_sal_ets.code_original_w as code_original,
                    w_sal_ets.code_original_w||to_char(contprev.cont_datd, 'YYYYMMDD') as cnt_code_ori,
                    p_calendrier.mois,
                    min(p_calendrier.date) as date_debut,
                    max(p_calendrier.date) as date_fin,
                    (max(p_calendrier.date) - min(p_calendrier.date) + 1) -- nb jours
                        / (base.cti_last_day((p_calendrier.mois||'01')::date) - base.cti_first_day((p_calendrier.mois||'01')::date) + 1) -- divisé par nb jours total du mois
                        * cont_etp::numeric / 10000::numeric as etp, -- multiplié par l'ETP du contrat.
                    0 as est_hors_periode,
                    -- Données du Profil CTI
                    chr(1)||'*' AS categorie_socio_professionnelle_code_original,
                    chr(1)||'*' AS code_emploi_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 motif_debut_code_original,
                    chr(1)||'*' AS motif_fin_code_original,
                    chr(1)||'*' AS qualification_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,
                    coalesce(contprev.cont_cod, chr(1)||'*') AS type_contrat_code_original,
                    chr(1)||'*' AS type_horaire_code_original,
                    chr(1)||'*' AS type_temps_travail_code_original,
                    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 base.p_calendrier
                    join w_sal_ets on p_calendrier.date between w_sal_ets.date_debut and w_sal_ets.date_fin
                    join prod_octime.contprev on 1=1
                        and contprev.pers_mat = w_sal_ets.pers_mat
                        and p_calendrier.date between contprev.cont_datd and contprev.cont_datf
                group by 1,2,3,4,5, 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, cont_etp
            ;

            ]]></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
                    0 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,
                    coalesce(nullif(pers_matp, ''), pers.pers_mat) as code,
                    coalesce(nullif(pers_matp, ''), pers.pers_mat) as code_original,
                    coalesce(nullif(pers_matp, ''), pers.pers_mat) as matricule,
                    t_etablissements.entreprise_id,
                    0 AS nationalite_id,
                    coalesce(t_codes_postaux.oid, 0) AS code_postal_id,
                    0 AS situation_famille_id,
                    coalesce((max(array[extract(epoch from date_debut), w_profils.profil_id]))[2], 0::bigint) 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
                from prod_octime.pers
                join w_profils on w_profils.pers_mat = pers.pers_mat
                    LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = pers.pers_cp
                    LEFT JOIN rh.t_etablissements ON t_etablissements.code_original = '01'
                    GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,  17,18,19,20,21,22,23,24,25
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE name="SALARIE" type="common" />
        <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[

            TRUNCATE rh.p_contrats
            ;

            ALTER SEQUENCE rh.s_contrats RESTART WITH 1
            ;

            INSERT INTO rh.p_contrats(
                    salarie_id,
                    date_debut,
                    date_fin,
                    numero_contrat,
                    code_original,
                    etablissement_id,
                    profil_id)
                SELECT
                    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, 'O') AS numero_contrat,
                    w_salaries.matricule||to_char(contprev.cont_datd, 'YYYYMMDD') AS code_original,
                    t_etablissements.oid AS etablissement_id,
                    coalesce((max(array[extract(epoch from w_profils.date_debut), w_profils.profil_id]))[2], 0::bigint) AS profil_id
                FROM prod_octime.contprev
                    join w_salaries on w_salaries.pers_mat = contprev.pers_mat
                    join w_profils on w_profils.pers_mat = contprev.pers_mat
                    JOIN rh.t_etablissements ON t_etablissements.code_original = '01'
                GROUP BY 1,2,3,  5,6, w_salaries.matricule, contprev.cont_datd
                window w as (PARTITION BY w_salaries.salarie_id ORDER BY cont_datd)
            ;

            -- Màj de l'ancienneté.
            UPDATE rh.p_contrats SET
                anciennete_anterieure_jours = subq.anciennete_anterieure_jours,
                anciennete_anterieure_calculee_mois = subq.anciennete_anterieure_calculee_mois
            FROM (
                select
                    numero_contrat,
                    coalesce(sum(date_fin - date_debut + 1) over w, 0) AS anciennete_anterieure_jours,
                    coalesce(sum(date_fin - date_debut + 1) over w / 30::numeric, 0) AS anciennete_anterieure_calculee_mois
                from rh.p_contrats
                window w as (partition by salarie_id order by date_debut rows between UNBOUNDED PRECEDING and 1 preceding)) AS subq
            WHERE 1=1
                AND p_contrats.numero_contrat = subq.numero_contrat
            ;

            SELECT base.cti_stash_table_indexes('rh.p_contrats_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,
                nombre_heures,
                age_id,
                age_jours,
                anciennete_jours,
                anciennete_mois,
                anciennete_annee_id,
                etablissement_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,
                    etp AS equivalent_temps_plein,
                    etp * t_etablissements.base_calcul_etp as nombre_heures,
                    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,
                    p_contrats.etablissement_id,
                    w_profils.profil_id
                FROM w_profils
                    JOIN rh.p_contrats ON p_contrats.code_original = w_profils.cnt_code_ori
                    JOIN rh.p_salaries ON p_contrats.salarie_id = p_salaries.oid
                    JOIN rh.t_etablissements ON p_contrats.etablissement_id = t_etablissements.oid
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
            ;

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

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

            ]]></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.code_original = p_salaries.code_original
                        AND w_profils.date_debut = p_contrats_mois.date_debut
                        AND w_profils.date_fin = p_contrats_mois.date_fin
                GROUP BY 1,2,3,4,5
            ;

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

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

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

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

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

            ]]></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 to_char(date_paie_encours, 'YYYYMM') FROM w_periode),
            --     (SELECT date_paie_encours FROM w_periode),
            --     '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>
