<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
    <NODE name="INIT" label="INITIALISATIONS">
        <NODE label="Pre-traitements des tables prestataire">
            <sqlcmd><![CDATA[

            DROP TABLE IF EXISTS w_bul
            ;

            CREATE TEMP TABLE w_bul AS
                select
                    cdmato as mat,
                    dtpero as mois,
                    dtdppo::text::date as date_debut,
                    dtfppo::text::date as date_fin,
                    nojobo,
                    norjpo
                from prod_talentia_rh.iptw2fghm_rsaldi
                group by 1,2,3,4,5,6
            ;

            DROP TABLE IF EXISTS w_caisses
            ;

            CREATE TEMP TABLE w_caisses AS
                with type_caisse as (
                        select ltrim(noenrg, '0') as code, ponpag as texte
                        from prod_talentia_rh.iptw2fghm_paramg
                        where cdenrg = 'NC'
                        group by 1,2),
                    code_caisse as (
                        select ltrim(noenrg, '0') as code, ponpag as texte
                        from prod_talentia_rh.iptw2fghm_paramg
                        where cdenrg = 'SC'
                        group by 1,2)
                select
                    cdrubk as rub,
                    coalesce(type_caisse.code, '')||'|'||coalesce(code_caisse.code, '') as code_ori,
                    coalesce(type_caisse.code, '')||case when code_caisse.code is null then '' else '-' end||coalesce(code_caisse.code, '') as code,
                    coalesce(type_caisse.texte, '')||case when code_caisse.code is null then '' else ' - ' end||coalesce(code_caisse.texte, '') as texte
                from prod_talentia_rh.iptw2fghm_rubrik
                    left join type_caisse on type_caisse.code = iptw2fghm_rubrik.cdncak
                    left join code_caisse on code_caisse.code = iptw2fghm_rubrik.cdcaik
                where cdncak != '' or cdcaik != ''
                group by 1,2,3,4
            ;

            ]]></sqlcmd>
        </NODE>
        <NODE name="INIT" type="common" />
        <NODE label="Mise à jour des informations permanentes">
            <sqlcmd><![CDATA[
            
            -- Màj des codes postaux.
            INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id, departement_code, departement_texte)
                select cpsala, max(libura), substr(max(libura), 1, 50), t_departements.oid, t_departements.code, t_departements.texte
                from prod_talentia_rh.iptw2fghm_coadrd
                    JOIN base.t_departements ON t_departements.code = substr(cpsala, 1, 2)
                where true
                    and trim(cpsala) != ''
                    and cpsala not in (SELECT code FROM base.t_codes_postaux)
                group by 1, 4,5,6
            ;

            -- Màj des Entreprises
            INSERT INTO rh.t_entreprises(code_original, code, texte, texte_court)
                select cdsocp, cdsocp, listep, substr(listep, 1, 50)
                from prod_talentia_rh.iptw2fghm_strucp
                where 1=1
                    AND cdetsp = '000'
                    AND cdsocp NOT IN (SELECT code_original FROM rh.t_entreprises)
                GROUP BY 1,2,3,4
            ;
            
            -- Màj des Etablissements
            INSERT INTO rh.t_etablissements(code_original, code, texte, texte_court, entreprise_id)
                select cdetsp, cdetsp, listep, substr(listep, 1, 50), t_entreprises.oid
                from prod_talentia_rh.iptw2fghm_strucp
                    JOIN rh.t_entreprises ON t_entreprises.code_original = iptw2fghm_strucp.cdsocp
                where 1=1
                    AND cddepp = '000'
                    AND cdetsp != '000'
                    AND cdetsp NOT IN (SELECT code_original FROM rh.t_etablissements)
                GROUP BY 1,2,3,4,5
            ;
            
            -- Màj des catégories socio-professionnelles.
            INSERT INTO rh.t_categories_socio_professionnelle(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'EM'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_categories_socio_professionnelle)
                group by 1,2,3,4
            ;

            -- [NON] Màj des groupes cotisants.

            -- Màj des motifs de début de contrat.
            INSERT INTO rh.t_motifs_debut_contrat(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'ME'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_motifs_debut_contrat)
                group by 1,2,3,4
            ;

            -- Màj des motifs de fin de contrat
            INSERT INTO rh.t_motifs_fin_contrat(code_original, code, texte, texte_court)
            select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'MD'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_motifs_fin_contrat)
                group by 1,2,3,4
            ;
            
            -- Màj des nationalités
            INSERT INTO rh.t_nationalites(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'PA'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_nationalites)
                group by 1,2,3,4
            ;
            
            -- Màj des organismes de cotisation.
            INSERT INTO rh.t_organismes_cotisation(code_original, code, texte, texte_court)
                SELECT code_ori, code, texte, substr(texte,1,50)
                FROM w_caisses
                WHERE code_ori NOT IN (SELECT code_original FROM rh.t_organismes_cotisation)
                GROUP BY 1,2,3,4
            ;
            
            -- Màj des qualifications.
            INSERT INTO rh.t_qualifications(code_original, code, texte, texte_court)
                SELECT cdepli, cdepli, liepli, substr(liepli, 1, 50)
                FROM prod_talentia_rh.iptw2fghm_emploi
                WHERE cdepli NOT IN (SELECT code_original FROM rh.t_qualifications)
                GROUP BY 1,2,3,4
            ;
            
            -- Màj des rubriques.
            INSERT INTO rh.t_rubriques(code_original, code, texte, texte_court, rang_edition)
                SELECT 
                    cdrubk,
                    cdrubk,
                    lirubk,
                    substr(lirubk, 1, 50),
                    nsequk
                FROM prod_talentia_rh.iptw2fghm_rubrik
                WHERE cdrubk NOT IN (SELECT code_original FROM rh.t_rubriques)
            ;

            -- Màj des situations de famille (non profil)
            INSERT INTO rh.t_situations_famille(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'SF'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_situations_famille)
                group by 1,2,3,4
            ;
    
            -- Màj des types de contrat -- iptw2fghm_atcpa1
            INSERT INTO rh.t_types_contrat(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'CO'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_types_contrat)
                group by 1,2,3,4
            ;
            
            -- Màj des statuts
            INSERT INTO rh.t_statuts(code_original, code, texte, texte_court)
                select ltrim(noenrg, '0'), ltrim(noenrg, '0'), trim(ponpag), substr(trim(ponpag), 1, 50)
                from prod_talentia_rh.iptw2fghm_paramg
                where 1=1
                    and cdenrg = 'ST'
                    and ltrim(noenrg, '0') NOT IN (SELECT code_original FROM rh.t_statuts)
                group by 1,2,3,4
            ;

            -- Màj des types de temps de travail
            INSERT INTO rh.t_types_temps_travail(code_original, code, texte, texte_court)
                select
                    case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'TP' else 'TC' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), '000.00')),
                    case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'TP' else 'TC' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), '000.00')),
                    case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'Temps Partiel ' else 'Temps Complet ' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), 'FM990D99')) || 'h',
                    case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'Tps Part ' else 'Tps Compl ' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), 'FM990D99')) || 'h'
                from prod_talentia_rh.iptw2fghm_csalar
                WHERE case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'TP' else 'TC' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), '000.00')) NOT IN (SELECT code_original FROM rh.t_types_temps_travail)
                group by 1,2,3,4
            ;

            -- Màj des types d'horaire
            INSERT INTO rh.t_types_horaire(code_original, code, texte, texte_court)
                select  codcdd, codcdd, libcdd, substr(libcdd, 1, 50)
                from prod_talentia_rh.iptw2fghm_zontab
                where true
                    and nomtbd = 'JOUNUI'
                    AND codcdd NOT IN (SELECT code_original FROM rh.t_types_horaire WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4
            ;

            -- Màj des services.
            INSERT INTO rh.t_services(code_original, code, texte, texte_court)
                select cddepp, cddepp, listep, substr(listep, 1, 50)
                from prod_talentia_rh.iptw2fghm_strucp
                where 1=1
                    AND cdsecp = '000'
                    and cddepp != '000'
                    AND cddepp NOT IN (SELECT code_original FROM rh.t_services)
                GROUP BY 1,2,3,4
            ;

            -- [NON] Màj des spécialités.
            
            -- Màj des codes emploi
            INSERT INTO rh.t_codes_emploi(code_original, code, texte, texte_court)
                select cdsecp, cdsecp, listep, substr(listep, 1, 50)
                from prod_talentia_rh.iptw2fghm_strucp
                where 1=1
                    and cdsecp != '000'
                    AND cdsecp NOT IN (SELECT code_original FROM rh.t_codes_emploi)
                GROUP BY 1,2,3,4
            ;

            -- [NON] Màj des comptes.

            -- [NON] Màj des sociétés d'interim

            -- Màj des grilles
            INSERT INTO rh.t_grilles(code_original, code, texte, texte_court)
                select nbpoin::int, nbpoin::int, nbpoin::int, substr(nbpoin::int, 1, 50)
                from prod_talentia_rh.iptw2fghm_csalar
                where nbpoin::int NOT IN (SELECT code_original FROM rh.t_grilles WHERE code_original IS NOT NULL)
                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 codcdd, codcdd, libcdd, substr(libcdd, 1, 50)
                from prod_talentia_rh.iptw2fghm_zontab
                where true
                    and nomtbd = 'FILIER'
                    AND codcdd NOT IN (SELECT code_original FROM rh.t_grilles_groupes WHERE code_original IS NOT NULL)
                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 cdcndb, cdcndb, libcob, substr(libcob, 1, 50)
                from prod_talentia_rh.iptw2fghm_coempb
                where cdcndb NOT IN (SELECT code_original FROM rh.t_motifs_arret WHERE code_original IS NOT NULL)
                GROUP BY 1,2,3,4
            ;

            -- Insertion du Plan Analytique.
            TRUNCATE rh.t_plan_analytique
            ;
            INSERT INTO rh.t_plan_analytique(oid, code, texte)
            VALUES
                (1, 'TALENTIARH', 'Plan analytique Talentia RH.')
            ;

            -- Màj des sections analytiques.
            INSERT INTO rh.t_section_analytique(code_original, code, texte, texte_court)
                select ctan1u||axe11u, ctan1u||axe11u, ctan1u||axe11u, substr(ctan1u||axe11u, 1, 50)
                from prod_talentia_rh.iptw2fghm_rsalan
                where ctan1u||axe11u NOT IN (SELECT code FROM rh.t_section_analytique)
                group by 1,2,3,4
            ;

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

            -- Pré-paramétrage automatique des rubriques (au mieux).
            -- Cette requête n'intervient pas sur les rubriques paramétrées à la main.
            -- s_* (source_) :
            --   - 0 = nombre
            --   - 1 = base
            --   - 2 = taux salarial
            --   - 3 = montant salarial
            --   - 4 = taux patronal
            --   - 5 = montant patronal
            --   - 6 = montant salarial + montant patronal

            DROP TABLE IF EXISTS w_rub_affectation
            ;
            
            CREATE TEMP TABLE w_rub_affectation AS
                select
                    cdrubk,
                    false as p_cumul,
                    -- Rubrique de détail.
                    cdde1k in ('G', 'R') or cdde3k = 'P' as p_detail,
                    -- Nombre.
                    false as p_nombre,
                    0 as s_nombre,
                    1 as c_nombre,
                    -- Base.
                    cdde1k in ('G', 'R') or cdde3k = 'P' as p_base,
                    1 as s_base,
                    1 as c_base,
                    -- Heures payées.
                    false as p_heures_payees,
                    0 as s_heures_payees,
                    1 as c_heures_payees,
                    -- Heures travaillées.
                    false as p_heures_travaillees,
                    0 as s_heures_travaillees,
                    1 as c_heures_travaillees,
                    -- Masse salariale.
                    (cdde1k in ('G', 'R') and cdrubk::int < 349900) or cdde3k = 'P' as p_masse_salariale,
                    case
                        when cdde1k in ('G', 'R') and cdrubk::int < 349900 then 3
                        when cdde3k = 'P' then 5
                        else 3
                    end as s_masse_salariale,
                    1 as c_masse_salariale,
                    -- Brut
                    cdde1k in ('G', 'R') and cdrubk::int < 349900 as p_brut,
                    3 as s_brut,
                    1 as c_brut,
                    -- Avantages en nature
                    false as p_avantage_nature,
                    3 as s_avantage_nature,
                    1 as c_avantage_nature,
                    -- Frais imposable
                    false as p_frais_imposables,
                    3 as s_frais_imposables,
                    1 as c_frais_imposables,
                    -- Cotisations salariales
                    cdde1k in ('G', 'R') and cdrubk::int between 349901 and 600600 as p_cotisation_salarie,
                    3 as s_cotisation_salarie,
                    1 as c_cotisation_salarie,
                    -- Cotisations patronales
                    cdde3k = 'P' as p_cotisation_patronale,
                    5 as s_cotisation_patronale,
                    1 as c_cotisation_patronale, -- tous les montants patronaux sont déjà signés négativement donc -1 pour ce coeff.
                    -- OD/Net salariales
                    cdde1k in ('G', 'R') and cdrubk::int > 600600 as p_od_net_salarie,
                    3 as s_od_net_salarie,
                    -1 as c_od_net_salarie,
                    -- OD/Net patronales
                    false as p_od_net_patronale,
                    5 as s_od_net_patronale,
                    1 as c_od_net_patronale,
                    -- Net imposable
                    cdde1k in ('G', 'R') and cdrubk::int < 599920 as p_net_imposable,
                    3 as s_net_imposable,
                    1 as c_net_imposable,
                    -- Net à payer
                    cdde1k in ('G', 'R') p_net_a_payer,
                    3 as s_net_a_payer,
                    1 as c_net_a_payer
                from prod_talentia_rh.iptw2fghm_rubrik
            ;

            update rh.t_rubriques set
                p_cumul = rub.p_cumul,
                p_detail = rub.p_detail,
                p_nombre = rub.p_nombre,
                s_nombre = rub.s_nombre,
                c_nombre = rub.c_nombre,
                p_base = rub.p_base,
                s_base = rub.s_base,
                c_base = rub.c_base,
                p_heures_payees = rub.p_heures_payees,
                s_heures_payees = rub.s_heures_payees,
                c_heures_payees = rub.c_heures_payees,
                p_heures_travaillees = rub.p_heures_travaillees,
                s_heures_travaillees = rub.s_heures_travaillees,
                c_heures_travaillees = rub.c_heures_travaillees,
                p_masse_salariale = rub.p_masse_salariale,
                s_masse_salariale = rub.s_masse_salariale,
                c_masse_salariale = rub.c_masse_salariale,
                p_brut = rub.p_brut,
                s_brut = rub.s_brut,
                c_brut = rub.c_brut,
                p_avantage_nature = rub.p_avantage_nature,
                s_avantage_nature = rub.s_avantage_nature,
                c_avantage_nature = rub.c_avantage_nature,
                p_frais_imposables = rub.p_frais_imposables,
                s_frais_imposables = rub.s_frais_imposables,
                c_frais_imposables = rub.c_frais_imposables,
                p_cotisation_salarie = rub.p_cotisation_salarie,
                s_cotisation_salarie = rub.s_cotisation_salarie,
                c_cotisation_salarie = rub.c_cotisation_salarie,
                p_cotisation_patronale = rub.p_cotisation_patronale,
                s_cotisation_patronale = rub.s_cotisation_patronale,
                c_cotisation_patronale = rub.c_cotisation_patronale,
                p_od_net_salarie = rub.p_od_net_salarie,
                s_od_net_salarie = rub.s_od_net_salarie,
                c_od_net_salarie = rub.c_od_net_salarie,
                p_od_net_patronale = rub.p_od_net_patronale,
                s_od_net_patronale = rub.s_od_net_patronale,
                c_od_net_patronale = rub.c_od_net_patronale,
                p_net_imposable = rub.p_net_imposable,
                s_net_imposable = rub.s_net_imposable,
                c_net_imposable = rub.c_net_imposable,
                p_net_a_payer = rub.p_net_a_payer,
                s_net_a_payer = rub.s_net_a_payer,
                c_net_a_payer = rub.c_net_a_payer
            from w_rub_affectation as rub
            where 1=1
                AND t_rubriques.code_original = rub.cdrubk
                AND NOT t_rubriques.user_modified
            ;

            ]]></sqlcmd>
        </NODE>
    </NODE>
    <NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
        <NODE label="Pre-traitement des 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
                    cdmatn||'-'||chronn as code_original, -- Code unique du profil CTI.
                    -- Clefs naturelles prestataire.
                    cdsocn as ent_ori,
                    cdetsn as ets_ori,
                    t_etablissements.oid as etablissement_id,
                    t_etablissements.entreprise_id,
                    cdmatn as mat,
                    -- noconn as numero_contrat,
                    noconn||'-'||chronn as numero_contrat,
                    base.cti_to_date(dtdctn)::date as date_debut,
                    coalesce(base.cti_to_date(dtfctn)::date, '2099-12-31'::date) as date_fin,
                    coalesce(nullif(nbhtpn, 0), 151.67) / 151.67 as etp_contrat,
                    coalesce(nullif(nbhtpn, 0), 151.67) as heures_contrat,
                    0 as est_hors_periode,
                    -- Données du Profil CTI
                    coalesce(nullif(trim(cdempn), ''), chr(1)||'*') as categorie_socio_professionnelle_code_original,
                    coalesce(nullif(trim(cdsecn), ''), chr(1)||'*') as code_emploi_code_original,
                    coalesce(nullif(trim(nbpoin::int), 0), chr(1)||'*') as grille_code_original,
                    chr(1)||'*' as grille_groupe_code_original, -- FIXME Impossible de trouver l'usage dans les tables de prod.
                    chr(1)||'*' AS groupe_cotisant_code_original,
                    coalesce(nullif(trim(MOTENN), ''), chr(1)||'*') as motif_debut_code_original,
                    coalesce(nullif(trim(CDMODN), ''), chr(1)||'*') as motif_fin_code_original,
                    coalesce(nullif(trim(cdepln), ''), chr(1)||'*') as qualification_code_original,
                    chr(1)||'*' AS section_analytique_code_original,
                    chr(1)||'*' AS section_analytique_paie_code_original,
                    coalesce(nullif(trim(cddepn), ''), chr(1)||'*') AS service_code_original,
                    chr(1)||'*' AS societe_interim_code_original,
                    chr(1)||'*' AS specialite_code_original,
                    coalesce(nullif(trim(cdcatn), ''), chr(1)||'*') as statut_code_original,
                    coalesce(nullif(trim(cdconn), ''), chr(1)||'*') AS type_contrat_code_original,
                    chr(1)||'*' AS type_horaire_code_original,
                    case when coalesce(nullif(nbhtpn, 0), 151.67) < 151.67 then 'TP' else 'TC' end || trim(to_char(coalesce(nullif(nbhtpn, 0), 151.67), '000.00')) AS type_temps_travail_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 prod_talentia_rh.iptw2fghm_csalar
                join rh.t_etablissements on t_etablissements.code_original = iptw2fghm_csalar.cdetsn
            ;

            ]]></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,
                    nomsan AS nom,
                    prenon AS prenom,
                    base.cti_to_date(aanasn, mmnasn, jjnasn) AS date_naissance,
                    CASE WHEN cdsexn = 'H' THEN 'M' ELSE 'F' END AS sexe,
                    cdmatn AS matricule,
                    cdmatn AS code,
                    cdmatn AS code_original,
                    coalesce(t_entreprises.oid, 0) AS entreprise_id,
                    coalesce(t_nationalites.oid, 0) AS nationalite_id,
                    coalesce(t_codes_postaux.oid, 0) AS code_postal_id,
                    nomjfn AS nom_naissance,
                    coalesce(t_situations_famille.oid, 0) AS situation_famille_id,
                    ((max(ARRAY[w_profils.date_fin::text, w_profils.profil_id::text]))[2])::bigint AS profil_id, -- dernier profil salarié.
                    max(w_profils.date_debut) AS date_debut, -- date de début du dernier contrat.
                    max(w_profils.date_fin) AS date_fin, -- date de fin du dernier contrat.
                    min(w_profils.date_debut) AS date_entree_ets,
                    max(w_profils.date_fin) AS date_sortie_ets,
                    -- Champs dédiés au public.
                    '1900-01-01'::date AS date_entree_fp,
                    '1900-01-01'::date  AS date_entree_fph,
                    0 AS no_adeli,
                    0 AS code_cotisation_id,
                    0 AS matricule_retraite
                FROM prod_talentia_rh.iptw2fghm_salarn AS salarie
                    JOIN w_profils on w_profils.mat = salarie.cdmatn
                    LEFT JOIN rh.t_codes_postaux ON t_codes_postaux.code = salarie.cpsaln
                    LEFT JOIN rh.t_situations_famille ON t_situations_famille.code_original = salarie.cdsifn
                    LEFT JOIN rh.t_entreprises ON t_entreprises.code_original = salarie.cdsocn
                    LEFT JOIN rh.t_nationalites ON t_nationalites.code_original = salarie.cdnatn
                GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13, 19,20,21,22,23
            ;
            
            ]]></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,
                profil_id)
                select
                    coalesce(p_salaries.oid,0) AS salarie_id,
                    w_profils.date_debut,
                    w_profils.date_fin,
                    w_profils.numero_contrat, 
                    w_profils.numero_contrat AS code_original,
                    coalesce(t_etablissements.oid,0) AS etablissement_id,
                    (max(ARRAY[extract(EPOCH from w_profils.date_fin), w_profils.profil_id]))[2] AS profil_id -- Il se peut que pour un même contrat, il y est plusieurs profils. Dans ce cas on prend le profil le plus récent.
                from w_profils
                   JOIN rh.p_salaries ON p_salaries.matricule = w_profils.mat
                   join rh.t_etablissements ON t_etablissements.code_original = w_profils.ets_ori
                GROUP BY 1,2,3,4,5,6
            ;
            
            TRUNCATE rh.p_contrats_mois
            ;

            ALTER SEQUENCE rh.s_contrats_mois RESTART WITH 1
            ;

            INSERT INTO rh.p_contrats_mois(
                code_original,
                salarie_id,
                etablissement_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)
                SELECT
                    w_profils.code_original,
                    p_salaries.oid AS salarie_id,
                    p_contrats.etablissement_id,
                    p_contrats.oid AS contrat_id,
                    p_calendrier_mois.mois AS mois,
                    GREATEST(p_calendrier_mois.date_debut, w_profils.date_debut) AS date_debut,
                    LEAST(p_calendrier_mois.date_fin, w_profils.date_fin) AS date_fin,
                    CASE WHEN p_salaries.date_entree_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_entrees,
                    CASE WHEN p_salaries.date_sortie_ets BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_departs,
                    CASE WHEN p_contrats.date_debut BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_debut_contrat,
                    CASE WHEN p_contrats.date_fin BETWEEN p_calendrier_mois.date_debut AND p_calendrier_mois.date_fin THEN 1 ELSE 0 END AS nombre_fin_contrat,
                    w_profils.est_hors_periode,
                    CASE WHEN p_calendrier_mois.date_debut BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_debut_mois,
                    CASE WHEN p_calendrier_mois.date_fin BETWEEN p_contrats.date_debut AND p_contrats.date_fin THEN 1 ELSE 0 END AS present_fin_mois,
                    etp_contrat,
                    heures_contrat,
                    base.cti_age(LEAST(p_calendrier_mois.date_fin, w_profils.date_fin), COALESCE(p_salaries.date_naissance, '1962-04-18'::date), 'ny')  AS age_id,
                    LEAST(p_calendrier_mois.date_fin, w_profils.date_fin)::date - COALESCE(p_salaries.date_naissance, '1962-04-18'::date) AS age_jours,
                    p_contrats.anciennete_anterieure_jours
                        + (LEAST(p_calendrier_mois.date_fin, w_profils.date_fin) - p_contrats.date_debut)
                        + 1
                    AS anciennete_jours,
                    base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
                        + p_contrats.anciennete_anterieure_calculee_mois
                    AS anciennete_mois,
                    floor(
                        (
                            base.cti_months_between(p_contrats.date_debut, p_calendrier_mois.date_fin)
                            + p_contrats.anciennete_anterieure_calculee_mois
                        ) / 12
                    ) AS anciennete_annee_id
                from w_profils
                    JOIN base.p_calendrier_mois ON base.cti_overlaps(w_profils.date_debut, w_profils.date_fin, p_calendrier_mois.date_debut, p_calendrier_mois.date_fin)
                    JOIN rh.p_contrats ON p_contrats.numero_contrat = w_profils.numero_contrat
                    JOIN rh.p_salaries ON p_salaries.matricule = w_profils.mat
                WHERE 1=1
                    AND p_calendrier_mois.mois < to_char(now() + '1 month'::interval, 'YYYYMM')
            ;

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

            DROP TABLE IF EXISTS w_hp
            ;

            CREATE TEMP TABLE w_hp AS
                SELECT
                    bul.mat,
                    p_salaries.oid as salarie_id,
                    p_salaries.date_naissance,
					bul.mois::int AS mois_paie,
                    bul.mois::int AS mois_activite,
                    nojobo,
                    norjpo,
                    bul.date_debut,
                    bul.date_fin,
                    bul.date_fin as date_paie,
                    t_rubriques.p_detail,
                    t_rubriques.p_cumul,
                    t_rubriques.oid as rubrique_id,
                    lig.cdrub9 as rub,
                    (CASE WHEN p_nombre THEN (CASE s_nombre
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_nombre)::numeric AS nombre,
                    (CASE WHEN p_base THEN (CASE s_base
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_base)::numeric AS base,
                    (CASE WHEN p_heures_payees THEN (CASE s_heures_payees
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_heures_payees)::numeric(11, 2) AS heure_payee,
                    (CASE WHEN p_heures_travaillees THEN (CASE s_heures_travaillees
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_heures_travaillees)::numeric(11, 2) AS heure_travaillee,
                    (CASE WHEN p_masse_salariale THEN (CASE s_masse_salariale
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_masse_salariale)::numeric AS montant_masse_salariale,
                    (CASE WHEN p_brut THEN (CASE s_brut
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_brut)::numeric AS montant_brut,
                    (CASE WHEN p_avantage_nature THEN (CASE s_avantage_nature
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_avantage_nature)::numeric AS montant_avantage_nature,
                    (CASE WHEN p_frais_imposables THEN (CASE s_frais_imposables
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_frais_imposables)::numeric AS montant_frais_imposables,
                    (txsa29 * coefficient_txs) AS taux_cotisation_salarie,
                    (CASE WHEN p_cotisation_salarie THEN (CASE s_cotisation_salarie
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_cotisation_salarie)::numeric AS montant_cotisation_salarie,
                    (txpa29 * coefficient_txp) AS taux_cotisation_patronale,
                    (CASE WHEN p_cotisation_patronale THEN (CASE s_cotisation_patronale
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_cotisation_patronale)::numeric AS montant_cotisation_patronale,
                    (CASE WHEN p_od_net_salarie THEN (CASE s_od_net_salarie
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_od_net_salarie)::numeric AS montant_od_net_salarie,
                    (CASE WHEN p_od_net_patronale THEN (CASE s_od_net_patronale
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_od_net_patronale)::numeric AS montant_od_net_patronale,
                    (CASE WHEN p_net_imposable THEN (CASE s_net_imposable
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_net_imposable)::numeric AS montant_net_imposable_salarie,
                    (CASE WHEN p_net_a_payer THEN (CASE s_net_a_payer
                            WHEN 0 THEN mbsp29
                            WHEN 1 THEN mbsp29
                            WHEN 2 THEN txsa29
                            WHEN 3 THEN mtsr29
                            WHEN 4 THEN txpa29
                            WHEN 5 THEN mtpr29
                            WHEN 6 THEN mtsr29 + mtpr29
                            WHEN 7 THEN mtsr29 - mtpr29
                            WHEN 8 THEN -mtsr29 + mtpr29
                        END) ELSE 0 END * c_net_a_payer)::numeric AS montant_net_a_payer_salarie
                FROM w_bul as bul
                    JOIN prod_talentia_rh.iptw2fghm_hires9 as lig ON 1=1
                        AND lig.cdmat9 = bul.mat
                        AND lig.nojob9 = bul.nojobo
                        AND lig.norjp9 = bul.norjpo
                    JOIN rh.p_salaries ON p_salaries.matricule = bul.mat
                    JOIN rh.t_rubriques ON t_rubriques.code_original = lig.cdrub9
                WHERE 1=1
                    AND aappa9::int >= 2016
                    AND (1!=1
                        OR t_rubriques.p_detail
                        OR t_rubriques.p_cumul)
            ;

            TRUNCATE rh.p_historique_paie
            ;

            ALTER SEQUENCE rh.s_historique_paie RESTART WITH 1
            ;
            
            SELECT base.cti_stash_table_indexes('rh', 'p_historique_paie')
            ;

            DROP TABLE IF EXISTS w_hp_1
            ;

            CREATE TEMP TABLE w_hp_1 AS
                SELECT
                    nextval('rh.s_historique_paie'::regclass) as oid,
                    date_part('year', age(w_hp.date_debut, date_naissance)) AS age_id,
                    w_hp.nombre,
                    w_hp.base AS base,
                    (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,
                    w_hp.date_debut,
                    w_hp.date_fin,
                    w_hp.date_paie,
                    w_hp.mois_activite,
                    w_hp.mois_paie,
                    w_hp.heure_payee,
                    w_hp.heure_travaillee,
                    w_hp.montant_avantage_nature,
                    w_hp.montant_brut,
                    w_hp.montant_masse_salariale,
                    w_hp.montant_cotisation_patronale,
                    w_hp.montant_cotisation_salarie,
                    w_hp.montant_frais_imposables,
                    w_hp.montant_net_a_payer_salarie,
                    w_hp.montant_net_imposable_salarie,
                    w_hp.montant_od_net_salarie,
                    w_hp.montant_od_net_patronale,
                    coalesce(t_organismes_cotisation.oid, 0) AS organisme_cotisation_id,
                    rubrique_id,
                    w_hp.mat,
                    w_hp.salarie_id,
                    w_hp.taux_cotisation_patronale,
                    w_hp.taux_cotisation_salarie,
                    0 AS compte_id,
                    nojobo,
                    norjpo
                FROM w_hp
                    LEFT JOIN w_caisses ON w_caisses.rub = w_hp.rub
                    LEFT JOIN rh.t_organismes_cotisation ON t_organismes_cotisation.code_original = w_caisses.code_ori
                    LEFT JOIN rh.p_contrats_mois ON 1=1
                        AND p_contrats_mois.salarie_id = w_hp.salarie_id
                        AND base.cti_overlaps(p_contrats_mois.date_debut, p_contrats_mois.date_fin, w_hp.date_debut, w_hp.date_fin)
                WHERE w_hp.p_detail
                GROUP BY 1,2,3,4,  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, w_hp.ctid
            ;

            -- Associer les bulletins hors contrat (is null) avec le contrat PRECEDENT.
            UPDATE w_hp_1 SET
                contrat_id = subq.contrat_id,
                contrat_mois_id = subq.contrat_mois_id
            FROM (
                select
                    w_hp_1.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_hp_1
                    join rh.p_contrats_mois on true
                        and p_contrats_mois.salarie_id = w_hp_1.salarie_id
                        and p_contrats_mois.date_fin < w_hp_1.date_debut
                where contrat_mois_id is null
                group by 1) as subq
            WHERE true
                AND w_hp_1.oid = subq.oid
                AND w_hp_1.contrat_mois_id is null
            ;

            -- Associer les bulletins hors contrat (is null) avec le contrat SUIVANT.
            UPDATE w_hp_1 SET
                contrat_id = subq.contrat_id,
                contrat_mois_id = subq.contrat_mois_id
            FROM (
                select
                    w_hp_1.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_hp_1
                    join rh.p_contrats_mois on true
                        and p_contrats_mois.salarie_id = w_hp_1.salarie_id
                        and p_contrats_mois.date_debut > w_hp_1.date_fin
                where contrat_mois_id is null
                group by 1) as subq
            WHERE true
                AND w_hp_1.oid = subq.oid
                AND w_hp_1.contrat_mois_id is null
            ;
            
            -- Insertion dans la table de production CTI.
            INSERT INTO rh.p_historique_paie(
                oid,
                age_id,
                nombre,
                base,
                contrat_id,
                contrat_mois_id,
                date_debut,
                date_fin,
                date_paie,
                mois_activite,
                mois_paie,
                heure_payee,
                heure_travaillee,
                montant_avantage_nature,
                montant_brut,
                montant_masse_salariale,
                montant_cotisation_patronale,
                montant_cotisation_salarie,
                montant_frais_imposables,
                montant_net_a_payer_salarie,
                montant_net_imposable_salarie,
                montant_od_net_salarie,
                montant_od_net_patronale,
                organisme_cotisation_id,
                rubrique_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie,
                compte_id)
                SELECT
                    oid,
                    age_id,
                    nombre,
                    base,
                    contrat_id,
                    contrat_mois_id,
                    date_debut,
                    date_fin,
                    date_paie,
                    mois_activite,
                    mois_paie,
                    heure_payee,
                    heure_travaillee,
                    montant_avantage_nature,
                    montant_brut,
                    montant_masse_salariale,
                    montant_cotisation_patronale,
                    montant_cotisation_salarie,
                    montant_frais_imposables,
                    montant_net_a_payer_salarie,
                    montant_net_imposable_salarie,
                    montant_od_net_salarie,
                    montant_od_net_patronale,
                    organisme_cotisation_id,
                    rubrique_id,
                    salarie_id,
                    taux_cotisation_patronale,
                    taux_cotisation_salarie,
                    compte_id
                FROM w_hp_1
            ;
            
            -- Inserer pour chaque bulletin une ligne qui va faire le compte avec le total (rubrique 'C000' nommée 'Ecart cumulé')
            INSERT INTO rh.p_historique_paie(
                age_id,
                contrat_id,
                contrat_mois_id,
                date_debut,
                date_fin,
                date_paie,
                mois_activite,
                mois_paie,
                nombre,
                base,
                heure_payee,
                heure_travaillee,
                montant_masse_salariale,
                montant_brut,
                montant_avantage_nature,
                montant_frais_imposables,
                montant_cotisation_salarie,
                montant_cotisation_patronale,
                montant_od_net_salarie,
                montant_od_net_patronale,
                montant_net_imposable_salarie,
                montant_net_a_payer_salarie,
                organisme_cotisation_id,
                profil_id, -- @deprecated
                rubrique_id,
                salarie_id,
                taux_cotisation_patronale,
                taux_cotisation_salarie)
                SELECT
                    age_id,
                    contrat_id,
                    contrat_mois_id,
                    subq.date_debut,
                    subq.date_fin,
                    subq.date_paie,
                    subq.mois_activite,
                    subq.mois_paie,
                    0 as nombre,
                    0 AS base,
                    sum(cum.heure_payee - subq.heure_payee) as heure_payee,
                    sum(cum.heure_travaillee - subq.heure_travaillee) as heure_travaillee,
                    sum(cum.montant_masse_salariale - subq.montant_masse_salariale) as montant_masse_salariale,
                    sum(cum.montant_brut - subq.montant_brut) as montant_brut,
                    sum(cum.montant_avantage_nature - subq.montant_avantage_nature) as montant_avantage_nature,
                    sum(cum.montant_frais_imposables - subq.montant_frais_imposables) as montant_frais_imposables,
                    sum(cum.montant_cotisation_salarie - subq.montant_cotisation_salarie) as montant_cotisation_salarie,
                    sum(cum.montant_cotisation_patronale - subq.montant_cotisation_patronale) as montant_cotisation_patronale,
                    sum(cum.montant_od_net_salarie - subq.montant_od_net_salarie) as montant_od_net_salarie,
                    sum(cum.montant_od_net_patronale - subq.montant_od_net_patronale) as montant_od_net_patronale,
                    sum(cum.montant_net_imposable_salarie - subq.montant_net_imposable_salarie) as montant_net_imposable_salarie,
                    sum(cum.montant_net_a_payer_salarie - subq.montant_net_a_payer_salarie) as montant_net_a_payer_salarie,
                    subq.organisme_cotisation_id AS organisme_cotisation_id,
                    subq.profil_id AS profil_id,
                    (SELECT oid FROM rh.t_rubriques WHERE code = 'C000') AS rubrique_id,
                    subq.salarie_id AS salarie_id,
                    0 AS taux_cotisation_patronale,
                    0 AS taux_cotisation_salarie
                FROM (
                    SELECT
                        w_hp.salarie_id,
                        w_hp.nojobo,
                        w_hp.norjpo,
                        sum(w_hp.heure_payee) as heure_payee,
                        sum(w_hp.heure_travaillee) as heure_travaillee,
                        sum(w_hp.montant_avantage_nature) as montant_avantage_nature,
                        sum(w_hp.montant_brut) as montant_brut,
                        sum(w_hp.montant_masse_salariale) as montant_masse_salariale,
                        sum(w_hp.montant_cotisation_patronale) as montant_cotisation_patronale,
                        sum(w_hp.montant_cotisation_salarie) as montant_cotisation_salarie,
                        sum(w_hp.montant_frais_imposables) as montant_frais_imposables,
                        sum(w_hp.montant_net_a_payer_salarie) as montant_net_a_payer_salarie,
                        sum(w_hp.montant_net_imposable_salarie) as montant_net_imposable_salarie,
                        sum(w_hp.montant_od_net_salarie) as montant_od_net_salarie,
                        sum(w_hp.montant_od_net_patronale) as montant_od_net_patronale
                    FROM w_hp
                    WHERE w_hp.p_cumul
                    GROUP BY 1,2,3) as cum
                    JOIN (
                        SELECT
                            age_id,
                            contrat_id,
                            contrat_mois_id,
                            date_debut,
                            date_fin,
                            date_paie,
                            mois_activite,
                            mois_paie,
                            nojobo,
                            norjpo,
                            sum(heure_payee) as heure_payee,
                            sum(heure_travaillee) as heure_travaillee,
                            sum(montant_masse_salariale) as montant_masse_salariale,
                            sum(montant_brut) AS montant_brut,
                            sum(montant_avantage_nature) AS montant_avantage_nature,
                            sum(montant_frais_imposables) AS montant_frais_imposables,
                            sum(montant_cotisation_salarie) AS montant_cotisation_salarie,
                            sum(montant_cotisation_patronale) AS montant_cotisation_patronale,
                            sum(montant_od_net_salarie) as montant_od_net_salarie,
                            sum(montant_od_net_patronale) as montant_od_net_patronale,
                            sum(montant_net_imposable_salarie) AS montant_net_imposable_salarie,
                            sum(montant_net_a_payer_salarie) AS montant_net_a_payer_salarie,
                            0 AS organisme_cotisation_id,
                            0 AS profil_id,
                            (SELECT oid FROM rh.t_rubriques WHERE code = 'C000'),
                            salarie_id,
                            0 AS taux_cotisation_patronale,
                            0 AS taux_cotisation_salarie
                        FROM w_hp_1
                        GROUP BY 1,2,3,4,5,6,7,8,9,10, 23,24,25,26,27,28) AS subq ON true
                            AND subq.salarie_id = cum.salarie_id
                            AND subq.nojobo = cum.nojobo
                            AND subq.norjpo = cum.norjpo
                GROUP BY 1,2,3,4,5,6,7,8, 23,24,25,26,27,28
                HAVING 1!=1
                    OR sum(cum.heure_payee - subq.heure_payee) != 0
                    OR sum(cum.heure_travaillee - subq.heure_travaillee) != 0
                    OR sum(cum.montant_masse_salariale - subq.montant_masse_salariale) != 0
                    OR sum(cum.montant_brut - subq.montant_brut) != 0
                    OR sum(cum.montant_avantage_nature - subq.montant_avantage_nature) != 0
                    OR sum(cum.montant_frais_imposables - subq.montant_frais_imposables) != 0
                    OR sum(cum.montant_cotisation_salarie - subq.montant_cotisation_salarie) != 0
                    OR sum(cum.montant_cotisation_patronale - subq.montant_cotisation_patronale) != 0
                    OR sum(cum.montant_od_net_salarie - subq.montant_od_net_salarie) != 0
                    OR sum(cum.montant_od_net_patronale - subq.montant_od_net_patronale) != 0
                    OR sum(cum.montant_net_imposable_salarie - subq.montant_net_imposable_salarie) != 0
                    OR sum(cum.montant_net_a_payer_salarie - subq.montant_net_a_payer_salarie) != 0
            ;

            SELECT base.cti_stash_pop_table_indexes('rh', 'p_historique_paie')
            ;
			
			INSERT INTO rh.t_divers (code, texte, valeur, valeur_date, description, show_info_module)
				SELECT
				'NOW',
				'Date en-cours',
				to_char(date_max, 'YYYYMM'),
				date_max,
				'Date non modifiable',
				true
			FROM 
				(SELECT date(MAX(date_paie) + interval '1 month') AS date_max FROM rh.p_historique_paie WHERE date_paie <= now()) sub
			WHERE 'NOW' NOT IN (SELECT code FROM rh.t_divers);
			
			
			INSERT INTO rh.t_divers (code, texte, valeur, valeur_date, description, show_info_module)
				SELECT
				'NOWCLOTURE',
				'Date en-cours',
				to_char(date_max, 'YYYYMM'),
				date_max,
				'Date non modifiable',
				true
			FROM 
				(SELECT date(MAX(date_paie)) AS date_max FROM rh.p_historique_paie WHERE date_paie <= now()) sub
			WHERE 'NOWCLOTURE' NOT IN (SELECT code FROM rh.t_divers);

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

            TRUNCATE rh.p_chiffrier_production
            ;

            INSERT INTO rh.p_chiffrier_production (entreprise_id, etablissement_id, mois, nombre_salaries, montant_brut, nombre_heures)
                select
                    t_etablissements.entreprise_id AS entreprise_id,
                    t_etablissements.oid as etablissement_id,
                    mois_paie,
                    count(distinct mat) AS nombre_salaries,
                    sum(montant_brut),
                    sum(heure_payee) AS nombre_heures
                FROM w_hp
                    JOIN rh.p_salaries ON p_salaries.matricule = w_hp.mat
                    LEFT 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_hp.date_debut, w_hp.date_fin)
                    LEFT JOIN rh.t_etablissements on t_etablissements.oid = p_contrats_mois.etablissement_id
                WHERE w_hp.p_cumul
                group by 1,2,3
            ;

            ]]></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
                    w_profils.profil_id,
                    p_contrats_mois.oid as contrat_mois_id,
                    p_contrats_mois.salarie_id,
                    1 AS ratio,
                    p_contrats_mois.mois_activite
                from rh.p_contrats_mois
                    join w_profils ON w_profils.code_original = p_contrats_mois.code_original
                group by 1,2,3,4,5
            ;

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

            DROP SEQUENCE IF EXISTS ventilation_id
            ;
            CREATE TEMP SEQUENCE ventilation_id START 1
            ;

            DROP TABLE IF EXISTS w_ven
            ;
            CREATE TEMP TABLE w_ven AS
                with ven_0 as (
                    select
                        ctan1u||axe11u as sec,
                        dtperu,
                        dtdppu,
                        dtfppu,
                        nojobu,
                        norjpu,
                        cdmatu as mat,
                        sum(pcan1u) / 100.0 as rat
                    from prod_talentia_rh.iptw2fghm_rsalan
                    group by 1,2,3,4,5,6,7)
                , ven_1 as (
                    select
                        sec,
                        dtperu,
                        dtdppu,
                        dtfppu,
                        nojobu,
                        norjpu,
                        mat,
                        base.cti_division(rat, sum(rat) over w) as rat,
                        row_number() over wo as rang
                    from ven_0
                    window w as (partition by mat, dtperu, dtdppu, dtfppu, nojobu, norjpu),
                          wo as (partition by mat, dtperu, dtdppu, dtfppu, nojobu, norjpu order by rat desc))
                , ven_corr as (
                    select
                        dtperu,
                        dtdppu,
                        dtfppu,
                        nojobu,
                        norjpu,
                        mat,
                        1.0 - sum(rat) as cor
                    from ven_1
                    group by 1,2,3,4,5,6
                    having sum(rat) != 1)
                select
                    ven_1.dtperu,
                    ven_1.dtdppu,
                    ven_1.dtfppu,
                    ven_1.nojobu,
                    ven_1.norjpu,
                    ven_1.mat,
                    array_agg(ven_1.sec order by ven_1.sec) as sec,
                    array_agg(case when cor is not null and ven_1.rang = 1 then ven_1.rat + ven_corr.cor else ven_1.rat end order by ven_1.sec) as rat,
                    nextval('ventilation_id') as ventilation_id
                from ven_1
                    left join ven_corr on 1=1
                        and ven_corr.dtperu = ven_1.dtperu
                        and ven_corr.dtdppu = ven_1.dtdppu
                        and ven_corr.dtfppu = ven_1.dtfppu
                        and ven_corr.nojobu = ven_1.nojobu
                        and ven_corr.norjpu = ven_1.norjpu
                        and ven_corr.mat = ven_1.mat
                group by 1,2,3,4,5,6
            ;

            -- 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(sec, ',')||' @ '||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(sec) as sec,
                            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 = sec
                UNION ALL
                    SELECT
                        0,
                        oid,
                        code,
                        texte,
                        1
                    FROM rh.t_section_analytique
                    WHERE oid = 0
            ;

            WITH subq AS (
                select
                    w_hp_1.oid,
                    w_ven.ventilation_id
                from w_hp_1
                    join w_ven on 1=1
                        and w_ven.nojobu = w_hp_1.nojobo
                        and w_ven.norjpu = w_hp_1.norjpo
                        and w_ven.mat = w_hp_1.mat
                        and w_ven.dtperu = w_hp_1.mois_paie)
            UPDATE rh.p_historique_paie SET
                ventilation_1_id = subq.ventilation_id
            FROM subq
            WHERE p_historique_paie.oid = subq.oid
            ;

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

            DROP TABLE IF EXISTS w_arrets
            ;

            CREATE TEMP TABLE w_arrets AS
                select
                    cdsocg as ent,
                    cdmatg as mat,
                    cdmatg||'-'||noarrg as code,
                    cdcndg as motif,
                    to_char(dtdatg::text::date, 'YYYYMM')::int as mois_activite,
                    dtdatg::text::date as date_debut,
                    dtfatg::text::date as date_fin,
                    dtfatg::text::date - dtdatg::text::date + 1 as duree,
                    nullif(dtretg, 0)::text::date as date_reprise
                from prod_talentia_rh.iptw2fghm_malptg
            ;

            -- Alimentation des arrêts de travail (pas d'heures dans Talentia RH).
            TRUNCATE rh.p_arrets_travail
            ;

            ALTER SEQUENCE rh.s_arrets_travail RESTART WITH 1
            ;

            INSERT INTO rh.p_arrets_travail(
                salarie_id,
                contrat_id,
                mois_activite,
                date_debut,
                date_fin,
                date_reprise,
                motif_arret_id,
                precision_motif_arret_id,
                nb_jours)
                SELECT 
                    p_salaries.oid,
                    max(p_contrats.oid),
                    w_arrets.mois_activite,
                    w_arrets.date_debut,
                    w_arrets.date_fin,
                    w_arrets.date_reprise,
                    coalesce(t_motifs_arret.oid, 0) AS motif_arret_id,
                    0 AS precision_motif_arret_id,
                    w_arrets.duree
                FROM w_arrets
                    JOIN rh.p_salaries ON p_salaries.code_original = w_arrets.mat
                    LEFT JOIN rh.t_motifs_arret ON t_motifs_arret.code_original = w_arrets.motif
                    JOIN rh.p_contrats ON 1=1
                        AND p_contrats.salarie_id = p_salaries.oid
                        AND base.cti_overlaps(w_arrets.date_debut, w_arrets.date_fin, p_contrats.date_debut, p_contrats.date_fin)
                GROUP BY 1, 3,4,5,6,7,8,9
            ;

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

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

            ]]></sqlcmd>
        </NODE>
    </NODE>
    <NODE name="POST" label="POST-TRAITEMENTS">
        <NODE name="DIVERS" type="common"/>
        <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>
