<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>


    <NODE name="INIT" label="INITIALISATIONS">
        <NODE label="Tests initiaux">
            <sqlcmd><![CDATA[]]></sqlcmd>
        </NODE>

        <NODE label="Identification des sejours">
            <sqlcmd><![CDATA[]]></sqlcmd>
        </NODE>

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

    <NODE name="PARAM" label="RECUPERATION DES PARAMETRES">
        <NODE label="Preparation des tables">
            <sqlcmd><![CDATA[

            DROP TABLE IF EXISTS w_periode;
            CREATE TEMP TABLE w_periode AS
            SELECT
                MAX(hf_datfac) AS date_extraction
            FROM prod_edlxplore.h_hisfac
			;
            ]]>
            </sqlcmd>
        </NODE>

        <NODE label="Medecins">
            <sqlcmd><![CDATA[
    
            INSERT INTO base.t_specialites_medecin(oid, code, code_original, texte, texte_court) 
            SELECT 0, '', '0', 'Non saisie', 'Non saisie'
            WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin);
            
            UPDATE base.t_specialites_medecin SET
                code_original = code 
            WHERE code_original IS NULL and oid != 0;

            INSERT INTO base.t_specialites_medecin (code, code_original, texte, texte_court)
            SELECT
                h_person.er_qua_ss,
                h_person.er_qua_ss,
                h_person.er_qualif,
                h_person.er_qualif
            FROM prod_edlxplore.h_person
            WHERE 1=1
                AND h_person.er_qua_ss <> ''
                AND h_person.er_qua_ss NOT IN(
                    SELECT
                        code FROM base.t_specialites_medecin)
            GROUP BY 1, 3;

            INSERT INTO activite[PX].t_specialites_medecin(oid, code, code_original, texte, texte_court) 
            SELECT 0, '', '0', 'Non saisie', 'Non saisie'
            WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_specialites_medecin);

            INSERT INTO activite[PX].t_specialites_medecin (code, code_original, texte, texte_court)
            SELECT
                h_person.er_qua_ss,
                h_person.er_qua_ss,
                h_person.er_qualif,
                h_person.er_qualif
            FROM prod_edlxplore.h_person
            WHERE 1=1
                AND h_person.er_qua_ss <> ''
                AND h_person.er_qua_ss NOT IN(
                    SELECT
                        code FROM activite[PX].t_specialites_medecin)
            GROUP BY 1, 3;
            
            INSERT INTO base.t_medecins(oid, nom, prenom, numero_ordre, specialite_id ) 
            SELECT 0, 'Non renseigne', '', '', 0 WHERE 0 NOT IN (SELECT oid FROM base.t_medecins);

            INSERT INTO activite[PX].t_medecins_administratifs(oid, code_original, code, nom, prenom, specialite_id, medecin_id) 
            SELECT 0, '0', '****', 'Non renseigne', '', 0, 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_medecins_administratifs);

            
            DROP TABLE IF EXISTS w_medecins_source;
            CREATE TEMP TABLE w_medecins_source AS
            SELECT
                *,
                er_rpps AS rpps,
                er_qua_ss AS specialite
            FROM
                prod_edlxplore.h_person
            WHERE 1=1
                AND er_codper IN (
                    SELECT
                        em_codtit FROM prod_edlxplore.H_DEMAND
            );

            DROP TABLE IF EXISTS w_medecins;
            CREATE TEMP TABLE w_medecins AS
            SELECT
                er_codper::text,
                er_codper::text AS mede_code,
                base.cti_soundex_nom(w_medecins_source.er_nomage) AS nom_soundex,
                base.cti_soundex_nom(COALESCE(w_medecins_source.er_pnoage, '')) AS prenom_soundex,
                w_medecins_source.er_nomage AS nom,
                COALESCE(w_medecins_source.er_pnoage, '') AS prenom,
                COALESCE(w_medecins_source.rpps, '') AS RPPS,
                COALESCE(w_medecins_source.specialite, '') AS SPECIALITE,
                COALESCE(t_medecins_administratifs.medecin_id, 0) AS medecin_id,
                er_numpra as no_adeli
            FROM
                w_medecins_source
                LEFT JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original = w_medecins_source.specialite::text;


            INSERT INTO base.t_medecins (nom, prenom, numero_ordre, specialite_id)
            SELECT
                nom,
                prenom,
                rpps,
                specialite_id
            FROM (
                SELECT
                    nom,
                    prenom,
                    SUBSTR(nom_soundex, 1, 8) AS nom_soundex,
                    SUBSTR(prenom_soundex, 1, 8) AS prenom_soundex,
                    rpps,
                    coalesce(t_specialites_medecin.oid, 0) AS specialite_id
                FROM
                    w_medecins
                LEFT JOIN base.t_specialites_medecin ON t_specialites_medecin.code = w_medecins.specialite) subview
            WHERE
                subview.nom_soundex || ',' || subview.prenom_soundex || ',' || subview.rpps NOT IN(
                    SELECT
                        substr(base.cti_soundex_nom (nom), 1, 8) || ',' || substr(base.cti_soundex_nom (prenom), 1, 8) || ',' || numero_ordre FROM base.t_medecins);

            UPDATE
                w_medecins
            SET
                medecin_id = subview.medecin_id
            FROM (
                SELECT
                    substr(base.cti_soundex_nom (nom), 1, 8) AS nom,
                    substr(base.cti_soundex_nom (prenom), 1, 8) AS prenom,
                    numero_ordre,
                    MIN(oid) AS medecin_id
                FROM
                    base.t_medecins
                GROUP BY
                    1,
                    2,
                    3) subview
            WHERE
                SUBSTR(nom_soundex, 1, 8) = subview.nom
                AND SUBSTR(prenom_soundex, 1, 8) = subview.prenom
                AND rpps = subview.numero_ordre
                AND w_medecins.medecin_id = 0;

            UPDATE
                w_medecins
            SET
                medecin_id = subview.medecin_id
            FROM (
                SELECT
                    base.cti_soundex_nom (nom) AS nom,
                    base.cti_soundex_nom (prenom) AS prenom,
                    MIN(oid) AS medecin_id
                FROM
                    base.t_medecins
                GROUP BY
                    1,
                    2) subview
            WHERE
                SUBSTR(nom_soundex, 1, 8) = subview.nom
                AND SUBSTR(prenom_soundex, 1, 8) = subview.prenom
                AND w_medecins.medecin_id = 0;

            INSERT INTO activite[PX].t_medecins_administratifs (code_original, code, nom, prenom, specialite_id, medecin_id, no_adeli)
            SELECT DISTINCT
                er_codper::text,
                er_codper::text,
                nom,
                prenom,
                COALESCE(t_specialites_medecin.oid::bigint, 0),
                medecin_id,
                no_adeli
            FROM
                w_medecins
                LEFT JOIN base.t_specialites_medecin ON t_specialites_medecin.code_original = specialite
            WHERE
                er_codper::text NOT IN(
                    SELECT
                        code_original FROM activite[PX].t_medecins_administratifs);

            UPDATE
                activite[PX].t_medecins_administratifs
            SET
                nom = w_medecins.nom,
                prenom = w_medecins.prenom,
                specialite_id = COALESCE(t_specialites_medecin.oid, t_specialites_medecin_2.oid, 0),
                medecin_id = w_medecins.medecin_id
            FROM
                w_medecins
                LEFT JOIN base.t_specialites_medecin ON t_specialites_medecin.code = specialite || '..'
                LEFT JOIN base.t_specialites_medecin t_specialites_medecin_2 ON  t_specialites_medecin_2.code = specialite
            WHERE
                w_medecins.er_codper::text = t_medecins_administratifs.code_original
                AND(t_medecins_administratifs.nom <> w_medecins.nom
                    OR t_medecins_administratifs.prenom <> w_medecins.prenom
                    OR t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid, t_specialites_medecin_2.oid, 0)
                    OR t_medecins_administratifs.medecin_id <> w_medecins.medecin_id);

            UPDATE activite[PX].t_medecins_administratifs
            SET specialite_id = subview.specialite_medecin_id
            FROM
                (
                SELECT t_medecins_administratifs.oid,t_specialites_medecin.oid AS specialite_medecin_id
                FROM activite[PX].t_medecins_administratifs
                JOIN base.t_specialites_medecin t_specialites_medecin_2 ON specialite_id = t_specialites_medecin_2.oid
                JOIN base.t_specialites_medecin ON t_specialites_medecin_2.code || '..'  = t_specialites_medecin.code
                ) subview
            WHERE t_medecins_administratifs.oid = subview.oid;

            UPDATE
                base.t_medecins
            SET
                specialite_id = subview.specialite_id
            FROM (
                SELECT
                    t_medecins.oid,
                    MIN(t_medecins_administratifs.specialite_id) AS specialite_id
                FROM
                    base.t_medecins,
                    activite[PX].t_medecins_administratifs,
                    base.t_specialites_medecin
                WHERE
                    t_medecins.oid = t_medecins_administratifs.medecin_id
                    AND t_medecins_administratifs.specialite_id = t_specialites_medecin.oid
                GROUP BY
                    t_medecins.oid) subview
            WHERE
                t_medecins.oid = subview.oid
                AND t_medecins.specialite_id IS DISTINCT FROM subview.specialite_id
                AND t_medecins.oid <> 0
                AND t_medecins.specialite_id = 0;
            ]]>
            </sqlcmd>
        </NODE>

        <NODE label="Hebergement">
            <sqlcmd><![CDATA[

            -- Services de facturation
            
            INSERT INTO activite[PX].t_services_facturation(oid, code_original, code, texte, texte_court) 
            SELECT 0, 0, '****', 'Non renseigne', 'Non renseigne' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_services_facturation);

            INSERT INTO activite[PX].t_services_facturation (code_original, code, texte, texte_court, type_t2a, mode_traitement_id)
            SELECT
                ts_codsit,
                ts_codsit,
                ts_lib30,
                ts_lib30,
                '0'::text AS type_t2a,
                0 as mode_traitement_id
            FROM
                prod_edlxplore.h_site
            WHERE
                ts_codsit NOT IN(
                    SELECT
                        code_original FROM activite[PX].t_services_facturation);

            -- Unites fonctionnelles
            
            INSERT INTO activite[PX].t_unites_fonctionnelles(oid, code_original, code, texte, texte_court) 
            SELECT 0, 0, '', 'Non renseignee', 'Non renseignee' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_unites_fonctionnelles);
            
            DROP TABLE IF EXISTS w_unites_fonctionnelles;
            CREATE TEMP TABLE w_unites_fonctionnelles AS
            SELECT
                un_codser AS code_original,
                un_codser AS code,
                un_lib30 AS texte
            FROM
                prod_edlxplore.h_unit;

            INSERT INTO activite[PX].t_unites_fonctionnelles (code_original, code, texte, texte_court)
            SELECT
                code_original,
                code,
                texte,
                texte
            FROM
                w_unites_fonctionnelles
            WHERE
                code_original NOT IN(
                    SELECT
                        code_original FROM activite[PX].t_unites_fonctionnelles);
                
            -- Unites medicales = unites fonctionnelles
            INSERT INTO activite[PX].t_unites_medicales (oid, code_original, code, texte, texte_court)
            SELECT
                oid,
                code_original,
                code,
                texte,
                texte
            FROM
                activite[PX].t_unites_fonctionnelles
            WHERE
                oid NOT IN(
                    SELECT
                        oid FROM activite[PX].t_unites_medicales);

            -- Activites 
            INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
            SELECT 
                EM_NATURE,
                EM_NATURE,
                EM_NATURE,
                EM_NATURE
            FROM prod_edlxplore.H_DEMAND
            WHERE 1=1
                AND EM_NATURE <> ''
                AND EM_NATURE NOT IN (SELECT code FROM activite[PX].t_activites)
            GROUP BY 1;

            -- Etages et lits (SOCIETE)

            INSERT INTO activite[PX].t_etages(oid, code_original, code, texte, texte_court, nb_lits) 
            SELECT 0, 0, '', 'Non renseigne', 'Non renseigne', 0 
            WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_etages);

            INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
            SELECT 
                un_codser,
                un_codser,
                un_lib30,
                un_lib30,
                0
            FROM prod_edlxplore.h_unit
            WHERE un_codser <> '' AND un_codser NOT IN (SELECT code FROM activite[PX].t_etages)
            GROUP BY 1, 3
			;

            INSERT INTO activite[PX].t_lits(oid, code_original, code, texte, texte_court, etage_id, chambre_particuliere)
            SELECT 0, '', '***', 'Non renseigne', 'Non renseigne', 0, 'N'
            WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_lits)
			;
			
			INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
			SELECT code_original || '-0' , '', 'Non renseigne', 'Non renseigne', oid, 'N' 
			FROM activite[PX].t_etages
			WHERE oid > 0 AND
				code_original || '-0' NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
			;	
			
            ]]>
            </sqlcmd>
        </NODE>

        <NODE label="Facturation">
            <sqlcmd><![CDATA[
        
            -- Rubriques et prestations

            INSERT INTO activite[PX].t_rubriques_facturation(oid, code_original, code, texte, texte_court) 
            SELECT 0, 0, '', 'Non renseignee', 'Non renseignee' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_rubriques_facturation);

            INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
            SELECT
                hfl_cod_acte,
                hfl_cod_acte,
                hfl_cod_acte,
                hfl_cod_acte
            FROM
                prod_edlxplore.h_faclig
            WHERE
                1 = 1
                AND hfl_typeligne = 'FT'
                AND hfl_cod_acte NOT IN(
                    SELECT
                        code_original FROM activite[PX].t_rubriques_facturation)
            GROUP BY
                1;
            
            INSERT INTO activite.t_prestations (code_original, code, texte, texte_court)
            SELECT
                hfl_cod_acte,
                hfl_cod_acte,
                hfl_cod_acte,
                hfl_cod_acte
            FROM
                prod_edlxplore.h_faclig
            WHERE
                1 = 1
                AND hfl_typeligne = 'FT'
                AND hfl_cod_acte NOT IN(
                    SELECT
                        code_original FROM activite.t_prestations)
            GROUP BY
                1;
                
            
            INSERT INTO activite[PX].t_protocoles(oid, code_original, code, texte, texte_court) 
            SELECT 0, 0, '***', 'Non renseigne', 'Non renseigne' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_protocoles);

            INSERT INTO base.t_actes (code, texte, texte_court, nomenclature)
            SELECT
                UPPER(za_cod_acte),
                MAX(za_nom_long),
                MAX(za_nom_court),
                'CCAM'
            FROM
                prod_edlxplore.z_acte
            WHERE
                za_cod_acte <> ''
                AND UPPER(za_cod_acte)
                NOT IN(
                    SELECT
                        code FROM base.t_actes
                    WHERE
                        code IS NOT NULL)
            GROUP BY
                1;

            
            INSERT INTO activite[PX].t_compte(oid, code_original, code, texte, texte_court) 
            SELECT 0, 0, '', 'Non renseigne', 'Non renseigne' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_compte);
            

            INSERT INTO activite[PX].t_compte (code_original, code, texte, texte_court)
            SELECT
                mc_numcpt,
                mc_numcpt,
                mc_numcpt,
                mc_numcpt
            FROM
                prod_edlxplore.h_mvtcpt
            WHERE
                mc_numcpt <> ''
                AND mc_numcpt NOT IN(
                    SELECT
                        code FROM activite[PX].t_compte
                    WHERE
                        code IS NOT NULL)
            GROUP BY
                1
            ORDER BY
                1;	
            ]]>            </sqlcmd>
        </NODE>

        <NODE label="Tiers payant">
            <sqlcmd><![CDATA[
			
				-- AMO
                INSERT INTO activite[PX].t_tiers_payant (code, code_original, texte, texte_court, code_postal_id, ville, adresse, type_tiers_payant_id, type_tiers_payant)
                SELECT
                    s.code,
                    s.code_original,
                    s.texte,
                    s.texte_court,
                    s.cp,
                    s.ville,
                    s.addr,
                    s.type_tiers_payant_id,
                    s.type_tiers_payant
                FROM (
                    SELECT
                        rg_codorg || 'C' AS code,
                        rg_codorg || 'C' AS code_original,
                        rg_nomorg || '(AMO)' AS texte,
                        rg_nomorg || '(AMO)' AS texte_court,
                        t_codes_postaux.oid AS cp,
                        rg_ville AS ville,
                        rg_adr_1 || ' ' || rg_adr_2 AS addr,
                        1 AS type_tiers_payant_id,
						'1'::text AS type_tiers_payant,
                        ROW_NUMBER() OVER (PARTITION BY rg_codorg || 'C') AS rn
                    FROM
                        prod_edlxplore.h_organ
                    LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = rg_codpos
					WHERE
						1 = 1
						AND rg_typorg = 'C'
						AND rg_codorg IN(
						SELECT
							em_numcai FROM prod_edlxplore.H_DEMAND)
						AND rg_codorg || 'C' NOT IN(SELECT code_original FROM activite[PX].t_tiers_payant)
					GROUP BY
						1,
						3,
						5,
						6,
						7
					) s
                WHERE
                    rn = 1;
            
			
				-- AMC
                INSERT INTO activite[PX].t_tiers_payant (code, code_original, texte, texte_court, code_postal_id, ville, adresse, type_tiers_payant_id, type_tiers_payant)
                SELECT
                    s.code,
                    s.code_original,
                    s.texte,
                    s.texte_court,
                    s.cp,
                    s.ville,
                    s.addr,
                    s.tiers_payant_id,
                    s.type_tiers_payant
                FROM (
                    SELECT
                        rg_codorg || 'M' AS code,
                        rg_codorg || 'M' AS code_original,
                        rg_nomorg || '(AMC)' AS texte,
                        rg_nomorg || '(AMC)' AS texte_court,
                        t_codes_postaux.oid AS cp,
                        rg_ville AS ville,
                        rg_adr_1 || ' ' || rg_adr_2 AS addr,
                        2 AS tiers_payant_id,
						'2'::text AS type_tiers_payant,
                        ROW_NUMBER() OVER (PARTITION BY rg_codorg || 'M') AS rn
                    FROM
                        prod_edlxplore.h_organ
                    LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = rg_codpos
					WHERE
						1 = 1
						AND rg_typorg = 'M'
						AND rg_codorg IN(
						SELECT
							em_nummut FROM prod_edlxplore.H_DEMAND)
						AND rg_codorg || 'M' NOT IN(SELECT code_original FROM activite[PX].t_tiers_payant)
					GROUP BY
						1,
						3,
						5,
						6,
						7
					) s
                WHERE
                    rn = 1;
					
				-- PATIENT
				INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, type_tiers_payant_id, texte, texte_court) 
				SELECT 'PATIENT', 'PATIENT', '0', 0, 'PATIENTS', 'PATIENTS'
				WHERE 'PATIENT' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);
				
				-- Grand regime
				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM prod_edlxplore.H_ORGAN
				JOIN base.t_grands_regimes ON RG_CODREG = t_grands_regimes.code
				WHERE t_tiers_payant.code_original = (RG_CODORG || 'C') AND
					grand_regime_id IS DISTINCT FROM t_grands_regimes.oid
				;

				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM prod_edlxplore.H_ORGAN
				JOIN base.t_grands_regimes ON RG_CODREG = t_grands_regimes.code
				WHERE t_tiers_payant.code_original = (RG_CODORG || 'M') AND
					grand_regime_id IS DISTINCT FROM t_grands_regimes.oid
				;

            ]]>
            </sqlcmd>
        </NODE>

    </NODE>

    <NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
	
		<NODE label="Selection">
			<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_H_DEMAND_select;
				CREATE TEMP TABLE w_H_DEMAND_select AS
				SELECT *,
					100 - EM_TAUCAI - EM_TAUMUT AS EM_TAUPAT,
					CASE WHEN EM_DATARR >= '[ENV_ADM_ANNEEDEBUT]0101' THEN 'OK' ELSE ''::text END AS OK
				FROM prod_edlxplore.H_DEMAND
				WHERE EM_CODSIT <> 'XA'
				;

				ANALYSE w_H_DEMAND_select
				;

				UPDATE w_H_DEMAND_select
				SET OK = 'OK'
				WHERE OK = '' AND
					EM_NUMDEM IN (SELECT HF_NUMDEM FROM prod_edlxplore.H_HISFAC WHERE HF_DATFAC >= '[ENV_ADM_ANNEEDEBUT]0101')
				;

				UPDATE w_H_DEMAND_select
				SET OK = 'OK'
				WHERE OK = '' AND
					EM_NUMDEM IN (SELECT GG_NUMDEM FROM prod_edlxplore.H_REGLEM WHERE GG_DATREG >= '[ENV_ADM_ANNEEDEBUT]0101')
				;
				
				UPDATE w_H_DEMAND_select
				SET OK = 'OK'
				WHERE OK = '' AND
					EM_NUMDEM IN (SELECT MC_TABIDX FROM prod_edlxplore.H_MVTCPT WHERE MC_PERIODE >= '[ENV_ADM_ANNEEDEBUT]0101')
				;

				DELETE FROM w_H_DEMAND_select
				WHERE OK = ''
				;

				VACUUM FULL ANALYSE w_H_DEMAND_select
				;
			]]>
            </sqlcmd>
        </NODE>
		
        <NODE label="Patients">
            <sqlcmd><![CDATA[
			
				-- NIP
				DROP TABLE IF EXISTS w_H_PATIEN_numper;
				CREATE TEMP TABLE w_H_PATIEN_numper AS 
				SELECT AT_NOMPAT, AT_PNOPAT, AT_DATNAI, AT_SEXE, MAX(AT_NUMPER) AS AT_NUMPER
				FROM prod_edlxplore.H_PATIEN
				GROUP BY 1,2,3,4
				;

				ANALYSE w_H_PATIEN_numper
				;

				INSERT INTO w_H_PATIEN_numper
				SELECT H_PATIEN.AT_NJFPAT, H_PATIEN.AT_PNOPAT, H_PATIEN.AT_DATNAI, H_PATIEN.AT_SEXE, MAX(H_PATIEN.AT_NUMPER)
				FROM prod_edlxplore.H_PATIEN
				LEFT JOIN w_H_PATIEN_numper ON
					H_PATIEN.AT_NJFPAT = w_H_PATIEN_numper.AT_NOMPAT AND
					H_PATIEN.AT_PNOPAT = w_H_PATIEN_numper.AT_PNOPAT AND
					H_PATIEN.AT_DATNAI = w_H_PATIEN_numper.AT_DATNAI AND
					H_PATIEN.AT_SEXE = w_H_PATIEN_numper.AT_SEXE
				WHERE H_PATIEN.AT_NJFPAT <> '' AND 
					left(H_PATIEN.AT_NJFPAT,1) BETWEEN 'A' AND 'Z' AND
					length(AT_NJFPAT) > 2 AND
					H_PATIEN.AT_NJFPAT <> H_PATIEN.AT_NOMPAT AND
					w_H_PATIEN_numper.AT_NUMPER IS NULL 
				GROUP BY 1,2,3,4
				;

				-- Si pas de NIP, creation numero provisoire
				UPDATE w_H_PATIEN_numper
				SET AT_NUMPER = subview.AT_NUMPER
				FROM
				(
				SELECT 
					AT_NOMPAT, 
					AT_PNOPAT, 
					AT_DATNAI, 
					AT_SEXE, 
					'Z'::text || to_char(AT_DATNAI,'YYMMDD') || AT_SEXE::text || to_char(rank() OVER (PARTITION BY to_char(AT_DATNAI,'YYMMDD'), AT_SEXE ORDER BY AT_NOMPAT, AT_PNOPAT),'FM990') AS AT_NUMPER
				FROM w_H_PATIEN_numper
				WHERE AT_NUMPER = ''
				) subview
				WHERE subview.AT_NOMPAT = w_H_PATIEN_numper.AT_NOMPAT AND
					subview.AT_PNOPAT = w_H_PATIEN_numper.AT_PNOPAT AND
					subview.AT_DATNAI = w_H_PATIEN_numper.AT_DATNAI AND
					subview.AT_SEXE = w_H_PATIEN_numper.AT_SEXE AND
					w_H_PATIEN_numper.AT_NUMPER = ''
					;

		
				UPDATE prod_edlxplore.H_PATIEN
				SET AT_NUMPER = w_H_PATIEN_numper.AT_NUMPER
				FROM w_H_PATIEN_numper
				WHERE H_PATIEN.AT_NUMPER = '' AND
					w_H_PATIEN_numper.AT_NUMPER <> '' AND
					H_PATIEN.AT_NOMPAT = w_H_PATIEN_numper.AT_NOMPAT AND
					H_PATIEN.AT_PNOPAT = w_H_PATIEN_numper.AT_PNOPAT AND
					H_PATIEN.AT_DATNAI = w_H_PATIEN_numper.AT_DATNAI AND
					H_PATIEN.AT_SEXE = w_H_PATIEN_numper.AT_SEXE
					;

				UPDATE prod_edlxplore.H_PATIEN
				SET AT_NUMPER = w_H_PATIEN_numper.AT_NUMPER
				FROM w_H_PATIEN_numper
				WHERE H_PATIEN.AT_NUMPER = '' AND
					w_H_PATIEN_numper.AT_NUMPER <> '' AND
					H_PATIEN.AT_NJFPAT = w_H_PATIEN_numper.AT_NOMPAT AND
					H_PATIEN.AT_PNOPAT = w_H_PATIEN_numper.AT_PNOPAT AND
					H_PATIEN.AT_DATNAI = w_H_PATIEN_numper.AT_DATNAI AND
					H_PATIEN.AT_SEXE = w_H_PATIEN_numper.AT_SEXE
					;


				TRUNCATE activite[PX].p_patients
				;

				INSERT INTO activite[PX].p_patients (no_patient, nom, nom_naissance, prenom, date_naissance, code_sexe)
				SELECT
					AT_NUMPER,
					(MAX(ARRAY[AT_NUMDOS,AT_NOMPAT]))[2],
					(MAX(ARRAY[AT_NUMDOS,AT_PNOPAT]))[2],
					(MAX(ARRAY[AT_NUMDOS,AT_NJFPAT]))[2],
					date(MAX(AT_DATNAI)),
					MAX(CASE WHEN AT_SEXE = 0 THEN '2' ELSE '1' END) AS sexe
				FROM prod_edlxplore.H_PATIEN
				WHERE AT_NUMDOS IN (SELECT EM_NUMDOS FROM w_H_DEMAND_select)
				GROUP BY 1
				;
            ]]>
            </sqlcmd>
        </NODE>

        <NODE label="Sejours">
            <sqlcmd><![CDATA[
			
				-- Lieux
			
				INSERT INTO activite[PX].t_lieux(
                    code_original_1, 
                    code_original_2, 
                    code_original_3, 
                    code_original_4, 
                    code_original_5, 
                    code_original_6, 
                    code_original_7,
                    service_facturation_id, 
                    activite_id, 
                    lit_id, 
                    unite_medicale_id, 
                    unite_fonctionnelle_id, 
                    mode_traitement_id)
				SELECT
                    EM_CODSIT, 
                    EM_NATURE,
                    '',
                    EM_CODSER,
                    EM_CODSER,
                    EM_CODSER,
                    '',
                    0 as service_facturation_id,
                    0,
                    0,
                    0,
                    0,
                    0
                FROM w_H_DEMAND_select H_DEMAND
                LEFT JOIN activite[PX].t_lieux ON 
                    t_lieux.code_original_1 = EM_CODSIT AND 
                    t_lieux.code_original_2 = EM_NATURE AND 
                    t_lieux.code_original_4 = EM_CODSER AND
                    t_lieux.code_original_5 = EM_CODSER AND
                    t_lieux.code_original_6 = EM_CODSER
                WHERE t_lieux.oid IS NULL
                GROUP BY EM_CODSIT, EM_CODSER, EM_NATURE
				;
				

                UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0) 
				FROM activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original
					AND (t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
				;
				
				UPDATE activite[PX].t_lieux SET
					activite_id = COALESCE(t_activites.oid,0)
				FROM activite[PX].t_activites 
				WHERE code_original_2 = t_activites.code_original AND
					t_lieux.activite_id <> COALESCE(t_activites.oid,0)
				;
				
				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM activite[PX].t_lits
				WHERE code_original_4||'-'||'0' = t_lits.code_original
					AND lit_id <> COALESCE(t_lits.oid,0)
				;

				UPDATE activite[PX].t_lieux SET
					unite_medicale_id = COALESCE(t_unites_medicales.oid,0)
				FROM activite[PX].t_unites_medicales
				WHERE code_original_5 = t_unites_medicales.code_original
					AND unite_medicale_id <> COALESCE(t_unites_medicales.oid,0)
				;

				
				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0)
				;
				

				-- Sejours
				DROP TABLE IF EXISTS w_sejours;
				
				CREATE TEMP TABLE w_sejours AS
				SELECT 
					H_DEMAND.em_numdem AS no_sejour, 
					H_DEMAND.em_numdem AS code_original, 
					H_PATIEN.AT_NUMPER AS no_patient, 
					H_DEMAND.em_DATARR AS date_entree, 
					REPLACE(H_DEMAND.em_HEUARR, ':', '') || '00' AS heure_entree,
					H_DEMAND.em_DATARR AS date_sortie,
					REPLACE(H_DEMAND.em_HEUARR, ':', '') || '00' AS heure_sortie, 
					CASE WHEN H_PATIEN.at_prefix ILIKE 'Mr%' THEN '1' ELSE '2' END AS code_sexe ,
					EXTRACT(YEAR FROM AGE(H_PATIEN.at_datnai)) AS age,
					1 AS code_sorti, 
					0 AS code_prevu,
					CASE em_etape WHEN 'S' THEN '9'::text ELSE '3'::text END AS type_sejour,
					COALESCE(t_codes_postaux.oid,0) AS code_postal_id,
					CASE WHEN t_sejour.medecin_sejour_id <> 0 THEN t_sejour.medecin_sejour_id ELSE COALESCE(t_medecins_administratifs.oid,0) END AS medecin_sejour_id,
					0 as ghm_id,
					0 AS ghs_id,
					'20991231'::date AS date_groupage,
					0::numeric AS code_cp_demandee,
					0 AS mode_traitement_id,
					CASE WHEN em_codser IN ('EXT', '') THEN '8'::character(1) ELSE '0'::character(1) END AS mode_entree,
					'0'::character(1) AS provenance,
					CASE WHEN em_codser IN ('EXT', '') THEN '8'::character(1) ELSE '0'::character(1) END AS mode_sortie,
					'0'::character(1) AS destination,
					COALESCE(t_tiers_payant_0.oid, 0) AS tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid, 0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid, 0) AS tiers_payant_2_id,
					0 AS tiers_payant_22_id,
					0 AS est_budget_global,
					em_finess AS finess,
					CASE WHEN t_sejour.est_ignore = '1' THEN 'I' ELSE '' END AS etat,
					em_codsit as service_facturation,
					em_codsit as uf,
					COALESCE(t_lieux.oid, 0) as lieu_sortie_id
				FROM w_H_DEMAND_select H_DEMAND
				JOIN prod_edlxplore.H_PATIEN ON H_PATIEN.at_numdos = H_DEMAND.em_numdos
				LEFT JOIN base.t_codes_postaux ON H_PATIEN.at_codpos = t_codes_postaux.code
				LEFT JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original = H_DEMAND.em_codtit
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON H_DEMAND.em_numcai::text || 'C' = t_tiers_payant_1.code_original
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON H_DEMAND.em_nummut::text || 'M' = t_tiers_payant_2.code_original
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON t_tiers_payant_0.code_original = 'PATIENT' 
				LEFT JOIN activite.t_sejour ON t_sejour.no_sejour = H_DEMAND.em_numdem
				LEFT JOIN activite[PX].t_lieux ON 
					t_lieux.code_original_1 = H_DEMAND.EM_CODSIT AND
					t_lieux.code_original_2 = H_DEMAND.EM_NATURE AND
					t_lieux.code_original_4 = H_DEMAND.EM_CODSER AND
					t_lieux.code_original_5 = H_DEMAND.EM_CODSER AND
					t_lieux.code_original_6 = H_DEMAND.EM_CODSER
				;
					
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_13');
				
						
				INSERT INTO activite[PX].p_sejours (
					no_sejour, 
					code_original, 
					no_patient, 
					date_entree, 
					heure_entree, 
					date_sortie, 
					heure_sortie, 
					code_sexe, 
					age, 
					code_sorti, 
					code_prevu, 
					type_sejour, 
					code_postal_id,
					medecin_sejour_id,
					date_groupage,
					code_cp_demandee,
					mode_traitement_id,
					mode_entree,
					provenance,
					mode_sortie,
					destination,
					ghm_id,
					ghs_id,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					est_budget_global,
					finess,
					etat,
					lieu_sortie_id
				) 
				SELECT 
					w_sejours.no_sejour, 
					w_sejours.code_original,
					w_sejours.no_patient, 
					w_sejours.date_entree, 
					w_sejours.heure_entree::numeric, 
					w_sejours.date_sortie, 
					w_sejours.heure_sortie::numeric, 
					w_sejours.code_sexe::char(1),
					w_sejours.age, 
					w_sejours.code_sorti, 
					w_sejours.code_prevu, 
					w_sejours.type_sejour::char(1), 
					w_sejours.code_postal_id,
					w_sejours.medecin_sejour_id,
					w_sejours.date_groupage,
					w_sejours.code_cp_demandee, 
					w_sejours.mode_traitement_id,
					w_sejours.mode_entree::char(1),
					w_sejours.provenance::char(1),
					w_sejours.mode_sortie::char(1),
					w_sejours.destination::char(1),
					w_sejours.ghm_id,
					w_sejours.ghs_id,
					w_sejours.tiers_payant_0_id,
					w_sejours.tiers_payant_1_id,
					w_sejours.tiers_payant_2_id,
					w_sejours.tiers_payant_22_id,
					w_sejours.est_budget_global,
					w_sejours.finess,
					w_sejours.etat,
					w_sejours.lieu_sortie_id
				FROM w_sejours
				;
				
				ANALYSE activite[PX].p_sejours
				;
			
				-- recreation index
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_13');


				-- assurance
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_4');
				
				INSERT INTO activite[PX].p_sejours_assurance (sejour_id, tiers_payant_0_id, tiers_payant_1_id, matricule_1, tiers_payant_2_id, matricule_2, tiers_payant_22_id, matricule_22)
				SELECT
					oid AS sejour_id,
					p_sejours.tiers_payant_0_id,
					p_sejours.tiers_payant_1_id,
					at_numss,
					p_sejours.tiers_payant_2_id,
					'',
					p_sejours.tiers_payant_22_id,
					''::text AS matricule_22
				FROM
					activite[PX].p_sejours
					LEFT JOIN prod_edlxplore.H_PATIEN ON H_PATIEN.at_numdos = p_sejours.no_patient
				WHERE
					p_sejours.etat = '';

				
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_4');
             ]]>            
			 </sqlcmd>
        </NODE>

        <NODE label="Mouvements">
            <sqlcmd><![CDATA[

            DROP TABLE IF EXISTS w_mouvements_sejour;
            CREATE TEMP TABLE w_mouvements_sejour AS
            SELECT
                p_sejours.no_sejour,
                p_sejours.oid AS sejour_id,
                p_calendrier.date,
                p_calendrier.jour_semaine,
                p_calendrier.is_weekend,
                p_sejours.heure_entree AS heure_debut,
                p_sejours.heure_sortie AS heure_fin,
                0::numeric AS nb_entrees_directes,
                0::numeric AS nb_sorties_directes,
                1::numeric AS est_jour_entree,
                1::numeric AS est_jour_sortie,
                '0'::text AS est_jour_hospitalisation,
                0::numeric AS nb_ambulatoires,
                1::numeric AS nb_externes,
                0::numeric AS nb_urgences,
                0::numeric AS nb_seances,
                0::numeric AS nb_entrees_mutation_service,
                0::numeric AS nb_sorties_mutation_service,
                0::numeric AS nb_entrees_mutation_etage,
                0::numeric AS nb_sorties_mutation_etage,
                0::numeric AS nb_entrees_mutation_activite,
                0::numeric AS nb_sorties_mutation_activite,
                0::numeric AS nb_entrees_mutation_unite_medicale,
                0::numeric AS nb_sorties_mutation_unite_medicale,
                0::numeric AS nb_jours_js_inclus,
                0::numeric AS nb_jours_js_non_inclus,
                '0'::text AS est_chambre_particuliere,
                0::numeric AS nb_chambres_particulieres,
                0::numeric AS nb_bebes,
                lieu_sortie_id AS lieu_id,
                p_sejours.medecin_sejour_id AS medecin_sejour_id,
                '0'::text AS est_mouvement_previsionnel,
                ''::text AS est_premier_mouvement_jour,
                ''::text AS est_dernier_mouvement_jour
            FROM activite[PX].p_sejours
			JOIN base.p_calendrier ON 
				p_calendrier.date = p_sejours.date_entree
				AND p_calendrier.date <= date(now())
            WHERE p_sejours.etat = ''
			;

            -- Mise en production des mouvements
            SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_1');
            SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_2');
            SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_3');
            SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_4');
            SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_5');
        
        
            INSERT INTO activite[PX].p_mouvements_sejour (
                sejour_id,
                no_sejour,
                date,
                est_mouvement_previsionnel,
                nb_jours_js_non_inclus, 
                lieu_id, nb_entrees_directes,
                nb_sorties_directes,
                nb_urgences,
                nb_externes,
                nb_ambulatoires,
                medecin_sejour_id,
                nb_jours_js_inclus,
                nb_seances,
                nb_entrees_mutation_service,
                nb_sorties_mutation_service, 
                nb_entrees_mutation_activite,
                nb_sorties_mutation_activite,
                nb_entrees_mutation_etage,
                nb_sorties_mutation_etage,
                nb_chambres_particulieres,
                heure_debut,
                heure_fin,
                est_jour_entree,
                est_jour_sortie,
                est_jour_hospitalisation,
                est_chambre_particuliere,
                nb_entrees_mutation_unite_medicale,
                nb_sorties_mutation_unite_medicale,
                nb_bebes,
                jour_semaine,
                is_weekend
                )
            SELECT
                sejour_id,
                no_sejour,
                date,
                est_mouvement_previsionnel,
                nb_jours_js_non_inclus,
                lieu_id,
                nb_entrees_directes,
                nb_sorties_directes,
                nb_urgences,
                nb_externes,
                nb_ambulatoires,
                medecin_sejour_id,
                nb_jours_js_inclus,
                nb_seances,
                nb_entrees_mutation_service,
                nb_sorties_mutation_service,
                nb_entrees_mutation_activite,
                nb_sorties_mutation_activite,
                nb_entrees_mutation_etage,
                nb_sorties_mutation_etage,
                nb_chambres_particulieres,
                heure_debut,
                heure_fin,
                est_jour_entree,
                est_jour_sortie,
                est_jour_hospitalisation,
                est_chambre_particuliere,
                nb_entrees_mutation_unite_medicale,
                nb_sorties_mutation_unite_medicale,
                nb_bebes,
                jour_semaine,
                is_weekend
            FROM
                w_mouvements_sejour
            WHERE
                heure_fin >= heure_debut
            ORDER BY
                no_sejour;
            
            
            SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_1');
            SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_2');
            SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_3');
            SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_4');
            SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_5');
            
            ANALYSE activite[PX].p_mouvements_sejour
            ;
            ]]>            </sqlcmd>
        </NODE>

    </NODE>

    <NODE name="FACTURE" label="RECUPERATION DES FACTURES">

        <NODE label="Entetes">

            <sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_H_HISFAC;
				CREATE TEMP TABLE w_H_HISFAC AS
				SELECT H_HISFAC.*, 
					HF_IDFAC AS HF_IDFAC_source,
					'20991231'::date AS HF_DATENV,
					1::numeric AS sens_facture,
					0::numeric AS rang
				FROM prod_edlxplore.H_HISFAC
				JOIN activite[PX].p_sejours ON HF_NUMDEM = no_sejour
				;

				INSERT INTO w_H_HISFAC
				SELECT H_HISFAC.*, 
					HF_IDFAC AS HF_IDFAC_source,
					'20991231'::date AS HF_DATENV,
					-1::numeric AS sens_facture,
					0::numeric AS rang
				FROM prod_edlxplore.H_HISFAC
				JOIN activite[PX].p_sejours ON HF_NUMDEM = no_sejour
				WHERE HF_DATANN IS NOT NULL
				;

				UPDATE w_H_HISFAC SET
					HF_IDFAC = HF_IDFAC || '.' || to_char(HF_NUMORD,'FM990') || CASE WHEN sens_facture < 0 THEN 'A' ELSE '' END,
					HF_DATFAC = CASE WHEN sens_facture < 0 THEN HF_DATANN ELSE HF_DATFAC END,
					HF_FACTUR = HF_FACTUR * sens_facture
				;
				
				ANALYSE w_H_HISFAC
				;


				UPDATE w_H_HISFAC
				SET HF_DATENV = date(subview.B6_DATENV)
				FROM
				(
				SELECT HF_NUM_HF, MAX(B6_DATENV) AS B6_DATENV
				FROM prod_edlxplore.H_DET615
				JOIN prod_edlxplore.H_BORD615 ON D6_NUMBOT = B6_NUMBOT
				JOIN w_H_HISFAC ON D6_NUMDEM = HF_NUMDEM
				GROUP BY 1
				) subview
				WHERE w_h_HISFAC.HF_NUM_HF = subview.HF_NUM_HF
				;
				
				-- Factures qui ne sont pas dans H_HISFAC
				-- Reconstruction car pas de table dediee trouvee
				UPDATE prod_edlxplore.H_MVTCPT
				SET MC_NUMCPT = '41XXXX'
				WHERE MC_NUMCPT NOT LIKE '41%' AND MC_LIBCPT_C = 'Collectif clients'
				;

				DROP TABLE IF EXISTS w_H_HISFAC_autre;
				CREATE TEMP TABLE w_H_HISFAC_autre AS
				SELECT MC_NUMPIECE || MC_CATECR AS HF_NUM_HF,
					MC_NUMPIECE,
					MC_TYPECR,
					MC_TABIDX AS HF_NUMDEM, 
					date(EM_DATARR) AS HF_DATARR,
					CASE WHEN MC_CATECR = 'E' THEN 'F' ELSE 'H' END AS HF_PART,
					0::numeric AS HF_NUMORD,
					SUM(CASE WHEN MC_NUMCPT NOT LIKE '41%' THEN MC_MTCREDIT - MC_MTDEBIT ELSE 0 END) AS HF_FACTUR,
					MC_NUMFAC::text AS HF_IDFAC,
					MC_NUMFAC::text AS HF_IDFAC_source,
					MC_PERIODE AS HF_DATFAC,
					'20991231'::date AS HF_DATENV,
					''::text AS HF_NUMBOT,
					CASE WHEN SUM(CASE WHEN MC_NUMCPT NOT LIKE '41%' THEN MC_MTCREDIT - MC_MTDEBIT ELSE 0 END) > 0 THEN 1 ELSE -1 END AS sens_facture,
					0::numeric AS rang
				FROM prod_edlxplore.H_MVTCPT
				JOIN w_H_DEMAND_select ON MC_TABIDX = EM_NUMDEM
				JOIN activite[PX].p_sejours ON MC_TABIDX = no_sejour
				WHERE MC_NUMCPT NOT LIKE '41%' AND
					MC_CODJRN LIKE 'VENTE%' AND
					MC_TABIDX NOT IN (SELECT HF_NUMDEM FROM w_H_HISFAC) 
				GROUP BY MC_NUMPIECE, MC_CATECR, MC_PERIODE, MC_NUMFAC, MC_TABIDX, EM_DATARR, MC_TYPECR
				HAVING SUM(CASE WHEN MC_NUMCPT NOT LIKE '41%' THEN MC_MTCREDIT - MC_MTDEBIT ELSE 0 END) <> 0
				;

				ANALYSE w_H_HISFAC_autre
				;


				UPDATE w_H_HISFAC_autre SET
					HF_DATENV = date(subview.B6_DATENV),
					HF_NUMBOT = subview.D6_NUMBOT
				FROM
				(
				SELECT HF_NUM_HF, 
					MAX(B6_DATENV) AS B6_DATENV,
					(MAX(ARRAY[B6_DATENV::text, D6_NUMBOT]))[2] AS D6_NUMBOT
				FROM prod_edlxplore.H_DET615
				JOIN prod_edlxplore.H_BORD615 ON D6_NUMBOT = B6_NUMBOT
				JOIN w_H_HISFAC_autre ON D6_NUMDEM = HF_NUMDEM
				GROUP BY 1
				) subview
				WHERE w_h_HISFAC_autre.HF_NUM_HF = subview.HF_NUM_HF
				;


				DROP TABLE IF EXISTS w_H_HISFAC_ord;
				CREATE TEMP TABLE w_H_HISFAC_ord AS
				SELECT *,
					row_number() OVER(PARTITION BY HF_NUMDEM ORDER BY MC_NUMPIECE, HF_DATFAC) AS HF_NUMORD,
					COALESCE(lead(MC_NUMPIECE) OVER (PARTITION BY HF_NUMDEM ORDER BY MC_NUMPIECE, HF_DATFAC),'Z99999999999') AS MC_NUMPIECE_next
				FROM
				(
				SELECT HF_NUMDEM, MC_NUMPIECE, HF_DATFAC, MC_TYPECR
				FROM w_H_HISFAC_autre
				WHERE MC_TYPECR = 'Facture'
				GROUP BY 1,2,3,4
				) subview
				;

				ANALYSE w_H_HISFAC_ord
				;

				INSERT INTO w_H_HISFAC_ord
				SELECT w_H_HISFAC_autre.HF_NUMDEM, w_H_HISFAC_autre.MC_NUMPIECE, w_H_HISFAC_autre.HF_DATFAC, w_H_HISFAC_autre.MC_TYPECR, MAX(w_H_HISFAC_ord.HF_NUMORD), ''::text
				FROM w_H_HISFAC_autre
				LEFT JOIN w_H_HISFAC_ord ON w_H_HISFAC_autre.HF_NUMDEM = w_H_HISFAC_ord.HF_NUMDEM AND
					w_H_HISFAC_autre.MC_NUMPIECE > w_H_HISFAC_ord.MC_NUMPIECE AND
					w_H_HISFAC_autre.MC_NUMPIECE < w_H_HISFAC_ord.MC_NUMPIECE_next
				WHERE w_H_HISFAC_autre.MC_TYPECR = 'Avoir' 
				GROUP BY 1,2,3,4
				;

				UPDATE w_H_HISFAC_autre
				SET HF_NUMORD = w_H_HISFAC_ord.HF_NUMORD
				FROM w_H_HISFAC_ord
				WHERE w_H_HISFAC_autre.MC_NUMPIECE = w_H_HISFAC_ord.MC_NUMPIECE
				;

				UPDATE w_H_HISFAC_autre SET
					HF_IDFAC = HF_IDFAC || '.' || to_char(HF_NUMORD,'FM990') || CASE WHEN sens_facture < 0 THEN 'A' ELSE '' END
				;

        
				-- Ajout des factures
				
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_14');

				INSERT INTO activite[PX].p_factures(
					sejour_id,
					no_sejour, 
					no_facture, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					code_vente, 
					date_vente, 
					mois_vente, 
					date_solde, 
					montant_facture_c, 
					montant_facture_h, 
					montant_regle_c, 
					montant_regle_h, 
					delai_facture, 
					delai_solde, 
					date_expedition, 
					delai_expedition, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					date_solde_0_c, 
					date_solde_0_h, 
					date_solde_1_c, 
					date_solde_1_h, 
					date_solde_2_c, 
					date_solde_2_h, 
					date_solde_22_c, 
					date_solde_22_h, 
					date_expedition_0, 
					date_expedition_1, 
					date_expedition_2, 
					date_expedition_22, 
					code_expedie_0, 
					code_expedie_1, 
					code_expedie_2, 
					code_expedie_22, 
					no_bordereau_0, 
					no_bordereau_1, 
					no_bordereau_2, 
					no_bordereau_22, 
					montant_facture_0_c,
					montant_facture_0_h, 
					montant_facture_1_c, 
					montant_facture_1_h, 
					montant_facture_2_c, 
					montant_facture_2_h, 
					montant_facture_22_c, 
					montant_facture_22_h, 
					montant_regle_0_c, 
					montant_regle_0_h, 
					montant_regle_1_c, 
					montant_regle_1_h, 
					montant_regle_2_c, 
					montant_regle_2_h, 
					montant_regle_22_c, 
					montant_regle_22_h, 
					delai_expedition_0, 
					delai_expedition_1, 
					delai_expedition_2, 
					delai_expedition_22, 
					delai_solde_0_c, 
					delai_solde_0_h, 
					delai_solde_1_c, 
					delai_solde_1_h, 
					delai_solde_2_c, 
					delai_solde_2_h, 
					delai_solde_22_c, 
					delai_solde_22_h, 
					ghs_id, 
					particularite_t2a, 
					code_cloture, 
					code_cp_demandee, 
					ghs_bebe1_id, 
					ghs_bebe2_id, 
					ghs_bebe3_id,
					montant_comptabilise_c, 
					montant_comptabilise_h, 
					montant_comptabilise_0_c,
					montant_comptabilise_0_h, 
					montant_comptabilise_1_c, 
					montant_comptabilise_1_h, 
					montant_comptabilise_2_c, 
					montant_comptabilise_2_h, 
					montant_comptabilise_22_c, 
					montant_comptabilise_22_h,
					nb_rejets,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour
					)         
				 SELECT
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					HF_IDFAC AS no_facture,
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					MAX(CASE WHEN H_HISFAC.sens_facture > 0 THEN '0'::text ELSE '1' END) AS type_facture,
					'1'::text AS code_facture,
					MAX(HF_DATFAC) AS date_facture,
					'1'::text AS code_vente,
					MAX(HF_DATFAC) as date_vente,
					MAX(to_char(HF_DATFAC,'YYYYMM')::numeric) AS mois_vente,
					'2099-12-31' AS date_solde, 
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END) AS montant_facture_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END) AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture, 
					0::numeric AS delai_solde, 
					MAX(HF_DATENV) as date_expedition, 
					0::numeric AS delai_expedition, 
					MAX(p_sejours.tiers_payant_0_id),
					MAX(p_sejours.tiers_payant_1_id),
					MAX(p_sejours.tiers_payant_2_id),
					0::bigint AS tiers_payant_22_id,	
					'2099-12-31' AS date_solde_0_c,     
					'2099-12-31' AS date_solde_0_h,     
					'2099-12-31' AS date_solde_1_c, 
					'2099-12-31' AS date_solde_1_h,	   
					'2099-12-31' AS date_solde_2_c,
					'2099-12-31' AS date_solde_2_h,
					'2099-12-31' AS date_solde_22_c,
					'2099-12-31' AS date_solde_22_h,
					'2099-12-31' AS date_expedition_0,
					MAX(HF_DATENV) AS date_expedition_1,
					MAX(HF_DATENV) AS date_expedition_2,
					'2099-12-31' AS date_expedition_22,
					'0'::text AS code_expedie_0,
					MAX(CASE WHEN HF_DATENV < '20991231' THEN '1'::text ELSE '0'::text END) AS code_expedie_1,
					MAX(CASE WHEN HF_DATENV < '20991231' THEN '1'::text ELSE '0'::text END) AS code_expedie_2,
					'0'::text AS code_expedie_22,
					'' AS no_bordereau_0,
					MAX(HF_NUMBOT) AS no_bordereau_1,
					MAX(HF_NUMBOT) AS no_bordereau_2,
					'' AS no_bordereau_22,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_facture_0_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_facture_0_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_facture_1_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_facture_1_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_facture_2_c,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_facture_2_h,
					0 AS montant_facture_22_c,
					0 AS montant_facture_22_h,
					0 AS montant_regle_0_c,
					0 AS montant_regle_0_h,
					0 AS montant_regle_1_c,
					0 AS montant_regle_1_h,
					0 AS montant_regle_2_c,
					0 AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0 AS delai_expedition_0, 
					0 AS delai_expedition_1, 
					0 AS delai_expedition_2, 
					0 AS delai_expedition_22, 
					0 AS delai_solde_0_c, 
					0 AS delai_solde_0_h, 
					0 AS delai_solde_1_c, 
					0 AS delai_solde_1_h, 
					0 AS delai_solde_2_c, 
					0 AS delai_solde_2_h, 
					0 AS delai_solde_22_c, 
					0 AS delai_solde_22_h, 
					0 AS ghs_id,
					'' as particularite_t2a, 
					'0' as code_cloture,
					'0' as code_cp_demandee, 
					0 AS ghs_bebe1_id, 
					0 AS ghs_bebe2_id, 
					0 AS ghs_bebe3_id,
					0 AS montant_comptabilise_c, 
					0 AS montant_comptabilise_h, 
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_comptabilise_0_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_comptabilise_0_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_comptabilise_1_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_comptabilise_1_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_comptabilise_2_c,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					0::numeric AS nb_rejets,
					0,
					0
				FROM w_H_HISFAC H_HISFAC
				JOIN activite[PX].p_sejours ON HF_NUMDEM = p_sejours.code_original
				JOIN w_H_DEMAND_select H_DEMAND  ON HF_NUMDEM = EM_NUMDEM
				GROUP BY 1,2,3
				;
				
				INSERT INTO activite[PX].p_factures(
					sejour_id,
					no_sejour, 
					no_facture, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					code_vente, 
					date_vente, 
					mois_vente, 
					date_solde, 
					montant_facture_c, 
					montant_facture_h, 
					montant_regle_c, 
					montant_regle_h, 
					delai_facture, 
					delai_solde, 
					date_expedition, 
					delai_expedition, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					date_solde_0_c, 
					date_solde_0_h, 
					date_solde_1_c, 
					date_solde_1_h, 
					date_solde_2_c, 
					date_solde_2_h, 
					date_solde_22_c, 
					date_solde_22_h, 
					date_expedition_0, 
					date_expedition_1, 
					date_expedition_2, 
					date_expedition_22, 
					code_expedie_0, 
					code_expedie_1, 
					code_expedie_2, 
					code_expedie_22, 
					no_bordereau_0, 
					no_bordereau_1, 
					no_bordereau_2, 
					no_bordereau_22, 
					montant_facture_0_c,
					montant_facture_0_h, 
					montant_facture_1_c, 
					montant_facture_1_h, 
					montant_facture_2_c, 
					montant_facture_2_h, 
					montant_facture_22_c, 
					montant_facture_22_h, 
					montant_regle_0_c, 
					montant_regle_0_h, 
					montant_regle_1_c, 
					montant_regle_1_h, 
					montant_regle_2_c, 
					montant_regle_2_h, 
					montant_regle_22_c, 
					montant_regle_22_h, 
					delai_expedition_0, 
					delai_expedition_1, 
					delai_expedition_2, 
					delai_expedition_22, 
					delai_solde_0_c, 
					delai_solde_0_h, 
					delai_solde_1_c, 
					delai_solde_1_h, 
					delai_solde_2_c, 
					delai_solde_2_h, 
					delai_solde_22_c, 
					delai_solde_22_h, 
					ghs_id, 
					particularite_t2a, 
					code_cloture, 
					code_cp_demandee, 
					ghs_bebe1_id, 
					ghs_bebe2_id, 
					ghs_bebe3_id,
					montant_comptabilise_c, 
					montant_comptabilise_h, 
					montant_comptabilise_0_c,
					montant_comptabilise_0_h, 
					montant_comptabilise_1_c, 
					montant_comptabilise_1_h, 
					montant_comptabilise_2_c, 
					montant_comptabilise_2_h, 
					montant_comptabilise_22_c, 
					montant_comptabilise_22_h,
					nb_rejets,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour
					)         
				 SELECT
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					HF_IDFAC AS no_facture,
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					MAX(CASE WHEN H_HISFAC.sens_facture > 0 THEN '0'::text ELSE '1' END) AS type_facture,
					'1'::text AS code_facture,
					MAX(HF_DATFAC) AS date_facture,
					'1'::text AS code_vente,
					MAX(HF_DATFAC) as date_vente,
					MAX(to_char(HF_DATFAC,'YYYYMM')::numeric) AS mois_vente,
					'2099-12-31' AS date_solde, 
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END) AS montant_facture_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END) AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture, 
					0::numeric AS delai_solde, 
					MAX(HF_DATENV) as date_expedition, 
					0::numeric AS delai_expedition, 
					MAX(p_sejours.tiers_payant_0_id),
					MAX(p_sejours.tiers_payant_1_id),
					MAX(p_sejours.tiers_payant_2_id),
					0::bigint AS tiers_payant_22_id,	
					'2099-12-31' AS date_solde_0_c,     
					'2099-12-31' AS date_solde_0_h,     
					'2099-12-31' AS date_solde_1_c, 
					'2099-12-31' AS date_solde_1_h,	   
					'2099-12-31' AS date_solde_2_c,
					'2099-12-31' AS date_solde_2_h,
					'2099-12-31' AS date_solde_22_c,
					'2099-12-31' AS date_solde_22_h,
					'2099-12-31' AS date_expedition_0,
					MAX(HF_DATENV) AS date_expedition_1,
					MAX(HF_DATENV) AS date_expedition_2,
					'2099-12-31' AS date_expedition_22,
					'0'::text AS code_expedie_0,
					MAX(CASE WHEN HF_DATENV < '20991231' THEN '1'::text ELSE '0'::text END) AS code_expedie_1,
					MAX(CASE WHEN HF_DATENV < '20991231' THEN '1'::text ELSE '0'::text END) AS code_expedie_2,
					'0'::text AS code_expedie_22,
					'' AS no_bordereau_0,
					MAX(HF_NUMBOT) AS no_bordereau_1,
					MAX(HF_NUMBOT) AS no_bordereau_2,
					'' AS no_bordereau_22,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_facture_0_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_facture_0_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_facture_1_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_facture_1_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_facture_2_c,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_facture_2_h,
					0 AS montant_facture_22_c,
					0 AS montant_facture_22_h,
					0 AS montant_regle_0_c,
					0 AS montant_regle_0_h,
					0 AS montant_regle_1_c,
					0 AS montant_regle_1_h,
					0 AS montant_regle_2_c,
					0 AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0 AS delai_expedition_0, 
					0 AS delai_expedition_1, 
					0 AS delai_expedition_2, 
					0 AS delai_expedition_22, 
					0 AS delai_solde_0_c, 
					0 AS delai_solde_0_h, 
					0 AS delai_solde_1_c, 
					0 AS delai_solde_1_h, 
					0 AS delai_solde_2_c, 
					0 AS delai_solde_2_h, 
					0 AS delai_solde_22_c, 
					0 AS delai_solde_22_h, 
					0 AS ghs_id,
					'' as particularite_t2a, 
					'0' as code_cloture,
					'0' as code_cp_demandee, 
					0 AS ghs_bebe1_id, 
					0 AS ghs_bebe2_id, 
					0 AS ghs_bebe3_id,
					0 AS montant_comptabilise_c, 
					0 AS montant_comptabilise_h, 
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_comptabilise_0_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUPAT / 100) AS montant_comptabilise_0_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_comptabilise_1_c,
					SUM(CASE WHEN HF_PART = 'H' THEN HF_FACTUR ELSE 0 END * EM_TAUCAI / 100) AS montant_comptabilise_1_h,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_comptabilise_2_c,
					SUM(CASE WHEN HF_PART = 'F' THEN HF_FACTUR ELSE 0 END * EM_TAUMUT / 100) AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					0::numeric AS nb_rejets,
					0,
					0
				FROM w_H_HISFAC_autre H_HISFAC
				JOIN activite[PX].p_sejours ON HF_NUMDEM = p_sejours.code_original
				JOIN w_H_DEMAND_select H_DEMAND  ON HF_NUMDEM = EM_NUMDEM
				GROUP BY 1,2,3
				;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_14');
				
				ANALYSE activite[PX].p_factures
				;
				
				-- Non facturees
				DROP TABLE IF EXISTS w_factures_trous;
				CREATE TEMP TABLE w_factures_trous AS
				SELECT
					p_sejours.finess,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					p_sejours.date_entree,
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					p_sejours.tiers_payant_2_id, 
					p_sejours.tiers_payant_22_id,
					p_sejours.code_cp_demandee,
					COALESCE(t_services_facturation.avec_facturation_intermediaire,'') AS avec_facturation_intermediaire,
					p_sejours.code_sorti,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_sortie,
					MAX(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END ELSE p_factures.date_fin END) AS date_fin_facture,
					date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 AND code_sorti = '1' THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_encours
				FROM activite[PX].p_sejours
					LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND no_facture NOT LIKE 'E%' AND type_facture IS DISTINCT FROM 'P'
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.etat = '' AND p_sejours.est_sans_facturation IS DISTINCT FROM '1' AND date_entree <= now() AND p_sejours.type_sejour <> '6' AND p_sejours.type_sejour <> '9'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12
				;

				INSERT INTO activite[PX].p_factures(
					finess, 
					sejour_id,
					no_sejour, 
					no_facture, 
					no_facture_reference, 
					type_facture, 
					code_facture, 
					date_facture, 
					tiers_payant_0_id, tiers_payant_1_id, tiers_payant_2_id, tiers_payant_22_id,
					code_cp_demandee, 
					date_debut, 
					date_fin)
				SELECT
					finess,
					sejour_id,
					no_sejour, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E', 
					'0', 
					'20991231'::date,
					tiers_payant_0_id, tiers_payant_1_id, tiers_payant_2_id, tiers_payant_22_id, 
					code_cp_demandee , 
					MIN(GREATEST(date_debut_encours, p_calendrier.date)), 
					MAX(LEAST(date_fin_encours, p_calendrier.date))
				FROM w_factures_trous 
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_encours AND date_fin_encours
				WHERE (date_debut_encours <= date_fin_encours or date_fin_facture is null) 
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13
				;

        
                                        
			]]>            
			</sqlcmd>
        </NODE>

        <NODE label="Rejets">
        </NODE>


        <NODE label="Lignes facturees Clinique">
            <sqlcmd><![CDATA[
    

				-- lignes clinique
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_8');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					compte_produit_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour)

				SELECT 
					HF_IDFAC AS no_facture, 
					p_factures.oid AS facture_id,
					p_factures.date_debut, 
					p_factures.date_fin, 
					1::numeric AS nb_rubrique, 
					HFL_QTEBAS AS nb_prestations, 
					HFL_COEFF AS coefficient, 
					1::numeric AS coefficient_mco, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id, 
					COALESCE(0) AS compte_produit_id, 
					COALESCE(t_prestations.oid,0) AS prestation_id, 
					HFL_FACTUR * sens_facture AS montant_facture, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUPAT / 100,2) AS montant_facture_0, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUCAI / 100,2) AS montant_facture_1, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUMUT / 100,2) AS montant_facture_2, 
					0::numeric AS montant_facture_22, 
					EM_TAUPAT AS taux_0, 
					EM_TAUCAI AS taux_1, 
					EM_TAUMUT AS taux_2, 
					0::numeric AS taux_22, 
					HFL_PRIUNI AS prix_unitaire, 
					p_sejours.lieu_sortie_id AS lieu_id,
					
					HFL_FACTUR * sens_facture AS montant_comptabilise, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUPAT / 100,2) AS montant_comptabilise_0, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUCAI / 100,2) AS montant_comptabilise_1, 
					round(HFL_FACTUR::numeric * sens_facture * EM_TAUMUT / 100,2) AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					1::integer AS origine_facturation_id,
					0::numeric AS montant_facture_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour

				FROM prod_edlxplore.H_FACLIG
				JOIN w_H_HISFAC ON HFL_NUM_HF = HF_NUM_HF
				JOIN w_H_DEMAND_select H_DEMAND  ON HF_NUMDEM = EM_NUMDEM
				JOIN activite[PX].p_factures ON HF_IDFAC = p_factures.no_facture
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN activite[PX].t_rubriques_facturation ON HFL_COD_ACTE = t_rubriques_facturation.code_original
				LEFT JOIN activite.t_prestations ON HFL_COD_ACTE = t_prestations.code
				WHERE HF_PART = 'F'
				;
				
				-- Lignes non trouvees dans HISFAC
				-- Recuperer depuis la compta
				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					compte_produit_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour)
				SELECT 
					HF_IDFAC AS no_facture, 
					p_factures.oid AS facture_id,
					p_factures.date_debut, 
					p_factures.date_fin, 
					1::numeric AS nb_rubrique, 
					1::numeric AS nb_prestations, 
					1::numeric AS coefficient, 
					1::numeric AS coefficient_mco, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id, 
					COALESCE(0) AS compte_produit_id, 
					COALESCE(t_prestations.oid,0) AS prestation_id, 
					(MC_MTCREDIT - MC_MTDEBIT) AS montant_facture, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUPAT / 100,2) AS montant_facture_0, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUCAI / 100,2) AS montant_facture_1, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUMUT / 100,2) AS montant_facture_2, 
					0::numeric AS montant_facture_22, 
					EM_TAUPAT AS taux_0, 
					EM_TAUCAI AS taux_1, 
					EM_TAUMUT AS taux_2, 
					0::numeric AS taux_22, 
					(MC_MTCREDIT - MC_MTDEBIT) AS prix_unitaire, 
					p_sejours.lieu_sortie_id AS lieu_id,
					
					(MC_MTCREDIT - MC_MTDEBIT) AS montant_comptabilise, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUPAT / 100,2) AS montant_comptabilise_0, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUCAI / 100,2) AS montant_comptabilise_1, 
					round((MC_MTCREDIT - MC_MTDEBIT) * EM_TAUMUT / 100,2) AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					1::integer AS origine_facturation_id,
					0::numeric AS montant_facture_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour

				FROM prod_edlxplore.H_MVTCPT
				JOIN w_H_HISFAC_autre w_H_HISFAC ON H_MVTCPT.MC_NUMPIECE = w_H_HISFAC.MC_NUMPIECE
				JOIN w_H_DEMAND_select H_DEMAND  ON HF_NUMDEM = EM_NUMDEM
				JOIN activite[PX].p_factures ON HF_IDFAC = p_factures.no_facture
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN activite[PX].t_rubriques_facturation ON 'FTR' = t_rubriques_facturation.code_original
				LEFT JOIN activite.t_prestations ON 'FTR' = t_prestations.code
				WHERE HF_PART = 'F' AND
					MC_CATECR = 'E' AND 
					MC_NUMCPT NOT LIKE '41%' AND
					MC_CODJRN LIKE 'VENTE%'
				;
				
				-- Compte produit d'apres compta
				DROP TABLE IF EXISTS w_H_MVTCPT_cpt;
				CREATE TEMP TABLE w_H_MVTCPT_cpt AS
				SELECT MC_NUMFAC, (MAX(ARRAY[MC_NUMMC,MC_NUMCPT]))[2] AS MC_NUMCPT,
					0::bigint AS compte_produit_id
				FROM prod_edlxplore.H_MVTCPT
				WHERE MC_CATECR = 'E' AND
					MC_NUMCPT NOT LIKE '41%' AND
					MC_NUMCPT <> ''
				GROUP BY 1
				;

				ANALYSE w_H_MVTCPT_cpt
				;

				UPDATE w_H_MVTCPT_cpt
				SET compte_produit_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE MC_NUMCPT = t_compte.code
				;

				UPDATE activite[PX].p_factures_lignes_c
				SET compte_produit_id = w_H_MVTCPT_cpt.compte_produit_id
				FROM w_H_MVTCPT_cpt
				WHERE split_part(p_factures_lignes_c.no_facture,'.',1) = MC_NUMFAC
				; 
				
				-- Arrondis
				UPDATE activite[PX].p_factures_lignes_c SET
					montant_facture_0 = montant_facture - montant_facture_1,
					montant_comptabilise_0 = montant_comptabilise - montant_comptabilise_1
				WHERE montant_facture_1 + montant_facture_2 + montant_facture_0 <> montant_facture AND
					montant_facture_1 <> 0 AND
					montant_facture_2 = 0 AND
					montant_facture_0 <> 0
				;

				UPDATE activite[PX].p_factures_lignes_c SET
					montant_facture_2 = montant_facture - montant_facture_1,
					montant_comptabilise_2 = montant_comptabilise - montant_comptabilise_1
				WHERE montant_facture_1 + montant_facture_2 + montant_facture_0 <> montant_facture AND
					montant_facture_1 <> 0 AND
					montant_facture_2 <> 0 AND
					montant_facture_0 = 0
				;
				
				
        
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_8');
				
				ANALYSE activite[PX].p_factures_lignes_c
				;

				
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_lignes_c');

        
			]]>
			</sqlcmd>
        </NODE>

        <NODE label="Lignes non facturees Clinique">
        </NODE>


        <NODE label="Compte client Clinique">
            <sqlcmd><![CDATA[
    
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_8');

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					p_factures.date_vente,
					p_factures_lignes_c.rubrique_comptabilisation_id,
					p_factures_lignes_c.prestation_id,
					SUM(p_factures_lignes_c.montant_comptabilise),
					SUM(p_factures_lignes_c.montant_comptabilise_0),
					SUM(p_factures_lignes_c.montant_comptabilise_1),
					SUM(p_factures_lignes_c.montant_comptabilise_2),
					SUM(p_factures_lignes_c.montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				WHERE p_factures.date_vente <> '20991231' AND 
					(
					p_factures_lignes_c.montant_comptabilise <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_0 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_1 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_2 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4
				;
				
				DROP TABLE IF EXISTS w_H_HISFAC_last;
				CREATE TEMP TABLE w_H_HISFAC_last AS
				SELECT HF_NUMDEM, 
					(MAX(ARRAY[HF_DATFAC::text,HF_IDFAC]))[2] AS no_facture
				FROM w_H_HISFAC
				WHERE sens_facture > 0
				GROUP BY 1
				;

				ANALYSE w_H_HISFAC_last
				;
				
				-- Reglements
				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					date(GG_DATREG) AS date_comptable,
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(GG_REGFOR),
					SUM(CASE WHEN GG_TYPREG = 'P' THEN GG_REGFOR  ELSE 0 END),
					SUM(CASE WHEN GG_TYPREG = 'C' THEN GG_REGFOR ELSE 0 END),
					SUM(CASE WHEN GG_TYPREG = 'M' THEN GG_REGFOR  ELSE 0 END),
					0
				FROM w_H_HISFAC_last
				JOIN prod_edlxplore.H_REGLEM ON HF_NUMDEM = GG_NUMDEM
				JOIN activite[PX].p_factures ON p_factures.no_facture = w_H_HISFAC_last.no_facture
				WHERE GG_REGFOR <> 0
				GROUP BY 1,2,3,4
				;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_8');

				ANALYSE activite[PX].p_factures_soldes_c
				;				
                                
			]]></sqlcmd>
        </NODE>
		
		<NODE label="Lignes non facturees Honoraires">
			<sqlcmd><![CDATA[
				TRUNCATE activite[PX].p_factures_lignes_non_facturees_h
				;
				
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					heure_debut, 
					nb_rubrique, 
					coefficient, 
					medecin_facture_id, 
					prestation_id, 
					prix_unitaire, 
					montant_depassement, 
					lieu_id, 
					acte_id, 
					phase_ccam, 
					activite_ccam, 
					extension_ccam, 
					modificateur_ccam_1, 
					modificateur_ccam_2,
					modificateur_ccam_3, 
					modificateur_ccam_4)
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					p_factures.date_debut AS date_debut,
					p_factures.date_fin AS date_fin,
					0::numeric AS heure_debut,
					1::numeric AS nb_rubrique,
					1::numeric AS coefficient,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
					COALESCE(t_prestations.oid,0) AS prestation_id,
					ZD_PRIUNI AS prix_unitaire,
					ZD_MTDEP AS montant_depassement, 
					p_sejours.lieu_sortie_id AS lieu_id,
					COALESCE(t_actes.oid,0) AS acte_id,
					'1'::text AS phase_ccam,
					'1'::text AS activite_ccam,
					''::text AS extension_ccam, 
					SPLIT_PART(ZD_MODIFFACT,';',1) AS modificateur_ccam_1, 
					SPLIT_PART(ZD_MODIFFACT,';',2) AS modificateur_ccam_2,
					SPLIT_PART(ZD_MODIFFACT,';',3) AS modificateur_ccam_3, 
					SPLIT_PART(ZD_MODIFFACT,';',4) AS modificateur_ccam_4
				FROM prod_edlxplore.H_CCAMDET
				JOIN activite[PX].p_sejours ON ZD_NUMDEM = p_sejours.code_original 
				JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND type_facture = 'E'
				LEFT JOIN activite[PX].t_medecins_administratifs ON ZD_CODPER = t_medecins_administratifs.code_original
				LEFT JOIN base.t_actes ON ZD_COD_ACTE = t_actes.code
				LEFT JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_ccam_regroupements.code = t_rubriques_facturation.code_original
				LEFT JOIN activite.t_prestations ON t_ccam_regroupements.code = t_prestations.code
				;
			
			]]></sqlcmd>
        </NODE>


        <NODE label="Lignes factures Honoraires">
            <sqlcmd><![CDATA[

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_9');

				INSERT INTO activite[PX].p_factures_lignes_h(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					medecin_facture_id, 
					medecin_comptabilise_id, 
					rubrique_facturation_id,
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					montant_depassement,
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour,

					acte_id,
					activite_ccam
				)

				SELECT 
					HF_IDFAC AS no_facture, 
					p_factures.oid AS facture_id,
					p_factures.date_debut, 
					p_factures.date_fin, 
					1::numeric AS nb_rubrique, 
					HFL_QTEBAS AS nb_prestations, 
					HFL_COEFF AS coefficient, 
					1::numeric AS coefficient_mco, 
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id, 
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id, 
					COALESCE(t_prestations.oid,0) AS prestation_id, 
					HFL_FACTUR * sens_facture AS montant_facture, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUPAT / 100,2) + HFL_MTDEP * sens_facture AS montant_facture_0, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUCAI / 100,2) AS montant_facture_1, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUMUT / 100,2) AS montant_facture_2, 
					0::numeric AS montant_facture_22,
					HFL_MTDEP AS montant_depassement,
					EM_TAUPAT AS taux_0, 
					EM_TAUCAI AS taux_1, 
					EM_TAUMUT AS taux_2, 
					0::numeric AS taux_22,
					HFL_PRIUNI AS prix_unitaire, 
					p_sejours.lieu_sortie_id AS lieu_id,
					
					HFL_FACTUR * sens_facture AS montant_comptabilise, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUPAT / 100,2) + HFL_MTDEP * sens_facture AS montant_comptabilise_0, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUCAI / 100,2) AS montant_comptabilise_1, 
					round((HFL_FACTUR::numeric-HFL_MTDEP) * sens_facture * EM_TAUMUT / 100,2) AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					0::numeric AS montant_facture_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour,

					COALESCE(t_actes.oid,0) AS acte_id,
					'1'::text AS activite_ccam

				FROM prod_edlxplore.H_FACLIG
				JOIN w_H_HISFAC ON HFL_NUM_HF = HF_NUM_HF
				JOIN w_H_DEMAND_select H_DEMAND  ON HF_NUMDEM = EM_NUMDEM
				JOIN activite[PX].p_factures ON HF_IDFAC = p_factures.no_facture
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN activite[PX].t_medecins_administratifs ON HFL_CODPER = t_medecins_administratifs.code_original
				LEFT JOIN base.t_actes ON HFL_COD_ACTE = t_actes.code
				LEFT JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_ccam_regroupements.code = t_rubriques_facturation.code_original
				LEFT JOIN activite.t_prestations ON t_ccam_regroupements.code = t_prestations.code
				WHERE HF_PART = 'H'
				;
				
				-- Lignes non trouvees dans HISFAC et FACLIG
				INSERT INTO activite[PX].p_factures_lignes_h(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					medecin_facture_id, 
					medecin_comptabilise_id, 
					rubrique_facturation_id,
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					montant_depassement,
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

					montant_facture_actes_inclus_dans_sejour, 
					montant_facture_0_actes_inclus_dans_sejour, 
					montant_facture_1_actes_inclus_dans_sejour, 
					montant_facture_2_actes_inclus_dans_sejour, 
					montant_facture_22_actes_inclus_dans_sejour,

					acte_id,
					activite_ccam, 
					modificateur_ccam_1, 
					modificateur_ccam_2,
					modificateur_ccam_3, 
					modificateur_ccam_4
				)
				SELECT 
					HF_IDFAC AS no_facture, 
					p_factures.oid AS facture_id,
					p_factures.date_debut, 
					p_factures.date_fin, 
					1::numeric AS nb_rubrique, 
					1::numeric AS nb_prestations, 
					1::numeric AS coefficient, 
					1::numeric AS coefficient_mco, 
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id, 
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id, 
					COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id, 
					COALESCE(t_prestations.oid,0) AS prestation_id, 
					ZD_FACTUR * sens_facture AS montant_facture, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUPAT / 100,2) + ZD_MTDEP * sens_facture AS montant_facture_0, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUCAI / 100,2) AS montant_facture_1, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUMUT / 100,2) AS montant_facture_2, 
					0::numeric AS montant_facture_22,
					ZD_MTDEP AS montant_depassement,
					EM_TAUPAT AS taux_0, 
					EM_TAUCAI AS taux_1, 
					EM_TAUMUT AS taux_2, 
					0::numeric AS taux_22,
					ZD_PRIUNI AS prix_unitaire, 
					p_sejours.lieu_sortie_id AS lieu_id,
					
					ZD_FACTUR * sens_facture AS montant_comptabilise, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUPAT / 100,2) + ZD_MTDEP * sens_facture AS montant_comptabilise_0, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUCAI / 100,2) AS montant_comptabilise_1, 
					round((ZD_FACTUR::numeric-ZD_MTDEP) * sens_facture * EM_TAUMUT / 100,2) AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					0::numeric AS montant_facture_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour,

					COALESCE(t_actes.oid,0) AS acte_id,
					'1'::text AS activite_ccam, 
					SPLIT_PART(ZD_MODIFFACT,';',1) AS modificateur_ccam_1, 
					SPLIT_PART(ZD_MODIFFACT,';',2) AS modificateur_ccam_2,
					SPLIT_PART(ZD_MODIFFACT,';',3) AS modificateur_ccam_3, 
					SPLIT_PART(ZD_MODIFFACT,';',4) AS modificateur_ccam_4

				FROM prod_edlxplore.H_CCAMDET
				JOIN w_H_HISFAC_autre w_H_HISFAC ON ZD_NUMDEM = HF_NUMDEM
				JOIN w_H_DEMAND_select H_DEMAND  ON ZD_NUMDEM = EM_NUMDEM
				JOIN activite[PX].p_factures ON HF_IDFAC = p_factures.no_facture
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN activite[PX].t_medecins_administratifs ON ZD_CODPER = t_medecins_administratifs.code_original
				LEFT JOIN base.t_actes ON ZD_COD_ACTE = t_actes.code
				LEFT JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_ccam_regroupements.code = t_rubriques_facturation.code_original
				LEFT JOIN activite.t_prestations ON t_ccam_regroupements.code = t_prestations.code
				WHERE HF_PART = 'H'
				;
				
				-- Arrondis
				UPDATE activite[PX].p_factures_lignes_h SET
					montant_facture_0 = montant_facture - montant_facture_1,
					montant_comptabilise_0 = montant_comptabilise - montant_comptabilise_1
				WHERE montant_facture_1 + montant_facture_2 + montant_facture_0 <> montant_facture AND
					montant_facture_1 <> 0 AND
					montant_facture_2 = 0 AND
					montant_facture_0 <> 0
				;

				UPDATE activite[PX].p_factures_lignes_h SET
					montant_facture_2 = montant_facture - montant_facture_1,
					montant_comptabilise_2 = montant_comptabilise - montant_comptabilise_1
				WHERE montant_facture_1 + montant_facture_2 + montant_facture_0 <> montant_facture AND
					montant_facture_1 <> 0 AND
					montant_facture_2 <> 0 AND
					montant_facture_0 = 0
				;
            
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_9');
				
				ANALYSE activite[PX].p_factures_lignes_h
				;
        
                                
				]]>            
			</sqlcmd>
        </NODE>
        

        <NODE label="Compte client Honoraires">
            <sqlcmd><![CDATA[
    
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');

				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id, 
					rubrique_comptabilisee_id,
					prestation_id,
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					p_factures.date_vente,
					medecin_comptabilise_id,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM activite[PX].p_factures_lignes_h
				JOIN activite[PX].p_factures On p_factures_lignes_h.no_facture = p_factures.no_facture
				WHERE date_vente IS NOT NULL AND
					(
					montant_comptabilise <> 0 OR 
					montant_comptabilise_0 <> 0 OR 
					montant_comptabilise_1 <> 0 OR 
					montant_comptabilise_2 <> 0 OR 
					montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4,5
				;
				
				-- Reglements
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					date_comptable,
					medecin_comptabilise_id,  
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					date(GG_DATREG) AS date_comptable,
					0::bigint AS medecin_comptabilise_id, 
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(GG_REGHON),
					SUM(CASE WHEN GG_TYPREG = 'P' THEN GG_REGHON  ELSE 0 END),
					SUM(CASE WHEN GG_TYPREG = 'C' THEN GG_REGHON ELSE 0 END),
					SUM(CASE WHEN GG_TYPREG = 'M' THEN GG_REGHON  ELSE 0 END),
					0
				FROM w_H_HISFAC_last
				JOIN prod_edlxplore.H_REGLEM ON HF_NUMDEM = GG_NUMDEM
				JOIN activite[PX].p_factures ON p_factures.no_facture = w_H_HISFAC_last.no_facture
				WHERE GG_REGFOR = 0 AND GG_REGHON <> 0
				GROUP BY 1,2,3,4
				;
        
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_8');
				
				ANALYSE activite[PX].p_factures_soldes_h
				;
				
				-- Medecin sur reglements selon facturation
				UPDATE activite[PX].p_factures_soldes_h
				SET medecin_comptabilise_id = subview.medecin_comptabilise_id
				FROM
				(
				SELECT no_facture, MAX(medecin_comptabilise_id) AS medecin_comptabilise_id
				FROM activite[PX].p_factures_soldes_h
				WHERE medecin_comptabilise_id <> 0
				GROUP BY 1
				HAVING count(DISTINCT medecin_comptabilise_id) = 1
				) subview
				WHERE p_factures_soldes_h.no_facture = subview.no_facture AND
					p_factures_soldes_h.medecin_comptabilise_id = 0
				;
        
			]]></sqlcmd>
        </NODE>

        <NODE label="Post traitement entetes">
			<sqlcmd><![CDATA[
			
				-- pour ma mutuelle CLIAXIUM, pas de reglements (pour envoi a la GAP de la clinique)
				-- Regle automatiquement
				-- CLIAXIUM en dur
				DROP TABLE IF EXISTS w_facture_cliaxium;
				CREATE TEMP TABLE w_facture_cliaxium AS
				SELECT p_factures_soldes_c.no_facture
				FROM activite[PX].p_factures_soldes_c
				JOIN activite[PX].p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				JOIN activite[PX].t_tiers_payant ON p_factures.tiers_payant_2_id = t_tiers_payant.oid
				WHERE t_tiers_payant.code = 'CLIAXIUMM' AND montant_comptabilise_2 <> 0
				GROUP BY 1
				;

				ANALYSE w_facture_cliaxium
				;

				UPDATE activite[PX].p_factures_soldes_c SET
					montant_regle_2 = montant_comptabilise_2,
					montant_regle = montant_regle + montant_comptabilise_2
				FROM w_facture_cliaxium
				WHERE p_factures_soldes_c.no_facture = w_facture_cliaxium.no_facture AND
					montant_comptabilise_2 <> 0
				;
				
				DROP TABLE IF EXISTS w_facture_cliaxium;
				CREATE TEMP TABLE w_facture_cliaxium AS
				SELECT p_factures_soldes_h.no_facture
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				JOIN activite[PX].t_tiers_payant ON p_factures.tiers_payant_2_id = t_tiers_payant.oid
				WHERE t_tiers_payant.code = 'CLIAXIUMM' AND montant_comptabilise_2 <> 0
				GROUP BY 1
				;

				ANALYSE w_facture_cliaxium
				;

				UPDATE activite[PX].p_factures_soldes_h
				SET montant_regle_2 = montant_comptabilise_2,
					montant_regle = montant_regle + montant_comptabilise_2
				FROM w_facture_cliaxium
				WHERE p_factures_soldes_h.no_facture = w_facture_cliaxium.no_facture AND
					montant_comptabilise_2 <> 0
				;
				
				-- OD avoir
				UPDATE activite[PX].p_factures SET
					no_facture_od_avoir = p_factures_2.no_facture,
					facture_od_avoir_id = p_factures_2.oid
				FROM activite[PX].p_factures p_factures_2
				WHERE p_factures.no_facture = p_factures_2.no_facture || 'A' AND
					p_factures.type_facture = '1'
				;

				UPDATE activite[PX].p_factures SET
					no_facture_od_avoir = p_factures_2.no_facture,
					facture_od_avoir_id = p_factures_2.oid
				FROM activite[PX].p_factures p_factures_2
				WHERE p_factures.no_facture || 'A' = p_factures_2.no_facture AND
					p_factures.type_facture = '0'
				;
				
				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_c.no_facture,
					CASE WHEN p_factures.type_facture = '0' THEN p_factures.date_vente ELSE p_factures_2.date_vente END,
					p_factures_soldes_c.rubrique_comptabilisee_id,
					p_factures_soldes_c.prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(p_factures_soldes_c.montant_comptabilise - p_factures_soldes_c.montant_regle),
					SUM(p_factures_soldes_c.montant_comptabilise_0 - p_factures_soldes_c.montant_regle_0),
					SUM(p_factures_soldes_c.montant_comptabilise_1 - p_factures_soldes_c.montant_regle_1),
					SUM(p_factures_soldes_c.montant_comptabilise_2 - p_factures_soldes_c.montant_regle_2),
					SUM(p_factures_soldes_c.montant_comptabilise_22 - p_factures_soldes_c.montant_regle_22),
					'1'::text
				FROM activite[PX].p_factures_soldes_c
				JOIN activite[PX].p_factures ON p_factures_soldes_c.no_facture = p_factures.no_facture
				JOIN activite[PX].p_factures p_factures_2 ON p_factures.no_facture_od_avoir = p_factures_2.no_facture
				WHERE p_factures.no_facture_od_avoir <> ''
				GROUP BY 1,2,3,4
				HAVING SUM(p_factures_soldes_c.montant_comptabilise - p_factures_soldes_c.montant_regle) <> 0
				;
				
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id,
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_h.no_facture,
					CASE WHEN p_factures.type_facture = '0' THEN p_factures.date_vente ELSE p_factures_2.date_vente END,
					p_factures_soldes_h.medecin_comptabilise_id,
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(p_factures_soldes_h.montant_comptabilise - p_factures_soldes_h.montant_regle),
					SUM(p_factures_soldes_h.montant_comptabilise_0 - p_factures_soldes_h.montant_regle_0),
					SUM(p_factures_soldes_h.montant_comptabilise_1 - p_factures_soldes_h.montant_regle_1),
					SUM(p_factures_soldes_h.montant_comptabilise_2 - p_factures_soldes_h.montant_regle_2),
					SUM(p_factures_soldes_h.montant_comptabilise_22 - p_factures_soldes_h.montant_regle_22),
					'1'::text
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].p_factures ON p_factures_soldes_h.no_facture = p_factures.no_facture
				JOIN activite[PX].p_factures p_factures_2 ON p_factures.no_facture_od_avoir = p_factures_2.no_facture
				WHERE p_factures.no_facture_od_avoir <> ''
				GROUP BY 1,2,3,4,5
				HAVING SUM(p_factures_soldes_h.montant_comptabilise - p_factures_soldes_h.montant_regle) <> 0
				;
				
				-- Honoraires payes directement aux medecins
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id,
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_h.no_facture,
					MIN(p_factures_soldes_h.date_comptable),
					p_factures_soldes_h.medecin_comptabilise_id,
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(p_factures_soldes_h.montant_comptabilise_1 - p_factures_soldes_h.montant_regle_1),
					0,
					SUM(p_factures_soldes_h.montant_comptabilise_1 - p_factures_soldes_h.montant_regle_1),
					0,
					0,
					'1'::text
				FROM activite[PX].p_factures_soldes_h
				GROUP BY 1,3,4,5
				HAVING SUM(p_factures_soldes_h.montant_comptabilise_1 - p_factures_soldes_h.montant_regle_1) <> 0
				;
				
				

				-- totaux facture
				UPDATE activite[PX].p_factures SET
					montant_facture_c = subview.montant_facture,
					montant_facture_0_c = subview.montant_facture_0,
					montant_facture_1_c = subview.montant_facture_1,
					montant_facture_2_c = subview.montant_facture_2,
					montant_comptabilise_c = subview.montant_comptabilise,
					montant_comptabilise_0_c = subview.montant_comptabilise_0,
					montant_comptabilise_1_c = subview.montant_comptabilise_1,
					montant_comptabilise_2_c = subview.montant_comptabilise_2
				FROM (
					SELECT no_facture, 
						SUM(montant_facture) AS montant_facture, 
						SUM(montant_facture_0) AS montant_facture_0, 
						SUM(montant_facture_1) AS montant_facture_1, 
						SUM(montant_facture_2) AS montant_facture_2, 
						SUM(montant_comptabilise) AS montant_comptabilise, 
						SUM(montant_comptabilise_0) AS montant_comptabilise_0, 
						SUM(montant_comptabilise_1) AS montant_comptabilise_1, 
						SUM(montant_comptabilise_2) AS montant_comptabilise_2
					FROM activite[PX].p_factures_lignes_c
					GROUP BY 1
					) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				UPDATE activite[PX].p_factures SET
					montant_facture_h = subview.montant_facture,
					montant_facture_0_h = subview.montant_facture_0,
					montant_facture_1_h = subview.montant_facture_1,
					montant_facture_2_h = subview.montant_facture_2,
					montant_comptabilise_h = subview.montant_comptabilise,
					montant_comptabilise_0_h = subview.montant_comptabilise_0,
					montant_comptabilise_1_h = subview.montant_comptabilise_1,
					montant_comptabilise_2_h = subview.montant_comptabilise_2
				FROM (
					SELECT no_facture, 
						SUM(montant_facture) AS montant_facture, 
						SUM(montant_facture_0) AS montant_facture_0, 
						SUM(montant_facture_1) AS montant_facture_1, 
						SUM(montant_facture_2) AS montant_facture_2, 
						SUM(montant_comptabilise) AS montant_comptabilise, 
						SUM(montant_comptabilise_0) AS montant_comptabilise_0, 
						SUM(montant_comptabilise_1) AS montant_comptabilise_1, 
						SUM(montant_comptabilise_2) AS montant_comptabilise_2
					FROM activite[PX].p_factures_lignes_h
					GROUP BY 1
					) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				UPDATE activite[PX].p_factures SET
					montant_regle_c = subview.montant_regle,
					montant_regle_0_c = subview.montant_regle_0,
					montant_regle_1_c = subview.montant_regle_1,
					montant_regle_2_c = subview.montant_regle_2,
					date_solde = COALESCE(subview.date_solde,p_factures.date_solde),
					date_solde_c = COALESCE(subview.date_solde,p_factures.date_solde),
					date_solde_0_c = COALESCE(subview.date_solde,p_factures.date_solde_0_c),
					date_solde_1_c = COALESCE(subview.date_solde,p_factures.date_solde_1_c),
					date_solde_2_c = COALESCE(subview.date_solde,p_factures.date_solde_2_c)
				FROM (
					SELECT no_facture, 
						SUM(montant_regle) AS montant_regle, 
						SUM(montant_regle_0) AS montant_regle_0, 
						SUM(montant_regle_1) AS montant_regle_1, 
						SUM(montant_regle_2) AS montant_regle_2,
						MAX(CASE WHEN montant_regle <> 0 THEN date_comptable ELSE NULL END) AS date_solde,
						MAX(CASE WHEN montant_regle_0 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_0,
						MAX(CASE WHEN montant_regle_1 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_1,
						MAX(CASE WHEN montant_regle_2 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_2
					FROM activite[PX].p_factures_soldes_c
					WHERE montant_regle <> 0 OR
						montant_regle_0 <> 0 OR
						montant_regle_1 <> 0 OR
						montant_regle_2 <> 0
					GROUP BY 1
					) subview
				WHERE p_factures.no_facture = subview.no_facture
				;


				UPDATE activite[PX].p_factures SET
					montant_regle_h = subview.montant_regle,
					montant_regle_0_h = subview.montant_regle_0,
					montant_regle_1_h = subview.montant_regle_1,
					montant_regle_2_h = subview.montant_regle_2,
					date_solde = GREATEST(p_factures.date_solde,COALESCE(subview.date_solde,p_factures.date_solde)),
					date_solde_h = COALESCE(subview.date_solde,p_factures.date_solde),
					date_solde_0_h = COALESCE(subview.date_solde,p_factures.date_solde_0_h),
					date_solde_1_h = COALESCE(subview.date_solde,p_factures.date_solde_1_h),
					date_solde_2_h = COALESCE(subview.date_solde,p_factures.date_solde_2_h)
				FROM (
					SELECT no_facture, 
						SUM(montant_regle) AS montant_regle, 
						SUM(montant_regle_0) AS montant_regle_0, 
						SUM(montant_regle_1) AS montant_regle_1, 
						SUM(montant_regle_2) AS montant_regle_2,
						MAX(CASE WHEN montant_regle <> 0 THEN date_comptable ELSE NULL END) AS date_solde,
						MAX(CASE WHEN montant_regle_0 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_0,
						MAX(CASE WHEN montant_regle_1 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_1,
						MAX(CASE WHEN montant_regle_2 <> 0 THEN date_comptable ELSE NULL END) AS date_solde_2
					FROM activite[PX].p_factures_soldes_h
					WHERE montant_regle <> 0 OR
						montant_regle_0 <> 0 OR
						montant_regle_1 <> 0 OR
						montant_regle_2 <> 0
					GROUP BY 1
					) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				-- Attention, en comptabilisation, prendre en compte le fait que le taux n'est pas toujours applique en comptabilisation
				-- On garde le taux facture mais la compta va a l'AMO (car tout est regle sur l'AMO
				DROP TABLE IF EXISTS w_factures_ajust_t;
				CREATE TEMP TABLE w_factures_ajust_t AS
				SELECT no_facture
				FROM activite[PX].p_factures
				WHERE montant_regle_1_c = montant_comptabilise_c AND
					montant_regle_1_c <> 0 AND
					(
					montant_comptabilise_2_c <> 0 OR
					montant_comptabilise_0_c <> 0
					)
				;

				ANALYSE w_factures_ajust_t
				;

				UPDATE activite[PX].p_factures SET
					montant_comptabilise_1_c = montant_comptabilise_1_c + montant_comptabilise_2_c + montant_comptabilise_0_c,
					montant_comptabilise_2_c = 0,
					montant_comptabilise_0_c = 0
				FROM w_factures_ajust_t
				WHERE p_factures.no_facture = w_factures_ajust_t.no_facture
				;

				
				UPDATE activite[PX].p_factures_lignes_c SET
					montant_comptabilise_1 = montant_comptabilise_1 + montant_comptabilise_2 + montant_comptabilise_0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_0 = 0
				FROM w_factures_ajust_t
				WHERE p_factures_lignes_c.no_facture = w_factures_ajust_t.no_facture
				;

				UPDATE activite[PX].p_factures_soldes_c SET
					montant_comptabilise_1 = montant_comptabilise_1 + montant_comptabilise_2 + montant_comptabilise_0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_0 = 0
				FROM w_factures_ajust_t
				WHERE p_factures_soldes_c.no_facture = w_factures_ajust_t.no_facture
				;
		
            ]]>
            </sqlcmd>
        </NODE>
		
		<NODE label="Post traitement sejours">
			<sqlcmd><![CDATA[
			
				UPDATE activite[PX].p_sejours 
				SET date_groupage = date_facture 
				WHERE (date_groupage IS null OR date_groupage = '20991231') AND 
					date_facture <> '2099-12-31';
				
				
				DROP TABLE IF EXISTS w_sejours_total;
				CREATE TEMP TABLE w_sejours_total AS
				SELECT   
					p_sejours.no_sejour AS no_sejour, 
					p_sejours.code_sorti,
					p_sejours.date_sortie,
					p_sejours.date_groupage,   
					p_sejours.ghs_id,
	
					MAX(COALESCE(p_factures.date_facture,'20991231')) AS date_facture,     
					MAX(COALESCE(p_factures.date_expedition,'20991231')) AS date_expedition,  
					MAX(COALESCE(p_factures.date_solde,'20991231')) AS date_solde,  
					SUM(COALESCE(p_factures.montant_facture_c,0)) AS montant_facture_c,  
					SUM(COALESCE(p_factures.montant_facture_h,0)) AS montant_facture_h,  
					SUM(COALESCE(p_factures.montant_regle_c,0)) AS montant_regle_c,  
					SUM(COALESCE(p_factures.montant_regle_h,0)) AS montant_regle_h,  
					SUM(COALESCE(CASE WHEN p_factures.type_facture <> 'P' AND p_factures.type_facture <> 'E' AND p_factures.type_facture <> 'G' THEN 1 ELSE 0 END,0)) AS nb_factures,  
					SUM(COALESCE(CASE WHEN p_factures.type_facture = '0' THEN 0 ELSE 1 END,0)) AS nb_factures_regularisation,  
					SUM(COALESCE(p_factures.nb_rejets,0)) AS nb_rejets,  

					SUM(COALESCE(p_factures.montant_facture_0_c,0)) AS montant_facture_0_c,  
					SUM(COALESCE(p_factures.montant_facture_0_h,0)) AS montant_facture_0_h,  
					SUM(COALESCE(p_factures.montant_regle_0_c,0)) AS montant_regle_0_c,  
					SUM(COALESCE(p_factures.montant_regle_0_h,0)) AS montant_regle_0_h,  
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_0_c <> 0 OR p_factures.montant_facture_0_h <> 0)  THEN p_factures.date_expedition_0 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_0,   
					MAX(COALESCE(CASE WHEN p_factures.date_solde_0_c < '2099-12-31' AND p_factures.date_solde_0_c > p_factures.date_solde_0_h THEN p_factures.date_solde_0_c ELSE p_factures.date_solde_0_h END,'20991231' )) AS date_solde_0,  
					

					SUM(COALESCE(p_factures.montant_facture_1_c,0)) AS montant_facture_1_c,  
					SUM(COALESCE(p_factures.montant_facture_1_h,0)) AS montant_facture_1_h,  
					SUM(COALESCE(p_factures.montant_regle_1_c,0)) AS montant_regle_1_c,  
					SUM(COALESCE(p_factures.montant_regle_1_h,0)) AS montant_regle_1_h,  
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_1_c <> 0 OR p_factures.montant_facture_1_h <> 0)  THEN p_factures.date_expedition_1 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_1,  
					MAX(COALESCE(CASE WHEN p_factures.date_solde_1_c < '2099-12-31' AND p_factures.date_solde_1_c > p_factures.date_solde_1_h THEN p_factures.date_solde_1_c ELSE p_factures.date_solde_1_h END,'20991231' )) AS date_solde_1,  

					SUM(COALESCE(p_factures.montant_facture_2_c,0)) AS montant_facture_2_c,  
					SUM(COALESCE(p_factures.montant_facture_2_h,0)) AS montant_facture_2_h,  
					SUM(COALESCE(p_factures.montant_regle_2_c,0)) AS montant_regle_2_c,  
					SUM(COALESCE(p_factures.montant_regle_2_h,0)) AS montant_regle_2_h,  
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_2_c <> 0 OR p_factures.montant_facture_2_h <> 0)  THEN p_factures.date_expedition_2 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_2,  
					MAX(COALESCE(CASE WHEN p_factures.date_solde_2_c < '2099-12-31' AND p_factures.date_solde_2_c > p_factures.date_solde_2_h THEN p_factures.date_solde_2_c ELSE p_factures.date_solde_2_h END,'20991231' )) AS date_solde_2,  

					SUM(COALESCE(p_factures.montant_facture_22_c,0)) AS montant_facture_22_c,  
					SUM(COALESCE(p_factures.montant_facture_22_h,0)) AS montant_facture_22_h,  
					SUM(COALESCE(p_factures.montant_regle_22_c,0)) AS montant_regle_22_c,  
					SUM(COALESCE(p_factures.montant_regle_22_h,0)) AS montant_regle_22_h,  
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_22_c <> 0 OR p_factures.montant_facture_22_h <> 0)  THEN p_factures.date_expedition_22 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_22,  
					MAX(COALESCE(CASE WHEN p_factures.date_solde_22_c < '2099-12-31' AND p_factures.date_solde_22_c > p_factures.date_solde_22_h THEN p_factures.date_solde_22_c ELSE p_factures.date_solde_22_h END,'20991231' )) AS date_solde_22 , 

					
					SUM(COALESCE(p_factures.montant_comptabilise_c,0)) AS montant_comptabilise_c,  
					SUM(COALESCE(p_factures.montant_comptabilise_h,0)) AS montant_comptabilise_h,  
					SUM(COALESCE(p_factures.montant_comptabilise_0_c,0)) AS montant_comptabilise_0_c,  
					SUM(COALESCE(p_factures.montant_comptabilise_0_h,0)) AS montant_comptabilise_0_h,  
					SUM(COALESCE(p_factures.montant_comptabilise_1_c,0)) AS montant_comptabilise_1_c,  
					SUM(COALESCE(p_factures.montant_comptabilise_1_h,0)) AS montant_comptabilise_1_h,  
					SUM(COALESCE(p_factures.montant_comptabilise_2_c,0)) AS montant_comptabilise_2_c,  
					SUM(COALESCE(p_factures.montant_comptabilise_2_h,0)) AS montant_comptabilise_2_h,  
					SUM(COALESCE(p_factures.montant_comptabilise_22_c,0)) AS montant_comptabilise_22_c,  
					SUM(COALESCE(p_factures.montant_comptabilise_22_h,0)) AS montant_comptabilise_22_h,

					SUM(COALESCE(p_factures.montant_comptabilise_budget_global_c,0)) AS montant_comptabilise_budget_global_c,  

					SUM(COALESCE(p_factures.montant_facture_c_actes_inclus_dans_sejour,0)) AS montant_facture_c_actes_inclus_dans_sejour,  
					SUM(COALESCE(p_factures.montant_facture_h_actes_inclus_dans_sejour,0)) AS montant_facture_h_actes_inclus_dans_sejour,

					0::numeric AS delai_groupage, 
					0::numeric AS delai_facture, 
					0::numeric AS delai_expedition, 
					0::numeric AS delai_solde, 
					0::numeric AS delai_expedition_0, 
					0::numeric AS delai_solde_0, 
					0::numeric AS delai_expedition_1, 
					0::numeric AS delai_solde_1, 
					0::numeric AS delai_expedition_2, 
					0::numeric AS delai_solde_2, 
					0::numeric AS delai_expedition_22, 
					0::numeric AS delai_solde_22
				
				FROM activite[PX].p_sejours LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture <> 'P'
				GROUP BY 1,2,3,4,5;
				
				
				UPDATE w_sejours_total
				SET date_groupage = date_facture 
				WHERE (date_groupage IS null OR date_groupage = '20991231' OR date_groupage = '00010101') AND 
					date_facture <> '2099-12-31';


				UPDATE w_sejours_total SET  
					date_groupage = CASE WHEN date_groupage > '00010101' THEN date_groupage ELSE '20991231' END,
					date_facture = CASE WHEN date_facture> '00010101' THEN date_facture ELSE '20991231' END,
					date_expedition = CASE WHEN date_expedition > '00010101' THEN date_expedition ELSE '20991231' END,
					date_solde = CASE WHEN date_solde > '00010101' THEN date_solde ELSE '20991231' END,
					date_expedition_0 = CASE WHEN date_expedition_0 > '00010101' THEN date_expedition_0 ELSE '20991231' END,
					date_solde_0 = CASE WHEN date_solde_0 > '00010101' THEN date_solde_0 ELSE '20991231' END,
					date_expedition_1 = CASE WHEN date_expedition_1 > '00010101' THEN date_expedition_1 ELSE '20991231' END,
					date_solde_1 = CASE WHEN date_solde_1 > '00010101' THEN date_solde_1 ELSE '20991231' END,
					date_expedition_2 = CASE WHEN date_expedition_2 > '00010101' THEN date_expedition_2 ELSE '20991231' END,
					date_solde_2 = CASE WHEN date_solde_2 > '00010101' THEN date_solde_2 ELSE '20991231' END,
					date_expedition_22 = CASE WHEN date_expedition_22 > '00010101' THEN date_expedition_22 ELSE '20991231' END,
					date_solde_22 = CASE WHEN date_solde_22 > '00010101' THEN date_solde_22 ELSE '20991231' END;

					
				UPDATE w_sejours_total SET  
					delai_groupage = CASE WHEN code_sorti = '1' AND date_groupage > date_sortie AND date_groupage < '2099-12-31' AND ghs_id <> 0
								THEN date_groupage  - date_sortie ELSE 0 END, 
					delai_facture = CASE WHEN code_sorti = '1' AND date_facture  > date_sortie AND date_facture < '2099-12-31' AND date_facture > date_sortie  
								THEN date_facture  - date_sortie ELSE 0 END, 
					delai_expedition = CASE WHEN code_sorti = '1' AND date_expedition  > date_sortie AND date_facture < '2099-12-31' AND date_expedition < '2099-12-31'  
								THEN date_expedition  - date_sortie ELSE 0 END, 
					delai_solde = CASE WHEN code_sorti = '1' AND date_solde > date_sortie AND date_facture < '2099-12-31' AND date_solde < '2099-12-31'  
								THEN date_solde - date_sortie ELSE 0 END, 
					delai_expedition_0 = CASE WHEN code_sorti = '1' AND date_expedition_0 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_0 < '2099-12-31'  
								THEN date_expedition_0  - date_sortie ELSE 0 END, 
					delai_solde_0 = CASE WHEN code_sorti = '1'AND date_solde_0 > date_sortie AND date_facture < '2099-12-31' AND date_solde_0 < '2099-12-31'  
								THEN date_solde_0 - date_sortie ELSE 0 END, 
					delai_expedition_1 = CASE WHEN code_sorti = '1' AND date_expedition_1 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_1 < '2099-12-31'  
								THEN date_expedition_1  - date_sortie ELSE 0 END, 
					delai_solde_1 = CASE WHEN code_sorti = '1' AND date_solde_1 > date_sortie AND date_facture < '2099-12-31' AND date_solde_1 < '2099-12-31'  
								THEN date_solde_1 - date_sortie ELSE 0 END, 
					delai_expedition_2 = CASE WHEN code_sorti = '1' AND date_expedition_2 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_2 < '2099-12-31'  
								THEN date_expedition_2  - date_sortie ELSE 0 END, 
					delai_solde_2 = CASE WHEN code_sorti = '1' AND date_solde_2 > date_sortie AND date_facture < '2099-12-31' AND date_solde_2 < '2099-12-31'  
								THEN date_solde_2 - date_sortie ELSE 0 END, 
					delai_expedition_22 = CASE WHEN code_sorti = '1' AND date_expedition_22 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_22 < '2099-12-31'  
								THEN date_expedition_22  - date_sortie ELSE 0 END, 
					delai_solde_22 = CASE WHEN code_sorti = '1' AND date_solde_22 > date_sortie AND date_facture < '2099-12-31' AND date_solde_22 < '2099-12-31'  
								THEN date_solde_22 - date_sortie ELSE 0 END;

				ALTER TABLE w_sejours_total  ADD CONSTRAINT w_sejours_total_pkey PRIMARY KEY(no_sejour);



				UPDATE activite[PX].p_sejours SET

					date_facture = w_sejours_total.date_facture,  
					date_expedition = w_sejours_total.date_expedition,  
					date_solde = w_sejours_total.date_solde,  
					montant_facture_c = w_sejours_total.montant_facture_c,  
					montant_facture_h = w_sejours_total.montant_facture_h,  
					montant_regle_c = w_sejours_total.montant_regle_c,  
					montant_regle_h = w_sejours_total.montant_regle_h,  
					nb_factures = w_sejours_total.nb_factures,  
					nb_factures_regularisation = w_sejours_total.nb_factures_regularisation,  
					nb_factures_rejet = w_sejours_total.nb_rejets,  

					montant_facture_0_c = w_sejours_total.montant_facture_0_c,  
					montant_facture_0_h = w_sejours_total.montant_facture_0_h,  
					montant_regle_0_c = w_sejours_total.montant_regle_0_c,  
					montant_regle_0_h = w_sejours_total.montant_regle_0_h,  
					date_expedition_0 = w_sejours_total.date_expedition_0,  
					date_solde_0 = w_sejours_total.date_solde_0,  

					montant_facture_1_c = w_sejours_total.montant_facture_1_c,  
					montant_facture_1_h = w_sejours_total.montant_facture_1_h,  
					montant_regle_1_c = w_sejours_total.montant_regle_1_c,  
					montant_regle_1_h = w_sejours_total.montant_regle_1_h,  
					date_expedition_1 = w_sejours_total.date_expedition_1,   
					date_solde_1 = w_sejours_total.date_solde_1,  
		 
					montant_facture_2_c = w_sejours_total.montant_facture_2_c,  
					montant_facture_2_h = w_sejours_total.montant_facture_2_h,  
					montant_regle_2_c = w_sejours_total.montant_regle_2_c,  
					montant_regle_2_h = w_sejours_total.montant_regle_2_h,  
					date_expedition_2 = w_sejours_total.date_expedition_2, 
					date_solde_2 = w_sejours_total.date_solde_2,  
		 
					montant_facture_22_c = w_sejours_total.montant_facture_22_c,  
					montant_facture_22_h = w_sejours_total.montant_facture_22_h,  
					montant_regle_22_c = w_sejours_total.montant_regle_22_c,  
					montant_regle_22_h = w_sejours_total.montant_regle_22_h,  
					date_expedition_22 = w_sejours_total.date_expedition_22, 
					date_solde_22 = w_sejours_total.date_solde_22,
					
					montant_comptabilise_c = w_sejours_total.montant_comptabilise_c,  
					montant_comptabilise_h = w_sejours_total.montant_comptabilise_h,  
					montant_comptabilise_0_c = w_sejours_total.montant_comptabilise_0_c,  
					montant_comptabilise_0_h = w_sejours_total.montant_comptabilise_0_h,  
					montant_comptabilise_1_c = w_sejours_total.montant_comptabilise_1_c,  
					montant_comptabilise_1_h = w_sejours_total.montant_comptabilise_1_h,  
					montant_comptabilise_2_c = w_sejours_total.montant_comptabilise_2_c,  
					montant_comptabilise_2_h = w_sejours_total.montant_comptabilise_2_h,  
					montant_comptabilise_22_c = w_sejours_total.montant_comptabilise_22_c,  
					montant_comptabilise_22_h = w_sejours_total.montant_comptabilise_22_h,

					montant_comptabilise_budget_global_c = w_sejours_total.montant_comptabilise_budget_global_c,

					montant_facture_c_actes_inclus_dans_sejour = w_sejours_total.montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour = w_sejours_total.montant_facture_h_actes_inclus_dans_sejour,


					delai_groupage = w_sejours_total.delai_groupage, 
					delai_facture = w_sejours_total.delai_facture, 
					delai_expedition = w_sejours_total.delai_expedition, 
					delai_solde = w_sejours_total.delai_solde, 
					delai_expedition_0 = w_sejours_total.delai_expedition_0, 
					delai_solde_0 = w_sejours_total.delai_solde_0, 
					delai_expedition_1 = w_sejours_total.delai_expedition_1, 
					delai_solde_1 = w_sejours_total.delai_solde_1, 
					delai_expedition_2 = w_sejours_total.delai_expedition_2, 
					delai_solde_2 = w_sejours_total.delai_solde_2, 
					delai_expedition_22 = w_sejours_total.delai_expedition_22, 
					delai_solde_22 = w_sejours_total.delai_solde_22
					
				FROM w_sejours_total
				WHERE w_sejours_total.no_sejour =  p_sejours.no_sejour

				AND (
					p_sejours.date_facture IS DISTINCT FROM w_sejours_total.date_facture OR   
					p_sejours.date_expedition IS DISTINCT FROM w_sejours_total.date_expedition OR   
					p_sejours.date_solde IS DISTINCT FROM w_sejours_total.date_solde OR   
					p_sejours.montant_facture_c IS DISTINCT FROM w_sejours_total.montant_facture_c OR   
					p_sejours.montant_facture_h IS DISTINCT FROM w_sejours_total.montant_facture_h OR   
					p_sejours.montant_regle_c IS DISTINCT FROM w_sejours_total.montant_regle_c OR   
					p_sejours.montant_regle_h IS DISTINCT FROM w_sejours_total.montant_regle_h OR   
					p_sejours.nb_factures IS DISTINCT FROM w_sejours_total.nb_factures OR   
					p_sejours.nb_factures_regularisation IS DISTINCT FROM w_sejours_total.nb_factures_regularisation OR   
					p_sejours.nb_factures_rejet IS DISTINCT FROM w_sejours_total.nb_rejets OR   

					p_sejours.montant_facture_0_c IS DISTINCT FROM w_sejours_total.montant_facture_0_c OR   
					p_sejours.montant_facture_0_h IS DISTINCT FROM w_sejours_total.montant_facture_0_h OR   
					p_sejours.montant_regle_0_c IS DISTINCT FROM w_sejours_total.montant_regle_0_c OR   
					p_sejours.montant_regle_0_h IS DISTINCT FROM w_sejours_total.montant_regle_0_h OR   
					p_sejours.date_expedition_0 IS DISTINCT FROM w_sejours_total.date_expedition_0 OR   
					p_sejours.date_solde_0 IS DISTINCT FROM w_sejours_total.date_solde_0 OR   

					p_sejours.montant_facture_1_c IS DISTINCT FROM w_sejours_total.montant_facture_1_c OR   
					p_sejours.montant_facture_1_h IS DISTINCT FROM w_sejours_total.montant_facture_1_h OR   
					p_sejours.montant_regle_1_c IS DISTINCT FROM w_sejours_total.montant_regle_1_c OR   
					p_sejours.montant_regle_1_h IS DISTINCT FROM w_sejours_total.montant_regle_1_h OR   
					p_sejours.date_expedition_1 IS DISTINCT FROM w_sejours_total.date_expedition_1 OR    
					p_sejours.date_solde_1 IS DISTINCT FROM w_sejours_total.date_solde_1 OR   
		 
					p_sejours.montant_facture_2_c IS DISTINCT FROM w_sejours_total.montant_facture_2_c OR   
					p_sejours.montant_facture_2_h IS DISTINCT FROM w_sejours_total.montant_facture_2_h OR   
					p_sejours.montant_regle_2_c IS DISTINCT FROM w_sejours_total.montant_regle_2_c OR   
					p_sejours.montant_regle_2_h IS DISTINCT FROM w_sejours_total.montant_regle_2_h OR   
					p_sejours.date_expedition_2 IS DISTINCT FROM w_sejours_total.date_expedition_2 OR  
					p_sejours.date_solde_2 IS DISTINCT FROM w_sejours_total.date_solde_2 OR   
		 
					p_sejours.montant_facture_22_c IS DISTINCT FROM w_sejours_total.montant_facture_22_c OR   
					p_sejours.montant_facture_22_h IS DISTINCT FROM w_sejours_total.montant_facture_22_h OR   
					p_sejours.montant_regle_22_c IS DISTINCT FROM w_sejours_total.montant_regle_22_c OR   
					p_sejours.montant_regle_22_h IS DISTINCT FROM w_sejours_total.montant_regle_22_h OR   
					p_sejours.date_expedition_22 IS DISTINCT FROM w_sejours_total.date_expedition_22 OR  
					p_sejours.date_solde_22 IS DISTINCT FROM w_sejours_total.date_solde_22 OR 
					
					p_sejours.montant_comptabilise_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_c OR   
					p_sejours.montant_comptabilise_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_h OR   
					p_sejours.montant_comptabilise_0_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_c OR   
					p_sejours.montant_comptabilise_0_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_h OR   
					p_sejours.montant_comptabilise_1_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_c OR   
					p_sejours.montant_comptabilise_1_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_h OR   
					p_sejours.montant_comptabilise_2_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_c OR   
					p_sejours.montant_comptabilise_2_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_h OR   
					p_sejours.montant_comptabilise_22_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_c OR   
					p_sejours.montant_comptabilise_22_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_h OR   

					p_sejours.montant_comptabilise_budget_global_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_budget_global_c OR   

					p_sejours.montant_facture_c_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_c_actes_inclus_dans_sejour OR   
					p_sejours.montant_facture_h_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_h_actes_inclus_dans_sejour OR

					p_sejours.delai_groupage IS DISTINCT FROM w_sejours_total.delai_groupage OR   
					p_sejours.delai_facture IS DISTINCT FROM w_sejours_total.delai_facture OR   
					p_sejours.delai_expedition IS DISTINCT FROM w_sejours_total.delai_expedition OR   
					p_sejours.delai_solde IS DISTINCT FROM w_sejours_total.delai_solde OR   
					p_sejours.delai_expedition_0 IS DISTINCT FROM w_sejours_total.delai_expedition_0 OR   
					p_sejours.delai_solde_0 IS DISTINCT FROM w_sejours_total.delai_solde_0 OR   
					p_sejours.delai_expedition_1 IS DISTINCT FROM w_sejours_total.delai_expedition_1 OR   
					p_sejours.delai_solde_1 IS DISTINCT FROM w_sejours_total.delai_solde_1 OR   
					p_sejours.delai_expedition_2 IS DISTINCT FROM w_sejours_total.delai_expedition_2 OR   
					p_sejours.delai_solde_2 IS DISTINCT FROM w_sejours_total.delai_solde_2 OR   
					p_sejours.delai_expedition_22 IS DISTINCT FROM w_sejours_total.delai_expedition_22 OR   
					p_sejours.delai_solde_22 IS DISTINCT FROM w_sejours_total.delai_solde_22

				);
		
            ]]>
            </sqlcmd>
        </NODE>

    </NODE>

    <NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">

        <NODE label="Recuperation chiffrier">
            <sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_chiffrier_comptable;

				INSERT INTO activite[PX].p_chiffrier_comptable(
					date_comptable,
					montant_ventes_c, 
					montant_reglements_c, 
					montant_solde_client_c, 
					montant_ventes_h, 
					montant_reglements_h, 
					montant_solde_client_h
				)
				SELECT date(date_trunc('month',MC_PERIODE)) AS date_comptable,
					SUM(CASE WHEN MC_CATECR = 'E' THEN MC_MTDEBIT - MC_MTCREDIT ELSE 0 END) AS montant_ventes_c,
					0::numeric AS montant_reglements_c,
					0::numeric AS montant_solde_client_c,
					SUM(CASE WHEN MC_CATECR = 'H' THEN MC_MTDEBIT - MC_MTCREDIT ELSE 0 END) AS montant_ventes_h,
					0::numeric AS montant_reglements_h,
					0::numeric AS monatnt_solde_client_h
				FROM prod_edlxplore.h_mvtcpt
				WHERE date(MC_PERIODE) >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					MC_CODJRN LIKE 'VENTE%' AND
					MC_NUMCPT LIKE '41%'
				GROUP BY 1
				;
				
				TRUNCATE activite[PX].p_factures_comptables;

				INSERT INTO activite[PX].p_factures_comptables(
					no_facture,
					date_comptable,
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h
				)
				SELECT MC_NUMFAC,
					date(date_trunc('month',MC_PERIODE)) AS date_comptable,
					SUM(CASE WHEN MC_CATECR = 'E' THEN MC_MTDEBIT - MC_MTCREDIT ELSE 0 END) AS montant_ventes_c,
					0::numeric AS montant_reglements_c,
					SUM(CASE WHEN MC_CATECR = 'H' THEN MC_MTDEBIT - MC_MTCREDIT ELSE 0 END) AS montant_ventes_h,
					0::numeric AS montant_reglements_h
				FROM prod_edlxplore.h_mvtcpt
				WHERE date(MC_PERIODE) >= '20180101' AND
					MC_CODJRN LIKE 'VENTE%' AND
					MC_NUMCPT LIKE '41%'
				GROUP BY 1,2
				;

				ANALYSE activite[PX].p_factures_comptables
				;
            ]]>
            </sqlcmd>
        </NODE>

    </NODE>

    <NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
    </NODE>

    <NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">
    </NODE>
</ROOT>
