return: text
lang: plpgsql
parameters:
  p0:
    type: date
    name: i_date_encours
  p1:
    type: text
    name: i_option
src: |
  DECLARE 
    w_NOW date;
    w_date_traitement date;
    w_date_encours_actuelle date;
    w_date_encours_actuelle_shs date;
    w_date_encours date;
    w_date_encours_YYMM text;
    w_date_histo_18 date;
    w_date_histo_12 date;
    w_date_histo_xx date;
    w_date_sortie_max date;
    w_date_histo_coeff_presta date;
    w_OPTION_ENCOURSVALOCP text;
    w_OPTION_ENCOURSMCOSUP text;
    _DATEENCOURS numeric;
    _DATESTARTENCOURS date;
    _NBSEJMIN_HISTOGHS numeric;
    _ENCOURSECARTGHSV numeric;
    _ENCOURSRETROSUP text;
    w_nbsejours_min text;
    w_simul text;
    
  BEGIN
    -- Date du jour = now sauf si date de fermeture
    w_NOW = (SELECT 
      MIN(CASE WHEN code = 'DATEFERMETURE' AND
        valeur <> '' AND
        valeur < to_char(now(),'YYYYMMDD') THEN valeur::date
        ELSE date(now()) END
      )
      FROM activite.t_divers)
    ;
    RAISE NOTICE '%' , 'Parametres. Aujourd''hui : ' || w_NOW;  
  
    -- Ne rien calculer sur etablissement fermé
  
    IF EXISTS (
      SELECT valeur
      FROM activite.t_divers 
      WHERE code IN ('DATEFERMETURE','ACT_DAT_FIN') AND 
        valeur <> '' AND
        (
        (
        valeur_date IS NOT NULL AND
        valeur_date < date(now())
        ) OR
        valeur::date < date(now())
        )
        LIMIT 1
        ) THEN 
      DELETE FROM activite.p_factures_lignes_c WHERE montant_encours <> 0;
      DELETE FROM activite.p_factures_lignes_h WHERE montant_encours <> 0;
  
      DELETE
      FROM activite.p_factures_lignes_c
      USING activite.p_factures
      WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
        p_factures.montant_encours_c <> 0
      ;
      DELETE
      FROM activite.p_factures_lignes_h
      USING activite.p_factures
      WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
        (p_factures.montant_encours_c <> 0 OR p_factures.montant_encours_h)
      ;
      
      UPDATE activite.p_factures SET 
        montant_encours_c = 0,
        montant_encours_0_c = 0,
        montant_encours_1_c = 0,
        montant_encours_2_c = 0,
        montant_encours_22_c = 0,
        montant_encours_h = 0,
        montant_encours_0_h = 0,
        montant_encours_1_h = 0,
        montant_encours_2_h = 0,
        montant_encours_22_h = 0
      WHERE montant_encours_c <> 0 OR montant_encours_h <> 0;
  
      TRUNCATE activite.p_facture_ligne_valorise_c
      ;
  
      return 'Valorisation désactivée car établissement fermé';
  
    END IF;
    
  
    -- Paramétrage
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'DATEENCOURS',
      'Date cloture encours',
      '5',
      'Décalage pour cloture encours en nombre de jours '
    WHERE 'DATEENCOURS' NOT IN (SELECT code FROM activite.t_divers);
    _DATEENCOURS = base.cti_to_number((SELECT valeur FROM activite.t_divers WHERE code = 'DATEENCOURS'));
    IF _DATEENCOURS <= 0 THEN 
      _DATEENCOURS = 5;
    END IF;
  
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'DATESTARTENCOURS',
      'Date démarrage stockage encours encours',
      '20110101',
      'Date démarrage stockage encours encours (AAAAMMJJ)'
    WHERE 'DATESTARTENCOURS' NOT IN (SELECT code FROM activite.t_divers);
    _DATESTARTENCOURS = (SELECT base.cti_to_date(valeur) FROM activite.t_divers WHERE code = 'DATESTARTENCOURS');
    IF _DATESTARTENCOURS < '20120101' OR _DATESTARTENCOURS IS NULL THEN
      _DATESTARTENCOURS = '20120101';
    END IF;
    RAISE NOTICE '%' , 'Parametres. Demarrage en-cours : ' || _DATESTARTENCOURS; 
    _DATESTARTENCOURS = date_trunc('month',_DATESTARTENCOURS) - interval '1 day';
    -- Paramètres pour génération fictive d'EXH
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSBORNEHAUTE',
      'Borne haute pour génération EXH en plus du GHS moyen',
      '15',
      'Borne haute pour génération EXH en plus du GHS moyen sur encours dossiers non groupés (voir ENCOURSEXHMOYEN)'
    WHERE 'ENCOURSBORNEHAUTE' NOT IN (SELECT code FROM activite.t_divers);
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSEXHMOYEN',
      'EXH moyen pour génération EXH en plus du GHS moyen',
      '50',
      'Valeur EXH moyen pour génération EXH en plus du GHS moyen sur encours dossiers non groupés (voir ENCOURSBORNEHAUTE)'
    WHERE 'ENCOURSEXHMOYEN' NOT IN (SELECT code FROM activite.t_divers);
    -- Paramètres pour génération fictive GHS sur esthétique
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSGHMSANSGHS',
      'Pas de génération de GHS pour les GHM',
      '14Z08Z',
      'Pas de génération de GHS pour les GHM'
    WHERE 'ENCOURSGHMSANSGHS' NOT IN (SELECT code FROM activite.t_divers);
    -- Paramètres pour génération fictive GHS sur esthétique
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSRETROSUP',
      'Nombre de mois pour calcul taux prestations',
      '18',
      '18 ou 12'
    WHERE 'ENCOURSRETROSUP' NOT IN (SELECT code FROM activite.t_divers);
    
    _ENCOURSRETROSUP = (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSRETROSUP');
  
    -- Nombre de séjours minimum par catégorie (= par règle) d'historique de facturation du GHS
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'NBSEJMIN_HISTOGHS',
      'Histo factu GHS : nb séjours min',
      '10',
      'Valorisation : nombre minimum de séjours par catégorie pour l''historique de facturation GHS (par défaut 10)'
    WHERE 'NBSEJMIN_HISTOGHS' NOT IN (SELECT code FROM activite.t_divers);
    _NBSEJMIN_HISTOGHS = base.cti_to_number((SELECT valeur FROM activite.t_divers WHERE code = 'NBSEJMIN_HISTOGHS'));
    IF _NBSEJMIN_HISTOGHS <= 0 THEN 
      _NBSEJMIN_HISTOGHS = 10;
    END IF;
    w_nbsejours_min = to_char(_NBSEJMIN_HISTOGHS, 'FM999');
    
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSACTIVE',
      'Encours activés',
      '0',
      '1 = Stockage des encours activé'
    WHERE 'ENCOURSACTIVE' NOT IN (SELECT code FROM activite.t_divers);
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSVALOCP',
      'Valorisation CP',
      '0',
      '1 = Ne pas tenir compte de la demande CP dans la valorisation'
    WHERE 'ENCOURSVALOCP' NOT IN (SELECT code FROM activite.t_divers);
    w_OPTION_ENCOURSVALOCP = (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSVALOCP');
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSGHSMBB',
      'GHS moyen des bébés sur encours',
      '0',
      'Pour les séjours en maternité sans GHS bébé, PU du GHS bébé à générer'
    WHERE 'ENCOURSGHSMBB' NOT IN (SELECT code FROM activite.t_divers);
  
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSMCOSUP',
      'Valorisation Suppléments MCO',
      '0',
      '1 = Sur dossiers groupés validés, valoriser les suppléments (SRC,REA,NNx,STF) saisis (pour les autres utiliser la moyenne)'
    WHERE 'ENCOURSMCOSUP' NOT IN (SELECT code FROM activite.t_divers);
    w_OPTION_ENCOURSMCOSUP = (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSMCOSUP');
  
    -- Paramètres pour generation encours sur honoraires medecins salaries
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSMEDSAL',
      'Génération encours sur médecins salariés',
      '0',
      '1 = Génération encours sur médecins salariés'
    WHERE 'ENCOURSMEDSAL' NOT IN (SELECT code FROM activite.t_divers);
  
    
  
    -- Paramètres pour comparer ghs valorisé avec moyenne / médecin -> Alerte expert
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSECARTGHSV',
      'Montant écart pour alerter si le GHS connu est sous valorisé / moyenne médecin',
      '0',
      'Les GHS groupés sont valorisés aussi par la méthode des moyennes et les deux résultats sont comparés'
    WHERE 'ENCOURSECARTGHSV' NOT IN (SELECT code FROM activite.t_divers);
  
    _ENCOURSECARTGHSV = base.cti_to_number(valeur) FROM activite.t_divers WHERE code = 'ENCOURSECARTGHSV';
  
    -- Paramètre pour génération des en-cours SUR BG
    INSERT INTO activite.t_divers (code, texte, valeur, description)
    SELECT
      'ENCOURSACTIVEBG',
      'Encours activés sur BG',
      '0',
      '1 = Stockage des encours BG activé'
    WHERE 'ENCOURSACTIVEBG' NOT IN (SELECT code FROM activite.t_divers);
  
    
  
    IF EXISTS (SELECT date_encours FROM activite.p_factures_encours LIMIT 1) THEN
      UPDATE activite.t_divers
      SET valeur = '1'
      WHERE code = 'ENCOURSACTIVE';
    END IF;
    _DATEENCOURS = base.cti_to_number((SELECT valeur FROM activite.t_divers WHERE code = 'DATEENCOURS'));
    IF _DATEENCOURS <= 0 THEN 
      _DATEENCOURS = 5;
    END IF;
    -- Initialisations
    -- Mise à jour factures externes pour affecter à la date d'entrée
    UPDATE activite.p_factures
    SET date_fin = date_debut
    FROM activite.p_sejours
    WHERE p_factures.no_sejour = p_sejours.no_sejour AND
      type_sejour = '3' AND
      (
      date_fin = date(date_debut + interval '1 day') OR
      date_fin = '20991231'
      )
    ;
    	-- Les GMT saisis en hospitalisation complète ne doivent pas être traités
  	DELETE FROM activite.p_factures_lignes_non_facturees_c
  	USING(
   		SELECT 
   			no_facture
  			, prestation_id
  		FROM activite.p_factures_lignes_non_facturees_c 
  			JOIN activite.t_prestations ON p_factures_lignes_non_facturees_c.prestation_id = t_prestations.oid
  			JOIN activite.t_lieux ON t_lieux.oid = p_factures_lignes_non_facturees_c.lieu_id
  			JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
  			JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
  		WHERE t_prestations.code = 'GMT'
  			AND t_modes_traitement.code = '03'
  		GROUP BY
  			no_facture
  			, prestation_id
  	) subview
      WHERE 
  		p_factures_lignes_non_facturees_c.no_facture = subview.no_facture
      	AND p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id
      ;
    -- Initialisation des tiers payant sur les non facturés (cas de CEGI LOGHOS ou de SIGEMS, les tiers payant ne sont pas connu sur les non facturés
    
  
    -- D'abord selon le tiers connu sur le patient
    UPDATE activite.p_factures SET
      tiers_payant_1_id = subview.tiers_payant_1_id,
      tiers_payant_2_id = subview.tiers_payant_2_id
    FROM
    (
    SELECT p_factures.no_facture, subview.tiers_payant_1_id, subview.tiers_payant_2_id
    FROM activite.p_factures
    JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
    JOIN
    (
    SELECT no_patient, 
      (MAX(ARRAY[date_entree::text,p_factures.tiers_payant_1_id::text]))[2]::bigint AS tiers_payant_1_id,
      (MAX(ARRAY[date_entree::text,p_factures.tiers_payant_2_id::text]))[2]::bigint AS tiers_payant_2_id
    FROM activite.p_factures
    JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
    WHERE p_factures.tiers_payant_1_id <> 0 
    GROUP BY 1
    ) subview ON p_sejours.no_patient = subview.no_patient
    WHERE p_factures.code_facture = '0' AND
      p_factures.tiers_payant_1_id = 0
    ) subview
    WHERE p_factures.no_facture = subview.no_facture
    ;
  
    -- Pour le reste, le code NR1 
    UPDATE activite.p_factures
    SET tiers_payant_1_id = t_tiers_payant.oid
    FROM activite.t_tiers_payant
    WHERE p_factures.code_facture = '0' AND
      p_factures.tiers_payant_1_id = 0 AND
      t_tiers_payant.code_original = '*CTINR1'
    ;
  
    
    -- désactivation index
    RAISE NOTICE '%' , 'Initialisations. Desactivation index';  
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_2');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_4');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_5');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_6');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_7');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_8');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_9');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_10');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_11');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_2');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_3');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_4');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_5');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_6');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_7');
    PERFORM base.cti_disable_index('activite', 'i_factures_encours_lignes_c_8');
    RAISE NOTICE '%' , 'Initialisations. Creation tables de travail';  
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_calcul_parametres') THEN
      CREATE TEMP TABLE w_cti_encours_calcul_parametres
      (
        date_encours date,
        coefficient_mco numeric,
        rubrique_facturation_ghs_id bigint,
        rubrique_comptabilisation_ghs_id bigint,
        prestation_ghs_id bigint,
        rubrique_facturation_ghs_sea_id bigint,
        rubrique_comptabilisation_ghs_sea_id bigint,
        prestation_ghs_sea_id bigint,
        rubrique_facturation_exh_id bigint,
        rubrique_comptabilisation_exh_id bigint,
        prestation_exh_id bigint,
        rubrique_facturation_i01_id bigint,
        rubrique_comptabilisation_i01_id bigint,
        prestation_i01_id bigint
      ) ;
    END IF;
    
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_calcul_parametres_services') THEN
      CREATE TEMP TABLE w_cti_encours_calcul_parametres_services
      (
        service_facturation_id bigint,
        type_sejour text,
        rubrique_facturation_ghs_id bigint,
        prestation_ghs_id bigint,
        rubrique_facturation_exh_id bigint,
        prestation_exh_id bigint
      ); 
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_calcul_parametres_services_prestations') THEN
      CREATE TEMP TABLE w_cti_encours_calcul_parametres_services_prestations
      (
        coefficient_mco numeric,
        lieu_service_id bigint,
        lieu_unite_fonctionnelle_id bigint,
        nb_ambulatoires numeric,
        nb_externes numeric,
        nb_seances numeric,
        nb_journees numeric,
        nb_journees_cp numeric,
        prestation_id bigint,
        prestation_code text,
        tranche_ght text,
        prestation_type_valorisation text,
        rubrique_facturation_id bigint,
        prix_unitaire numeric,
        nombre numeric,
        coefficient numeric,
        prix_unitaire_moyen_1 numeric,
        nb_prix_unitaire_moyen_1 numeric,
        prix_unitaire_moyen_3 numeric,
        nb_prix_unitaire_moyen_3 numeric,
        prix_unitaire_moyen numeric,
        regle_prestation_texte text,
        coefficient_calcule numeric DEFAULT 0,
        prix_unitaire_calcule numeric DEFAULT 0,
        coefficient_is_force text DEFAULT '0',
        prix_unitaire_is_force text DEFAULT '0',
        type_ligne text DEFAULT '',
        prestation_10p_code text DEFAULT '',
        rubrique_code text DEFAULT '',
        rubrique_10p_code text DEFAULT '',
        prestation_10p_id bigint DEFAULT 0,
        rubrique_10p_id bigint DEFAULT 0
      ); 
    END IF;
    
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_calcul_parametres_services_journees') THEN
      CREATE TEMP TABLE w_cti_encours_calcul_parametres_services_journees
      (
        lieu_service_id bigint,
        lieu_unite_fonctionnelle_id bigint,
        nb_ambulatoires numeric,
        nb_externes numeric,
        nb_seances numeric,
        nb_journees bigint,
        nb_journees_cp bigint
      );
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_sejours') THEN
      CREATE TEMP TABLE w_cti_encours_sejours
      (
        sejour_id bigint NOT NULL,
        no_sejour text NOT NULL,
        type_sejour character(1),
        est_budget_global text,
        secteur_tarif text default '2',
        medecin_sejour_id bigint,
        specialite_medecin_sejour_id bigint,
        lieu_sortie_service_id bigint,
        lieu_sortie_unite_fonctionnelle_id bigint,
        code_sorti numeric(1),
        lieu_sortie_id bigint,
        mode_sortie character(1),
        date_groupage date,
        tiers_payant_1_id bigint,
        tiers_payant_2_id bigint,
        nb_ghs numeric,
        ghm_id bigint,
        ghs_id bigint,
        ghs_bebe1_id bigint,
        ghs_bebe2_id bigint,
        ghs_bebe3_id bigint,
        particularites_encours_service text,
        type_t2a text,
        CONSTRAINT w_cti_encours_sejours_pkey PRIMARY KEY (no_sejour)
      ) ;
    END IF;
    
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_histo_sejour_facture') THEN
      CREATE TEMP TABLE w_cti_encours_histo_sejour_facture
      (
        no_sejour text,
        date_fin date,
        classe_ghm text default '',
        medecin_sejour_id bigint,
        specialite_medecin_sejour_id bigint,
        lieu_sortie_service_id bigint,
        lieu_sortie_unite_fonctionnelle_id bigint,
        nb_ghs numeric,
        tranche_sejour text,
        duree_sejour integer,
        montant_ghs numeric,
        montant_ghs_original numeric,
        taux_0 numeric,
        taux_1 numeric,
        taux_2 numeric
      )  ;
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_histo_ghs') THEN
      CREATE TEMP TABLE w_cti_encours_histo_ghs
      (
        classe_ghm text,
        regle text,
        medecin_sejour_id bigint,
        specialite_medecin_sejour_id bigint,
        lieu_sortie_service_id bigint,
        lieu_sortie_unite_fonctionnelle_id bigint,
        tranche_sejour text,
        duree_sejour integer,
        nombre bigint,
        montant_moyen_ghs numeric,
        medecin_sejour_texte text default '',
        specialite_medecin_sejour_texte text default '',
        lieu_sortie_service_texte text default '',
        lieu_sortie_unite_fonctionnelle_texte text default '',
        tranche_sejour_texte text default '',
        duree_sejour_texte text default ''
      ) ;
      CREATE INDEX w_cti_encours_histo_ghs_i1
        ON w_cti_encours_histo_ghs
        USING btree
        (medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id)
      ;
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_histo_dms_sejours') THEN
      CREATE TEMP TABLE w_cti_encours_histo_dms_sejours
      (
        no_sejour text,
        medecin_sejour_id bigint,
        specialite_medecin_sejour_id bigint,
        lieu_sortie_service_id bigint,
        lieu_sortie_unite_fonctionnelle_id bigint,
        date_fin date,
        date_debut date
      ) ;
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_histo_dms') THEN
      CREATE TEMP TABLE w_cti_encours_histo_dms
      (
        regle text,
        medecin_sejour_id bigint,
        specialite_medecin_sejour_id bigint,
        lieu_sortie_service_id bigint,
        lieu_sortie_unite_fonctionnelle_id bigint,
        dms numeric,
        occurences bigint
      ) ;
    END IF;
    IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_ghm_sans_ghs') THEN
      CREATE TEMP TABLE w_cti_encours_ghm_sans_ghs
      (
        ghm_id bigint
      ) ;
    END IF;
    TRUNCATE w_cti_encours_ghm_sans_ghs;
    INSERT INTO w_cti_encours_ghm_sans_ghs
    SELECT oid 
    FROM base.t_ghm 
    WHERE code IN ('14Z08Z')
    ;
    INSERT INTO w_cti_encours_ghm_sans_ghs
    SELECT oid 
    FROM base.t_ghm 
    JOIN activite.t_divers ON t_divers.code = 'ENCOURSGHMSANSGHS' 
    WHERE t_divers.valeur LIKE '%' || t_ghm.code || '%' AND 
      oid <> 0 AND 
      length(t_ghm.code) = 6 AND
      t_ghm.code <> '14Z08Z'
    ;	
    
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures
    (
      oid bigint,
      sejour_id bigint NOT NULL,
      no_sejour text NOT NULL,
      type_sejour text,
      classe_ghm text,
      no_facture text NOT NULL,
      no_facture_encours text NOT NULL,
      no_facture_reference text NOT NULL,
      date_encours date,
      date_debut date,
      date_fin date,
      lieu_sortie_id bigint,
      mode_sortie text,
      ghs_id bigint DEFAULT 0,
      ghm_id bigint DEFAULT 0,
      code_cp_demandee character(1) DEFAULT 0,
      montant_valorise_c numeric(13,2) DEFAULT 0,
      montant_valorise_0_c numeric(13,2) DEFAULT 0,
      montant_valorise_1_c numeric(13,2) DEFAULT 0,
      montant_valorise_2_c numeric(13,2) DEFAULT 0,
      montant_encours_c numeric(13,2) DEFAULT 0,
      montant_encours_0_c numeric(13,2) DEFAULT 0,
      montant_encours_1_c numeric(13,2) DEFAULT 0,
      montant_encours_2_c numeric(13,2) DEFAULT 0,
      montant_valorise_h numeric(13,2) DEFAULT 0,
      etat character(1) DEFAULT ''::bpchar,
      type_t2a character(1) DEFAULT '0'::bpchar,
      est_budget_global text,
      secteur_tarif text default '2',
      ghs_bebe1_id bigint DEFAULT 0,
      ghs_bebe2_id bigint DEFAULT 0,
      ghs_bebe3_id bigint DEFAULT 0,
      code_sorti character(1) DEFAULT '0'::bpchar,
      lieu_sortie_service_id bigint DEFAULT 0,
      lieu_sortie_unite_fonctionnelle_id bigint DEFAULT 0,
      medecin_sejour_id bigint DEFAULT 0,
      specialite_medecin_sejour_id bigint,
      duree_sejour integer DEFAULT 0,
      tranche_sejour character(1) DEFAULT '0'::bpchar,
      regle_ghs text DEFAULT ''::text,
      regle_dms text DEFAULT '0'::text,
      dms numeric default 0,
      tiers_payant_1_id bigint,
      tiers_payant_2_id bigint,
      particularites_encours_service text,
      uniquement_prestations_saisies text default '0',
      ignorer text default '0',
      CONSTRAINT w_cti_encours_factures_pkey PRIMARY KEY (no_facture)
    );
  	
    CREATE INDEX IF NOT EXISTS w_cti_encours_factures_i1
      ON w_cti_encours_factures
      USING btree
      (no_sejour);
  	  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_deja_cpc
    (
      no_facture_reference text NOT NULL,
      CONSTRAINT w_cti_encours_factures_deja_cpc_pkey PRIMARY KEY (no_facture_reference)
    );
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_histo_taux
    (
      service_facturation_id bigint,
      taux_ghs_1 numeric,
      nb numeric,
      regle_taux_texte text,
      CONSTRAINT w_cti_encours_factures_histo_taux_pkey PRIMARY KEY (service_facturation_id)
    );
  	
    CREATE TEMP SEQUENCE IF NOT EXISTS w_cti_encours_factures_lignes_c_sequence;
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_lignes_c
    (
      oid bigint NOT NULL DEFAULT nextval('w_cti_encours_factures_lignes_c_sequence'::regclass),
      no_sejour text NOT NULL,
      no_facture text NOT NULL,
      date_debut date,
      date_fin date,
      nb_rubrique numeric(5) DEFAULT 1,
      coefficient numeric(7,2) DEFAULT 1,
      coefficient_mco numeric(7,4) DEFAULT 1,
      prestation_id bigint DEFAULT 0,
      lpp_id bigint DEFAULT 0,
      ucd_id bigint DEFAULT 0,
      rubrique_facturation_id bigint DEFAULT 0,
      rubrique_comptabilisation_id bigint DEFAULT 0,
      ghs_id bigint DEFAULT 0,
      prix_unitaire numeric(13,2) DEFAULT 0,
      borne_basse numeric(5) DEFAULT 0,
      borne_haute numeric(5) DEFAULT 0,
      forfait_exb numeric(13,2) DEFAULT 0,
      tarif_exb numeric(13,2) DEFAULT 0,
      duree_sejour numeric(7) DEFAULT 0,
      nb_prestation numeric(5) DEFAULT 1,
      montant_encours numeric(13,2) DEFAULT 0,
      montant_encours_0 numeric(13,2) DEFAULT 0,
      montant_encours_1 numeric(13,2) DEFAULT 0,
      montant_encours_2 numeric(13,2) DEFAULT 0,
      montant_encours_22 numeric(13,2) DEFAULT 0,
      type_ligne text DEFAULT ''::text,
      regle_ghs text DEFAULT ''::text,
      lieu_id bigint DEFAULT 0,
      regle_coefficient numeric DEFAULT 0,
      regle_texte text,
      prix_unitaire_calcule numeric(13,2) DEFAULT 0,
      coefficient_calcule numeric(13,2) DEFAULT 0,
      ignorer text default '0'
    );
  
    CREATE INDEX IF NOT EXISTS w_cti_encours_factures_lignes_c_i1
      ON w_cti_encours_factures_lignes_c
      USING btree
      (no_facture);
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_factures_lignes_non_facturees_c
    (
      no_sejour text,
      no_facture text,
      prestation_code character varying,
      only_jour_sortie text,
      type_valorisation_non_facture text
    );
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_actes_se1234
    (
      oid bigint,
      code text,
      prestation_code text
    );
    CREATE INDEX IF NOT EXISTS w_cti_encours_actes_se1234_i1
      ON w_cti_encours_actes_se1234
      USING btree
      (oid);
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_se1234
    (
      no_facture text,
      acte_se text,
      type_se text
    );
  
    CREATE INDEX IF NOT EXISTS w_cti_encours_se1234_i1
      ON w_cti_encours_se1234
      USING btree
      (no_facture);
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_lignes_sup_c
    (
      from_oid bigint,
      prestation_code text,
      date_debut_ghs date,
      date_fin_ghs date,
      nb_prestation_ghs integer,
      oid bigint,
      no_sejour text,
      no_facture text,
      date_debut date,
      date_fin date,
      nb_rubrique numeric(5),
      coefficient numeric(7,2),
      coefficient_mco numeric(7,4),
      prestation_id bigint,
      lpp_id bigint DEFAULT 0,
      ucd_id bigint DEFAULT 0,
      rubrique_facturation_id bigint,
      rubrique_comptabilisation_id bigint,
      ghs_id bigint,
      prix_unitaire numeric(13,2),
      borne_basse numeric(5),
      borne_haute numeric(5),
      forfait_exb numeric(13,2),
      tarif_exb numeric(13,2),
      duree_sejour numeric(7),
      nb_prestation numeric(5),
      montant_encours numeric(13,2),
      montant_encours_0 numeric(13,2),
      montant_encours_1 numeric(13,2),
      montant_encours_2 numeric(13,2),
      montant_encours_22 numeric(13,2),
      type_ligne text,
      regle_ghs text,
      lieu_id bigint,
      regle_coefficient numeric,
      regle_texte text,
      prix_unitaire_calcule numeric(13,2) DEFAULT 0,
      coefficient_calcule numeric(13,2) DEFAULT 0,
      ignorer text default '0'
    );
  
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_lignes_sup_c_gen
    (
      from_oid bigint,
      no_sejour text,
      no_facture text,
      date_debut date,
      date_fin date,
      lieu_id bigint,
      rubrique_facturation_id bigint,
      rubrique_comptabilisation_id bigint,
      prestation_id bigint,
      lpp_id bigint DEFAULT 0,
      ucd_id bigint DEFAULT 0,
      nb_rubrique integer,
      nb_prestation integer,
      coefficient numeric(7,2),
      coefficient_mco numeric(7,4),
      prix_unitaire numeric(13,2),
      oid bigint,
      montant_encours numeric,
      type_ligne text,
      regle_ghs text,
      regle_coefficient numeric,
      regle_texte text
    );
  
  	CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_factures_lignes_sup_c_gen_tot
    (
      from_oid bigint,
      nb_rubrique bigint,
      nb_prestation bigint,
      montant_encours numeric
    );
    
    CREATE TEMP TABLE IF NOT EXISTS w_cti_encours_repartition_tp
    (
      rubrique_facturation_id bigint NOT NULL,
      coeff_1 numeric,
      coeff_2 numeric,
      CONSTRAINT w_cti_encours_repartition_tp_pk PRIMARY KEY (rubrique_facturation_id)
    );
  
  	RAISE NOTICE '%' , 'Initialisations. Repartition par tiers payant';  
          
    TRUNCATE w_cti_encours_repartition_tp;
    
    INSERT INTO w_cti_encours_repartition_tp
    SELECT
      rubrique_facturation_id,
      base.cti_division(SUM(montant_facture_1) , SUM(montant_facture)) AS coeff_1,
      base.cti_division(SUM(montant_facture_2 + montant_facture_22) , SUM(montant_facture)) AS coeff_2
    FROM activite.p_factures_lignes_c
      JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
    WHERE tiers_payant_1_id <> 0 ANd montant_facture <> 0 AND 
      p_factures_lignes_c.date_fin BETWEEN '20100301' AND w_NOW
    GROUP BY 1;
    UPDATE w_cti_encours_repartition_tp SET coeff_2 = 0 WHERE coeff_2 < 0.01;
    UPDATE w_cti_encours_repartition_tp SET coeff_2 = 1 - coeff_1 WHERE coeff_2 >= 0.01 AND 1 - coeff_1 - coeff_2 < 0.01;
  
  	-- Ménage selon paramétrage
  	IF i_option NOT ILIKE '%-nogen%' THEN
  		DELETE 
  		FROM activite.p_factures_encours
  		WHERE code_origine = 'C' AND date_encours < (SELECT date(date_trunc('month',base.cti_to_date(valeur))) FROM activite.t_divers WHERE code = 'DATESTARTENCOURS')
  		;
  		DELETE FROM activite.p_factures_encours_lignes_c
  		WHERE NOT EXISTS (SELECT 'NOT_TO_DELETE' FROM activite.p_factures_encours WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture)
  		AND p_factures_encours_lignes_c IS NOT NULL;
  	END IF;
  	-- Retraitement d'un mois
  	IF i_date_encours IS NOT NULL AND i_option NOT ILIKE '%-nogen%' THEN
  		DELETE FROM activite.p_factures_encours
  		USING w_cti_encours_calcul_parametres
  		WHERE date_trunc('month',p_factures_encours.date_encours) >= date_trunc('month',i_date_encours) AND 
  			code_origine = 'C';  		
  		
      DELETE FROM activite.p_factures_encours_lignes_c
  		WHERE NOT EXISTS (SELECT 'NOT_TO_DELETE' FROM activite.p_factures_encours WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture)
  		AND p_factures_encours_lignes_c IS NOT NULL;
  	END IF;
  	-- Génération ou regénération des encours
  	RAISE NOTICE '%' , 'Generation encours';
  	-- date encours actuelle spécial SHS
  	w_date_encours_actuelle_shs = 
  	CASE WHEN EXISTS(SELECT nspname from pg_namespace where nspname = 'prod_shs')
  	THEN (SELECT date(date_trunc('month', MAX(date_vente)) + interval '2 month' - interval '1 day')
  		FROM activite.p_factures
  			JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
  			JOIN activite.t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid AND t_rubriques_facturation.code_original = '111'
  		WHERE code_vente = '1')
  	ELSE '2099-12-31' END;
  	-- date encours actuelle standard
  	w_date_encours_actuelle = date(CASE WHEN EXTRACT('day' FROM w_NOW) <= _DATEENCOURS THEN date_trunc('month', w_NOW) - interval '1 day' ELSE date_trunc('month', w_NOW) + interval '1 month' - interval '1 day' END);
  	-- Pour SHS, Si date en cours < date standard (ventes pas faites)
  	IF w_date_encours_actuelle_shs < w_date_encours_actuelle THEN
  		w_date_encours_actuelle = w_date_encours_actuelle_shs;
  	END IF;
  	-- Stockage date encours active
  	INSERT INTO activite.t_divers (code, texte, valeur, description, valeur_date)
  	SELECT
  		'ENCOURSNOW',
  		'Date encours calculés',
  		w_date_encours_actuelle::text,
  		'Date des encours actuellement calculés (non modifiable)',
  		w_date_encours_actuelle
  	WHERE 'ENCOURSNOW' NOT IN (SELECT code FROM activite.t_divers);
  	UPDATE activite.t_divers SET
  		valeur = w_date_encours_actuelle::text,
  		valeur_date = w_date_encours_actuelle
  	WHERE code = 'ENCOURSNOW'
  	;
  	
  	w_date_encours = _DATESTARTENCOURS;
  	IF i_option ILIKE '%-nogen%' THEN
  		w_date_encours = date(date_trunc('month', w_date_encours_actuelle) - interval '1 day');
  	END IF;
  	IF NOT EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN
  		w_date_encours = date(date_trunc('month', w_date_encours_actuelle) - interval '1 day');
  	END IF;
  	LOOP
  		w_date_encours = date(date_trunc('month', w_date_encours) + interval '2 month' - interval '1 day');
  		w_date_encours_YYMM = to_char(w_date_encours, 'MM YYYY');
  		RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Generation encours. Analyse.';
  		IF w_date_encours > date(date_trunc('month',now())+interval '2 month') THEN
  			EXIT;
  		END IF;
  		IF w_date_encours > w_date_encours_actuelle THEN
  			EXIT;
  		END IF;
  		IF i_date_encours IS NOT NULL AND w_date_encours > i_date_encours THEN
  			EXIT;
  		END IF;
  		IF w_date_encours < w_date_encours_actuelle AND 
  			EXISTS (SELECT date_encours FROM activite.p_factures_encours WHERE code_origine = 'C' AND date_trunc('month', date_encours) = date_trunc('month', w_date_encours) LIMIT 1) THEN
  			CONTINUE;
  		END IF;
  		IF w_date_encours < w_date_encours_actuelle AND 
  			NOT EXISTS (SELECT date_vente FROM activite.p_factures WHERE code_vente = '1' AND date_trunc('month', date_vente) = date_trunc('month', w_date_encours) LIMIT 1) THEN
  			CONTINUE;
  		END IF;
  		
  		IF w_date_encours = w_date_encours_actuelle THEN
  			w_date_traitement = w_NOW;
  			w_date_sortie_max = w_NOW + CASE WHEN date_part('hour' ,w_NOW) > 18 THEN interval '1 day' ELSE interval '0 day' END;
  		ELSE
  			w_date_traitement = w_date_encours + interval '15 days';
  			w_date_sortie_max = w_date_traitement;
  		END IF;
  		w_date_traitement = date(w_date_traitement);
  		
  		w_date_histo_18 = date(date_trunc('month',w_date_encours) - interval '18 month');
  		w_date_histo_12 = date(date_trunc('month',w_date_encours) - interval '12 month');
  		w_date_histo_xx = w_date_histo_18;
  		w_date_histo_coeff_presta = date(date_trunc('month',w_date_encours) - (_ENCOURSRETROSUP || 'month')::interval);
      
      RAISE NOTICE '%. %' , w_date_histo_coeff_presta, 'Date de calcul coefficient prestations ENCOURSRETROSUP';  
  
  		w_date_sortie_max = date(w_date_sortie_max);
  		RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Generation encours ' || w_date_encours_YYMM || ' ' || w_date_traitement::text;
  		-- Raz tables de travail
  		TRUNCATE w_cti_encours_calcul_parametres;
  		TRUNCATE w_cti_encours_calcul_parametres_services;
  		TRUNCATE w_cti_encours_calcul_parametres_services_prestations;
  		TRUNCATE w_cti_encours_calcul_parametres_services_journees;
  		TRUNCATE w_cti_encours_sejours;
  		TRUNCATE w_cti_encours_histo_sejour_facture;
  		TRUNCATE w_cti_encours_histo_ghs;
  		TRUNCATE w_cti_encours_histo_dms_sejours;
  		TRUNCATE w_cti_encours_histo_dms;
  		TRUNCATE w_cti_encours_factures_histo_taux;
  		TRUNCATE w_cti_encours_factures;
  		TRUNCATE w_cti_encours_factures_deja_cpc;
  		TRUNCATE w_cti_encours_factures_lignes_c;
  		TRUNCATE w_cti_factures_lignes_non_facturees_c;
  		TRUNCATE w_cti_encours_se1234;
  		TRUNCATE w_cti_encours_actes_se1234;
  		TRUNCATE w_cti_encours_factures_lignes_sup_c;
  		TRUNCATE w_cti_encours_factures_lignes_sup_c_gen;
  		TRUNCATE w_cti_encours_factures_lignes_sup_c_gen_tot;
  		-- Correction coefficient MCO
  		-- Initialisation du coefficient MCO non alimenté (exemple WEB100T)
  		UPDATE activite.p_factures_lignes_c
  		SET coefficient_mco = coefficient_mco_calcul
  		FROM activite.t_prestations, base.v_coefficient_mco
  		WHERE 
  			prestation_id = t_prestations.oid AND
  			t_prestations.code IN ('GHS', 'EXH') AND
  			montant_facture <> 0 AND
  			coefficient_mco = 1 AND
  			date(p_factures_lignes_c.date_fin) BETWEEN v_coefficient_mco.date_debut AND v_coefficient_mco.date_fin
  		;
  		
  		
  		-- Paramétrage des GHS
  		RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Parametrage GHS';  
  				INSERT INTO w_cti_encours_calcul_parametres 
  				SELECT
  					w_date_encours as date_encours,
  					(MAX(Array[date(p_factures_lignes_c.date_fin) - w_NOW, coefficient_mco]))[2] AS coefficient_mco,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_facturation_id]))[2] AS rubrique_facturation_ghs_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_comptabilisation_id]))[2] AS rubrique_comptabilisation_ghs_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, prestation_id]))[2] AS prestation_ghs_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour = '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_facturation_id]))[2] AS rubrique_facturation_ghs_sea_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour = '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_comptabilisation_id]))[2] AS rubrique_comptabilisation_ghs_sea_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'GHS' AND type_sejour = '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, prestation_id]))[2] AS prestation_ghs_sea_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'EXH' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_facturation_id]))[2] AS rubrique_facturation_exh_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'EXH' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_comptabilisation_id]))[2] AS rubrique_comptabilisation_exh_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'EXH' AND type_sejour <> '5' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, prestation_id]))[2] AS prestation_exh_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'I01' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_facturation_id]))[2] AS rubrique_facturation_I01_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'I01' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, rubrique_comptabilisation_id]))[2] AS rubrique_comptabilisation_I01_id,
  					(MAX(Array[CASE WHEN t_prestations.code = 'I01' THEN date(p_factures_lignes_c.date_fin) - w_NOW ELSE -99999999 END, prestation_id]))[2] AS prestation_I01_id
  				FROM
  					activite.p_factures_lignes_c 
  					JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture AND p_factures.date_fin >= w_date_histo_18
  					JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
  					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS', 'EXH', 'I01')  
  				WHERE montant_facture <> 0 AND 
  					p_factures_lignes_c.date_fin BETWEEN w_date_histo_18 AND w_date_traitement AND montant_facture > 0;
  				-- Prestations et rubriques par défaut
  				UPDATE w_cti_encours_calcul_parametres SET 
  					coefficient_mco = COALESCE(coefficient_mco, 1),
  					prestation_ghs_id = COALESCE(prestation_ghs_id, (SELECT oid FROM activite.t_prestations WHERE code = 'GHS')),
  					rubrique_facturation_ghs_id = COALESCE(rubrique_facturation_ghs_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'GHS')),
  					rubrique_comptabilisation_ghs_id = COALESCE(rubrique_comptabilisation_ghs_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'GHS')),
  					prestation_ghs_sea_id = COALESCE(prestation_ghs_sea_id, (SELECT oid FROM activite.t_prestations WHERE code = 'GHS')),
  					rubrique_facturation_ghs_sea_id = COALESCE(rubrique_facturation_ghs_sea_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'GHS')),
  					rubrique_comptabilisation_ghs_sea_id = COALESCE(rubrique_comptabilisation_ghs_sea_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'GHS')),
  					prestation_exh_id = COALESCE(prestation_exh_id, (SELECT oid FROM activite.t_prestations WHERE code = 'EXH')),
  					rubrique_facturation_exh_id = COALESCE(rubrique_facturation_exh_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'EXH')),
  					rubrique_comptabilisation_exh_id = COALESCE(rubrique_comptabilisation_exh_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'EXH')),
  					prestation_i01_id = COALESCE(prestation_i01_id, (SELECT oid FROM activite.t_prestations WHERE code = 'I01')),
  					rubrique_facturation_i01_id = COALESCE(rubrique_facturation_i01_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'I01')),
  					rubrique_comptabilisation_i01_id = COALESCE(rubrique_comptabilisation_i01_id, (SELECT oid FROM activite.t_rubriques_facturation WHERE code = 'I01'))
  				;
  				-- forcage coefficient mco selon calcul et non plus depuis la facturation
  				UPDATE w_cti_encours_calcul_parametres
  				SET coefficient_mco = coefficient_mco_calcul
  				FROM base.v_coefficient_mco
  				WHERE date(now()) BETWEEN v_coefficient_mco.date_debut AND v_coefficient_mco.date_fin
  				;
  				-- Par service
  				INSERT INTO w_cti_encours_calcul_parametres_services
  				SELECT
  					service_facturation_id,
  					type_sejour,
  					(MAX(CASE WHEN prestation_code = 'GHS' THEN ARRAY[to_char(nb,'FM0000000000'),rubrique_facturation_id::text] ELSE NULL END))[2]::bigint,
  					(MAX(CASE WHEN prestation_code = 'GHS' THEN ARRAY[to_char(nb,'FM0000000000'),prestation_id::text] ELSE NULL END))[2]::bigint,
  					(MAX(CASE WHEN prestation_code = 'EXH' THEN ARRAY[to_char(nb,'FM0000000000'),rubrique_facturation_id::text] ELSE NULL END))[2]::bigint,
  					(MAX(CASE WHEN prestation_code = 'EXH' THEN ARRAY[to_char(nb,'FM0000000000'),prestation_id::text] ELSE NULL END))[2]::bigint
  				FROM
  				(					
  					SELECT 
  						type_sejour,
  						t_lieux.service_facturation_id,
  						t_prestations.code AS prestation_code,
  						prestation_id,
  						rubrique_facturation_id,
  						count(*) AS nb
  					FROM
  						activite.p_factures_lignes_c 
  						JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
  						JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
  						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS', 'EXH') 
  						JOIN activite.t_lieux ON lieu_id = t_lieux.oid 
  					WHERE montant_facture <> 0 AND 
  						p_factures_lignes_c.date_fin BETWEEN w_date_histo_18 AND w_date_traitement AND montant_facture > 0
  					GROUP BY 1,2,3,4,5
  					HAVING count(*) > 10
  				) subview
  				GROUP BY 1,2
  				;
  	
  		RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Historique facturation prestations';  
  				
  				INSERT INTO w_cti_encours_calcul_parametres_services_prestations
  				SELECT w_cti_encours_calcul_parametres.coefficient_mco,
  					t_lieux.service_facturation_id AS lieu_service_id, 
  					t_lieux.unite_fonctionnelle_id AS lieu_unite_fonctionnelle_id, 
  					0::numeric AS nb_ambulatoires,
  					0::numeric AS nb_externes,
  					0::numeric AS nb_seances,
  					0::numeric AS nb_journees,
  					0::numeric AS nb_journees_cp,
  					prestation_id,
  					t_prestations.code AS prestation_code,
  					CASE 
  						WHEN t_prestations.code = 'GHT' AND p_factures_lignes_c.date_debut - p_sejours.date_entree <= 3 THEN '1'
  						WHEN t_prestations.code = 'GHT' AND p_factures_lignes_c.date_debut - p_sejours.date_entree BETWEEN 4 AND 8 THEN '2'
  						WHEN t_prestations.code = 'GHT' AND p_factures_lignes_c.date_debut - p_sejours.date_entree BETWEEN 9 AND 30 THEN '3'
  						WHEN t_prestations.code = 'GHT' AND p_factures_lignes_c.date_debut - p_sejours.date_entree > 30 THEN '9'
  						ELSE '' END AS tranche_ght,
  					COALESCE(t_prestations.type_valorisation_non_facture,'') AS prestation_type_valorisation,
  					rubrique_facturation_id, 
  					COALESCE((MAX(Array[date(p_factures_lignes_c.date_fin) - w_NOW, prix_unitaire]))[2],0) as prix_unitaire, 
  					SUM(nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END) -
  						SUM(CASE WHEN p_sejours.type_sejour = '1' AND p_factures_lignes_c.date_fin = p_sejours.date_sortie AND (t_prestations.code IN ('CPC', 'SHO', 'CP') OR t_prestations.type_valorisation_non_facture IN ('CP')) THEN 1 ELSE 0 END)  as nombre,
  					0::numeric AS coefficient,
  					base.cti_division(
  						SUM(CASE WHEN p_factures_lignes_c.date_debut >= date(date_trunc('month',w_cti_encours_calcul_parametres.date_encours)) THEN CASE WHEN taux_1+taux_2+taux_0 = 100 THEN montant_facture ELSE nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END * prix_unitaire END ELSE 0 END) , 
  						SUM(CASE WHEN p_factures_lignes_c.date_debut >= date(date_trunc('month',w_cti_encours_calcul_parametres.date_encours)) THEN nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END ELSE 0 END)
  					) AS prix_unitaire_moyen_1,
  					SUM(CASE WHEN p_factures_lignes_c.date_debut >= date(date_trunc('month',w_cti_encours_calcul_parametres.date_encours)) THEN nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END ELSE 0 END) AS nb_prix_unitaire_moyen_1,
  					base.cti_division(
  						SUM(CASE WHEN p_factures_lignes_c.date_debut >= w_cti_encours_calcul_parametres.date_encours - interval '3 month' THEN CASE WHEN taux_1+taux_2+taux_0 = 100 THEN montant_facture ELSE nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END * prix_unitaire END ELSE 0 END) , 
  						SUM(CASE WHEN p_factures_lignes_c.date_debut >= w_cti_encours_calcul_parametres.date_encours - interval '3 month' THEN nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END ELSE 0 END)
  					) AS prix_unitaire_moyen_3,
  					SUM(CASE WHEN p_factures_lignes_c.date_debut >= w_cti_encours_calcul_parametres.date_encours - interval '3 month' THEN nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END ELSE 0 END) AS nb_prix_unitaire_moyen_3,
  					base.cti_division(
  						SUM(CASE WHEN taux_1+taux_2+taux_0 = 100 THEN montant_facture ELSE nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END * prix_unitaire END), 
  						SUM(nb_rubrique * CASE WHEN coefficient <> 0 THEN coefficient ELSE 1 END)
  					) AS prix_unitaire_moyen,
  					''::text AS regle_prestation_texte,
  					0::numeric AS coefficient_calcule,
  					0::numeric AS prix_unitaire_calcule,
  					'0'::text AS coefficient_is_force,
  					'0'::text AS prix_unitaire_is_force,
  					''::text AS type_ligne,
  					''::text AS prestation_10p_code,
  					''::text AS rubrique_code,
  					''::text AS rubrique_10p_code,
  					0::bigint AS prestation_10p_id,
  					0::bigint AS rubrique_10p_id
  				FROM w_cti_encours_calcul_parametres, activite.p_factures_lignes_c
  					JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture AND type_facture NOT IN ('E') AND code_facture >= '1' AND p_factures.date_fin >= w_date_histo_coeff_presta
  					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
  					JOIN activite.t_lieux ON lieu_id = t_lieux.oid
  					JOIN activite.p_sejours On p_factures.no_sejour = p_sejours.no_sejour
  				WHERE p_factures_lignes_c.montant_facture <> 0 AND p_factures_lignes_c.date_fin <= w_cti_encours_calcul_parametres.date_encours AND
  						(t_prestations.code IN ('GMT', 'PJ', 'FJ', 'ENT', 'I01', 'PMS', 'CPC', 'SHO', 'CP','SRC','STF','REA','FJA','ATU','FPU','SE1','SE2','SE3','SE4','SE5','SE6','SE7', 'IGM', 'IGP', 'APD', 'AMD', 'AMF', 'APD', 'IMD', 'IMI', 'IPD', 'IVG', 'GHT', 'NN1', 'NN2', 'NN3', 'D09', 'D11', 'D13', 'D15', 'D16', 'DTP', 'DMASSR') OR
  						t_prestations.type_valorisation_non_facture IN ('GMT', 'CP','PJ','ENT','*AVGJOUSER')
  						)
  				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13
  				ORDER BY 1,2,3,4,5,6;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET rubrique_code = t_rubriques_facturation.code
          FROM activite.t_rubriques_facturation 
          WHERE rubrique_facturation_id = t_rubriques_facturation.oid
          ;
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prestation_10p_code = t_prestations.code,
            prestation_10p_id = t_prestations.oid
          FROM activite.t_prestations 
          WHERE ('M'||w_cti_encours_calcul_parametres_services_prestations.prestation_code = t_prestations.code AND t_prestations.code <> 'MPJ' OR 
            w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('GMT', 'PJ') AND t_prestations.code = 'MPJS') 
          ;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET rubrique_10p_id = subview.rubrique_10p_id, rubrique_10p_code = subview.rubrique_10p_code
          FROM
          (
          SELECT prestation_10p_id, 
            (MAX(Array[date_debut::text,p_factures_lignes_c.rubrique_facturation_id::text]))[2]::bigint AS rubrique_10p_id, 
            (MAX(Array[date_debut::text,t_rubriques_facturation.code::text]))[2]::text AS rubrique_10p_code
          FROM activite.p_factures_lignes_c
          JOIN w_cti_encours_calcul_parametres_services_prestations ON p_factures_lignes_c.prestation_id = prestation_10p_id AND  prestation_10p_id > 0
          JOIN activite.t_rubriques_facturation ON p_factures_lignes_c.rubrique_facturation_id = t_rubriques_facturation.oid
          WHERE montant_facture <> 0
          group by 1
          ) subview
          WHERE w_cti_encours_calcul_parametres_services_prestations.prestation_10p_id = subview.prestation_10p_id
          ;
  
          
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET nombre = CASE WHEN w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id = subview.rubrique_facturation_id 
            THEN w_cti_encours_calcul_parametres_services_prestations.nombre
            ELSE 0 END
          FROM
            (
            SELECT lieu_service_id,
              lieu_unite_fonctionnelle_id,
              prestation_id,
              count(*),
              (MAX(Array[nombre, rubrique_facturation_id]))[2] AS rubrique_facturation_id
            FROM w_cti_encours_calcul_parametres_services_prestations
            WHERE prestation_code NOT IN ('CPC', 'SHO', 'CP') AND prestation_type_valorisation NOT IN ('CP')
            GROUP BY 1,2,3
            HAVING count(*) > 1
            ) subview
          WHERE w_cti_encours_calcul_parametres_services_prestations.lieu_service_id = subview.lieu_service_id AND
            w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id = subview.lieu_unite_fonctionnelle_id AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_id = subview.prestation_id;
          DELETE FROM w_cti_encours_calcul_parametres_services_prestations WHERE nombre = 0;
          INSERT INTO w_cti_encours_calcul_parametres_services_prestations
          SELECT
            coefficient_mco,
            lieu_service_id, 
            lieu_unite_fonctionnelle_id, 
            nb_ambulatoires,
            nb_externes,
            nb_seances,
            nb_journees,
            nb_journees_cp,
            (SELECT oid FROM activite.t_prestations WHERE code = 'FJA') AS prestation_id,
            'FJA' AS prestation_code,
            ''::text AS tranche_ght,
            ''::text AS prestation_type_valorisation,
            rubrique_facturation_id, 
            prix_unitaire, 
            nombre,
            coefficient,
            prix_unitaire_moyen_1,
            nb_prix_unitaire_moyen_1,
            prix_unitaire_moyen_3,
            nb_prix_unitaire_moyen_3,
            prix_unitaire_moyen,
            ''::text AS regle_prestation_texte,
            0::numeric AS coefficient_calcule,
            0::numeric AS prix_unitaire_calcule,
            '0'::text AS coefficient_is_force,
            '0'::text AS prix_unitaire_is_force,
            ''::text AS type_ligne
          FROM w_cti_encours_calcul_parametres_services_prestations
          WHERE prestation_code = 'FJ' AND
            'FJA' || '|' || lieu_service_id::text || '|' || lieu_unite_fonctionnelle_id::text NOT IN (SELECT prestation_code || '|' || lieu_service_id::text || '|' || lieu_unite_fonctionnelle_id::text FROM w_cti_encours_calcul_parametres_services_prestations);
      
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire =
            CASE
            WHEN prix_unitaire_moyen_1 <> 0 AND nb_prix_unitaire_moyen_1 > 100 THEN
              CASE WHEN prix_unitaire - prix_unitaire_moyen_1 BETWEEN -2 AND 2 THEN prix_unitaire ELSE round(prix_unitaire_moyen_1,2) END
            WHEN prix_unitaire_moyen_3 <> 0 AND nb_prix_unitaire_moyen_1 > 100 THEN
              CASE WHEN prix_unitaire - prix_unitaire_moyen_3 BETWEEN -2 AND 2 THEN prix_unitaire ELSE round(prix_unitaire_moyen_3,2) END
            WHEN prix_unitaire_moyen <> 0  THEN
              CASE WHEN prix_unitaire - prix_unitaire_moyen BETWEEN -2 AND 2 THEN prix_unitaire ELSE round(prix_unitaire_moyen,2) END
            ELSE prix_unitaire
            END;
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Historique occupation ' || w_date_histo_coeff_presta::text;  
          INSERT INTO w_cti_encours_calcul_parametres_services_journees
          SELECT t_lieux.service_facturation_id AS lieu_service_id, 
            t_lieux.unite_fonctionnelle_id AS lieu_unite_fonctionnelle_id, 
            SUM(nb_ambulatoires) AS nb_ambulatoires,
            SUM(nb_externes) AS nb_externes,
            SUM(nb_seances) AS nb_seances,
            COUNT(DISTINCT CASE WHEN heure_fin = 240000 OR heure_debut > 0 AND heure_fin < 240000 THEN p_mouvements_sejour.no_sejour || p_mouvements_sejour.date::text ELSE NULL END) as nb_journees, 
            COUNT(DISTINCT CASE WHEN est_chambre_particuliere <> '1' THEN NULL 
            WHEN heure_fin = 240000 OR heure_debut > 0 AND heure_fin < 240000 THEN p_mouvements_sejour.no_sejour || p_mouvements_sejour.date::text
            ELSE NULL END
            ) as nb_journees_cp
          FROM w_cti_encours_calcul_parametres, 
            activite.p_mouvements_sejour
            JOIN activite.p_sejours ON p_mouvements_sejour.no_sejour = p_sejours.no_sejour 
            JOIN activite.t_lieux ON lieu_id = t_lieux.oid
          WHERE p_mouvements_sejour.date <= w_cti_encours_calcul_parametres.date_encours AND
            p_mouvements_sejour.date >= w_date_histo_coeff_presta AND
            p_mouvements_sejour.no_sejour IN (SELECT no_sejour FROM activite.p_factures WHERE type_facture NOT IN ('E') AND code_facture >= '1' AND p_factures.date_fin >= w_date_histo_18)
          GROUP BY 1,2;
          UPDATE w_cti_encours_calcul_parametres_services_prestations SET 
            nb_ambulatoires = w_cti_encours_calcul_parametres_services_journees.nb_ambulatoires,
            nb_externes = w_cti_encours_calcul_parametres_services_journees.nb_externes,
            nb_seances = w_cti_encours_calcul_parametres_services_journees.nb_seances,
            nb_journees = w_cti_encours_calcul_parametres_services_journees.nb_journees,
            nb_journees_cp = w_cti_encours_calcul_parametres_services_journees.nb_journees_cp
          FROM w_cti_encours_calcul_parametres_services_journees
          WHERE w_cti_encours_calcul_parametres_services_journees.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            w_cti_encours_calcul_parametres_services_journees.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id;
          
          
  
          -- Récupération historique d'un autre environnement (saint gatien)
          IF EXISTS (
            SELECT table_name 
            FROM information_schema.tables
            WHERE table_schema || '.' || table_name = 'activite.t_encours_calcul_parametres_services_prestations_histo' ) THEN
  
            INSERT INTO w_cti_encours_calcul_parametres_services_prestations
              (
              coefficient_mco,
              lieu_service_id,
              lieu_unite_fonctionnelle_id,
              nb_ambulatoires,
              nb_externes,
              nb_seances,
              nb_journees,
              nb_journees_cp,
              prestation_id,
              prestation_code,
              tranche_ght,
              prestation_type_valorisation,
              rubrique_facturation_id,
              prix_unitaire,
              nombre,
              coefficient,
              prix_unitaire_moyen_1,
              nb_prix_unitaire_moyen_1,
              prix_unitaire_moyen_3,
              nb_prix_unitaire_moyen_3,
              prix_unitaire_moyen,
              regle_prestation_texte,
              coefficient_calcule,
              prix_unitaire_calcule,
              coefficient_is_force,
              prix_unitaire_is_force,
              type_ligne,
              prestation_10p_code,
              rubrique_code,
              rubrique_10p_code,
              prestation_10p_id,
              rubrique_10p_id
              )
            SELECT 
              t_encours_calcul_parametres_services_prestations_histo.coefficient_mco,
              t_encours_calcul_parametres_services_prestations_histo.lieu_service_id,
              t_encours_calcul_parametres_services_prestations_histo.lieu_unite_fonctionnelle_id,
              t_encours_calcul_parametres_services_prestations_histo.nb_ambulatoires,
              t_encours_calcul_parametres_services_prestations_histo.nb_externes,
              t_encours_calcul_parametres_services_prestations_histo.nb_seances,
              t_encours_calcul_parametres_services_prestations_histo.nb_journees,
              t_encours_calcul_parametres_services_prestations_histo.nb_journees_cp,
              t_encours_calcul_parametres_services_prestations_histo.prestation_id,
              t_encours_calcul_parametres_services_prestations_histo.prestation_code,
              t_encours_calcul_parametres_services_prestations_histo.tranche_ght,
              t_encours_calcul_parametres_services_prestations_histo.prestation_type_valorisation,
              t_encours_calcul_parametres_services_prestations_histo.rubrique_facturation_id,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire,
              t_encours_calcul_parametres_services_prestations_histo.nombre,
              t_encours_calcul_parametres_services_prestations_histo.coefficient,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire_moyen_1,
              t_encours_calcul_parametres_services_prestations_histo.nb_prix_unitaire_moyen_1,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire_moyen_3,
              t_encours_calcul_parametres_services_prestations_histo.nb_prix_unitaire_moyen_3,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire_moyen,
              t_encours_calcul_parametres_services_prestations_histo.regle_prestation_texte,
              t_encours_calcul_parametres_services_prestations_histo.coefficient_calcule,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire_calcule,
              t_encours_calcul_parametres_services_prestations_histo.coefficient_is_force,
              t_encours_calcul_parametres_services_prestations_histo.prix_unitaire_is_force,
              t_encours_calcul_parametres_services_prestations_histo.type_ligne,
              t_encours_calcul_parametres_services_prestations_histo.prestation_10p_code,
              t_encours_calcul_parametres_services_prestations_histo.rubrique_code,
              t_encours_calcul_parametres_services_prestations_histo.rubrique_10p_code,
              t_encours_calcul_parametres_services_prestations_histo.prestation_10p_id,
              t_encours_calcul_parametres_services_prestations_histo.rubrique_10p_id
            FROM activite.t_encours_calcul_parametres_services_prestations_histo
            LEFT JOIN w_cti_encours_calcul_parametres_services_prestations ON 
              t_encours_calcul_parametres_services_prestations_histo.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_encours_calcul_parametres_services_prestations_histo.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              t_encours_calcul_parametres_services_prestations_histo.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
              t_encours_calcul_parametres_services_prestations_histo.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
              t_encours_calcul_parametres_services_prestations_histo.tranche_ght = w_cti_encours_calcul_parametres_services_prestations.tranche_ght
            WHERE w_cti_encours_calcul_parametres_services_prestations.lieu_service_id IS NULL
            ;
  
            UPDATE w_cti_encours_calcul_parametres_services_prestations SET
              nb_ambulatoires = w_cti_encours_calcul_parametres_services_prestations.nb_ambulatoires + t_encours_calcul_parametres_services_prestations_histo.nb_ambulatoires,
              nb_externes = w_cti_encours_calcul_parametres_services_prestations.nb_externes + t_encours_calcul_parametres_services_prestations_histo.nb_externes,
              nb_seances = w_cti_encours_calcul_parametres_services_prestations.nb_seances + t_encours_calcul_parametres_services_prestations_histo.nb_seances,
              nb_journees = w_cti_encours_calcul_parametres_services_prestations.nb_journees + t_encours_calcul_parametres_services_prestations_histo.nb_journees,
              nb_journees_cp = w_cti_encours_calcul_parametres_services_prestations.nb_journees_cp + t_encours_calcul_parametres_services_prestations_histo.nb_journees_cp,
              nombre = w_cti_encours_calcul_parametres_services_prestations.nombre + t_encours_calcul_parametres_services_prestations_histo.nombre
            FROM activite.t_encours_calcul_parametres_services_prestations_histo
            WHERE t_encours_calcul_parametres_services_prestations_histo.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_encours_calcul_parametres_services_prestations_histo.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              t_encours_calcul_parametres_services_prestations_histo.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
              t_encours_calcul_parametres_services_prestations_histo.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
              t_encours_calcul_parametres_services_prestations_histo.tranche_ght = w_cti_encours_calcul_parametres_services_prestations.tranche_ght
            ;
  
          END IF;
  
          
          -- 
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_seances) < 0.1 THEN 0
            WHEN base.cti_division(nombre, nb_seances) > 0.4 THEN 1
            ELSE round(base.cti_division(nombre, nb_seances),2) 
            END
          WHERE prestation_code IN ('D09', 'D11', 'D13', 'D13', 'D15', 'D16', 'DTP');
          
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_journees) < 0.05 THEN 0
            WHEN base.cti_division(nombre, nb_journees) < 0.1 AND nombre < 100 THEN 0
            WHEN base.cti_division(nombre, nb_journees) > 0.95 THEN 1
            ELSE round(base.cti_division(nombre, nb_journees),2) 
            END
          WHERE prestation_code IN ('SRC', 'REA', 'STF');
          
            
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_journees_cp) < 0.05 THEN 0
            WHEN base.cti_division(nombre, nb_journees_cp) > 1 THEN 1
            ELSE round(base.cti_division(nombre, nb_journees_cp),2) 
            END
          WHERE prestation_code IN ('CPC', 'SHO', 'CP') OR prestation_type_valorisation IN ('CP');
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET nb_journees = w_cti_encours_calcul_parametres_services_prestations.nombre,
            coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_journees) < 0.1 THEN 0
            ELSE 1
            END
          FROM 
            (
            SELECT lieu_service_id, lieu_unite_fonctionnelle_id, 
               base.cti_division(SUM(nombre), MAX(nb_journees))
            FROM w_cti_encours_calcul_parametres_services_prestations
            WHERE prestation_code IN ('GHT')
            GROUP BY 1,2
            ) subview
          WHERE w_cti_encours_calcul_parametres_services_prestations.lieu_service_id = subview.lieu_service_id AND
            w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id = subview.lieu_unite_fonctionnelle_id AND
            prestation_code IN ('GHT');
          
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_ambulatoires + nb_externes) < 0.05 THEN 0
            WHEN base.cti_division(nombre, nb_ambulatoires + nb_externes) > 1 THEN 1
            ELSE round(base.cti_division(nombre, nb_ambulatoires + nb_externes),2) 
            END
          WHERE prestation_code IN ('AMD', 'AMF', 'IGM', 'IGP', 'APD', 'IMD', 'IMI', 'IPD', 'IVG');
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 
            CASE 
            WHEN base.cti_division(nombre, nb_journees) < 0.05 THEN 0
            WHEN base.cti_division(nombre, nb_journees) > 1 THEN 1
            ELSE round(base.cti_division(nombre, nb_journees),2) 
            END
          WHERE prestation_code IN ('NN1', 'NN2', 'NN3');
  
          -- FPU à compter de janvier 2022. Initialisation provisoire 
          INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
          SELECT 'FPU'::text, 'FPU'::text, 'Forfait patient urgences'::text, 'Forfait patient urgences'::text
          WHERE 'FPU'::text NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL ) 
          ;
                      
          INSERT INTO w_cti_encours_calcul_parametres_services_prestations
          SELECT coefficient_mco,
            lieu_service_id, 
            lieu_unite_fonctionnelle_id, 
            nb_ambulatoires,
            nb_externes,
            nb_seances,
            nb_journees,
            nb_journees_cp,
            t_prestations.oid AS prestation_id,
            t_prestations.code AS prestation_code,
            ''::text AS tranche_ght,
            prestation_type_valorisation,
            rubrique_facturation_id, 
            19.61::numeric as prix_unitaire, 
            0::numeric as nombre,
            0::numeric AS coefficient,
            19.61::numeric as prix_unitaire_moyen_1,
            0::numeric as nb_prix_unitaire_moyen_1,
            19.61::numeric as prix_unitaire_moyen_3,
            0::numeric as nb_prix_unitaire_moyen_3,
            19.61::numeric as prix_unitaire_moyen,
            regle_prestation_texte,
            coefficient_calcule,
            19.61::numeric AS prix_unitaire_calcule,
            coefficient_is_force,
            prix_unitaire_is_force,
            ''::text AS type_ligne
          FROM w_cti_encours_calcul_parametres_services_prestations
          JOIN activite.t_prestations ON t_prestations.code = 'FPU'
          WHERE prestation_code = 'ATU' AND
            (lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||t_prestations.code::text) NOT IN
            (
            SELECT lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||prestation_code::text FROM w_cti_encours_calcul_parametres_services_prestations
            )
          ;
  
          -- Le coefficient calculé est la somme des ATU FPU
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = subview.coefficient
          FROM
          ( 
            SELECT lieu_service_id, lieu_unite_fonctionnelle_id, 
              CASE 
              WHEN base.cti_division(SUM(nombre), MAX(nb_externes)) < 0.05 THEN 0
              WHEN base.cti_division(SUM(nombre), MAX(nb_externes)) > 0.95 THEN 1
              ELSE round(base.cti_division(SUM(nombre), MAX(nb_externes)),2) 
              END AS coefficient
            FROM w_cti_encours_calcul_parametres_services_prestations
            WHERE prestation_code IN ('ATU','FPU')
            GROUP BY 1,2
          ) subview
          WHERE prestation_code IN ('ATU','FPU') AND
            w_cti_encours_calcul_parametres_services_prestations.lieu_service_id = subview.lieu_service_id AND
            w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id = subview.lieu_unite_fonctionnelle_id
          ;
          
          -- Prix unitaire moyen par jour
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire = base.cti_division(prix_unitaire_moyen * nombre , nb_journees + nb_ambulatoires)
          WHERE prestation_type_valorisation = '*AVGJOUSER';
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire = 0
          WHERE prestation_type_valorisation = '*AVGJOUSER' AND 
            (prix_unitaire < 20 AND base.cti_division(nombre,nb_journees + nb_ambulatoires) < 0.8 OR
            prix_unitaire < 1
            );
  
          -- pas de séjour si absence
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire = 0
          WHERE lieu_service_id IN
            (
            SELECT oid
            FROM activite.t_services_facturation
            WHERE est_absence = '1'
            )
          ;
  
          -- Prestations comme séjour, seulement si significatif
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire = 0
          WHERE (prestation_type_valorisation IN ('PJ', 'GMT') OR prestation_code IN ('PJ', 'GMT')) AND 
            (prix_unitaire < 20 AND base.cti_division(nombre,nb_journees + nb_ambulatoires) < 0.8 OR
            prix_unitaire < 1
            );
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET prix_unitaire = 0
          WHERE (prestation_type_valorisation IN ('PJ', 'GMT') OR prestation_code IN ('PJ', 'GMT')) AND 
            (base.cti_division(nombre,nb_journees + nb_ambulatoires) < 0.2
            );
  
          -- Sauvegarde des prix calcules
          UPDATE w_cti_encours_calcul_parametres_services_prestations SET
            coefficient_calcule = coefficient,
            prix_unitaire_calcule = prix_unitaire
          ;
  
          -- Paramètres qui ne sont pas dans l'historique
          INSERT INTO w_cti_encours_calcul_parametres_services_prestations
          SELECT 
  			t_calcul_encours.coefficient_mco
  			, t_calcul_encours.lieu_service_id
  			, t_calcul_encours.lieu_unite_fonctionnelle_id
  			, 0::numeric AS nb_ambulatoires
  			, 0::numeric AS nb_externes
  			, 0::numeric AS nb_seances
  			, 0::numeric AS nb_journees
  			, 0::numeric AS nb_journees_cp
  			, t_calcul_encours.prestation_id
  			, t_prestations.code AS prestation_code
  			, ''::text AS tranche_ght
  			, COALESCE(t_prestations.type_valorisation_non_facture,'') AS prestation_type_valorisation
  			, rubrique_facturation_id 
  			, 0::numeric AS prix_unitaire 
  			, 0::numeric AS nombre
  			, 0::numeric AS coefficient
  			, 0::numeric AS prix_unitaire_moyen_1
  			, 0::numeric AS nb_prix_unitaire_moyen_1
  			, 0::numeric AS prix_unitaire_moyen_3
  			, 0::numeric AS nb_prix_unitaire_moyen_3
  			, 0::numeric AS prix_unitaire_moyen
  			, ''::text AS regle_prestation_texte
  			, 0::numeric AS coefficient_calcule
  			, 0::numeric AS prix_unitaire_calcule
  			, '0'::text AS coefficient_is_force
  			, '0'::text AS prix_unitaire_is_force
  			, ''::text AS type_ligne
  		FROM activite.t_calcul_encours
  		JOIN activite.t_prestations ON prestation_id = t_prestations.oid
  		WHERE 
  			type_ligne = 'PRESTA-PC'
  			AND (
  				coefficient_is_force = '1' 
  				OR prix_unitaire_is_force = '1'
  				)
  			AND (lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||prestation_id::text||'-'||rubrique_facturation_id::text) NOT IN
  				(
  					SELECT lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||prestation_id::text||'-'||rubrique_facturation_id::text 
  					FROM w_cti_encours_calcul_parametres_services_prestations
  				)
          ;
  
          DELETE FROM activite.t_calcul_encours
          WHERE type_ligne = 'PRESTA-PC' 
          	AND NOT (
  					coefficient_is_force = '1' 
  					OR prix_unitaire_is_force = '1'
  					) 
          	AND (lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||prestation_id::text||'-'||rubrique_facturation_id::text) NOT IN
          	(
          	SELECT lieu_service_id::text||'-'||lieu_unite_fonctionnelle_id::text||'-'||prestation_id::text||'-'||rubrique_facturation_id::text 
  			FROM w_cti_encours_calcul_parametres_services_prestations
          	)
          ;
  
          -- Coefficients et prix unitaire force
          UPDATE w_cti_encours_calcul_parametres_services_prestations SET
            coefficient = t_calcul_encours.coefficient_force,
            coefficient_is_force = '1'
          FROM activite.t_calcul_encours
          WHERE t_calcul_encours.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            t_calcul_encours.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
            t_calcul_encours.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
            t_calcul_encours.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
            t_calcul_encours.type_ligne LIKE 'PRESTA%' AND
            t_calcul_encours.coefficient_is_force = '1'
          ;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations SET
            prix_unitaire = t_calcul_encours.prix_unitaire_force,
            prix_unitaire_is_force = '1'
          FROM activite.t_calcul_encours
          WHERE t_calcul_encours.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            t_calcul_encours.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
            t_calcul_encours.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
            t_calcul_encours.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
            t_calcul_encours.type_ligne LIKE 'PRESTA%' AND
            t_calcul_encours.prix_unitaire_is_force = '1'
          ;
  
          -- Texte des règles appliquéées
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET regle_prestation_texte = 
            'Coefficient ' || to_char(coefficient,'FM90D00') || 
            CASE WHEN coefficient_is_force <> '1' 
              THEN ' issu du taux de facturation de ' || prestation_code || ' (rubrique ' || t_rubriques_facturation.code || ')' ||
              ' : ' || to_char(nombre,'FM999999999999') || ' journées facturées sur ' || 
              to_char(nb_journees,'FM999999999999') || ' journées dans le service ' || 
              t_services_facturation.texte || ' (' || t_services_facturation.code || ') ' ||
              'des séjours facturés sortis des ' || _ENCOURSRETROSUP || ' derniers mois (' || to_char(w_date_histo_coeff_presta,'DD/MM/YYYY') || ')'
              ELSE ' forcé dans le paramétrage de la génération des encours ' END 
          FROM activite.t_services_facturation, activite.t_rubriques_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            rubrique_facturation_id = t_rubriques_facturation.oid AND
            w_cti_encours_calcul_parametres_services_prestations.coefficient > 0 AND
            prestation_code IN ('SRC', 'REA', 'STF', 'AMD', 'AMF', 'IGM', 'IGP', 'APD', 'IMD', 'IMI', 'IPD', 'IVG', 'NN1', 'NN2', 'NN3');
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET regle_prestation_texte = 
            'Coefficient ' || to_char(coefficient,'FM90D00') || 
            CASE WHEN coefficient_is_force <> '1' 
              THEN ' issu du taux de facturation de ' || prestation_code || ' (rubrique ' || t_rubriques_facturation.code || ')' ||
              ' : ' || to_char(nombre,'FM999999999999') || ' journées facturées sur ' || 
              to_char(nb_journees_cp,'FM999999999999') || ' journées en CP dans le service ' || 
              t_services_facturation.texte || ' (' || t_services_facturation.code || ') ' ||
              'des séjours facturés sortis des ' || _ENCOURSRETROSUP || ' derniers mois (' || to_char(w_date_histo_coeff_presta,'DD/MM/YYYY') || ')'
              ELSE ' forcé dans le paramétrage de la génération des encours ' END 
          FROM activite.t_services_facturation, activite.t_rubriques_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            rubrique_facturation_id = t_rubriques_facturation.oid AND
            w_cti_encours_calcul_parametres_services_prestations.coefficient > 0 AND
            (prestation_code IN ('CPC', 'SHO', 'CP') OR prestation_type_valorisation IN ('CP'));
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET regle_prestation_texte = 
            'Coefficient ' || to_char(coefficient,'FM90D00') || 
            CASE WHEN coefficient_is_force <> '1' 
              THEN ' issu du taux de facturation de ' || prestation_code || ' (rubrique ' || t_rubriques_facturation.code || ')' ||
              ' : ' || to_char(nombre,'FM999999999999') || ' séances facturées sur ' || 
              to_char(nb_seances,'FM999999999999') || ' séances dans le service ' || 
              t_services_facturation.texte || ' (' || t_services_facturation.code || ') ' ||
              'des séjours facturés sortis des ' || _ENCOURSRETROSUP || ' derniers mois (' || to_char(w_date_histo_coeff_presta,'DD/MM/YYYY') || ')'
              ELSE ' forcé dans le paramétrage de la génération des encours ' END 
          FROM activite.t_services_facturation, activite.t_rubriques_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            rubrique_facturation_id = t_rubriques_facturation.oid AND
            w_cti_encours_calcul_parametres_services_prestations.coefficient > 0 AND
            prestation_code IN ('D09','D11', 'D13', 'D13', 'D15', 'D16', 'DTP');
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET regle_prestation_texte = 
            'P.U. ' || to_char(prix_unitaire,'FM99999999990D00') || 
            CASE WHEN prix_unitaire_is_force <> '1' 
              THEN ' issu du P.U. moyen quotidien ' ||
              CASE 
              WHEN tranche_ght = '1' THEN '(<= 4j)'
              WHEN tranche_ght = '2' THEN '(5-9j)'
              WHEN tranche_ght = '3' THEN '(10-30j)'
              ELSE '(> 30j)' END || ' de ' || prestation_code || ' (rubrique ' || t_rubriques_facturation.code || ')' ||
              ' : ' || to_char(nb_journees + nb_ambulatoires,'FM999999999999') || ' journées facturées pour un montant de ' || 
              to_char(prix_unitaire_moyen * nombre,'FM999999999999') || ' euros dans le service ' || 
              t_services_facturation.texte || ' (' || t_services_facturation.code || ') ' ||
              'des séjours facturés sortis des ' || _ENCOURSRETROSUP || ' derniers mois (' || to_char(w_date_histo_coeff_presta,'DD/MM/YYYY') || ')'
              ELSE ' forcé dans le paramétrage de la génération des encours ' END 
          FROM activite.t_services_facturation, activite.t_rubriques_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            rubrique_facturation_id = t_rubriques_facturation.oid AND
            w_cti_encours_calcul_parametres_services_prestations.prix_unitaire > 0 AND
            (prestation_code IN ('GHT'))
          ;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET regle_prestation_texte = 
            'P.U. ' || to_char(prix_unitaire,'FM99999999990D00') || 
            CASE WHEN prix_unitaire_is_force <> '1' 
              THEN ' issu du P.U. moyen quotidien de ' || prestation_code || ' (rubrique ' || t_rubriques_facturation.code || ')' ||
              ' : ' || to_char(nb_journees + nb_ambulatoires,'FM999999999999') || ' journées facturées pour un montant de ' || 
              to_char(prix_unitaire_moyen * nombre,'FM999999999999') || ' euros dans le service ' || 
              t_services_facturation.texte || ' (' || t_services_facturation.code || ') ' ||
              'des séjours facturés sortis des ' || _ENCOURSRETROSUP || ' derniers mois (' || to_char(w_date_histo_coeff_presta,'DD/MM/YYYY') || ')'
              ELSE ' forcé dans le paramétrage de la génération des encours ' END 
          FROM activite.t_services_facturation, activite.t_rubriques_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            rubrique_facturation_id = t_rubriques_facturation.oid AND
            w_cti_encours_calcul_parametres_services_prestations.prix_unitaire > 0 AND
            (prestation_type_valorisation = '*AVGJOUSER' OR prestation_code IN ('GHT'))
          ;
  
          
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Historique taux facturation AMO BG';  
          DROP TABLE IF EXISTS w_actes_120;
          CREATE TEMP TABLE w_actes_120 AS
          SELECT p_factures.no_sejour
          FROM activite.p_factures_lignes_h 
            JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
          WHERE p_factures_lignes_h.prix_unitaire >= 120
          GROUP BY 1;
          INSERT INTO w_actes_120
          SELECT p_factures.no_sejour
          FROM activite.p_factures_lignes_non_facturees_h 
            JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
          WHERE p_factures_lignes_non_facturees_h.prix_unitaire >= 120
          GROUP BY 1;
  
          INSERT INTO w_cti_encours_factures_histo_taux
          SELECT service_facturation_id, AVG(taux_ghs_1) AS taux_ghs_1, count(*) AS nb, ''::text AS regle_taux_texte
          FROM
          (
          SELECT p_factures.no_sejour, 
            MAX(t_lieux.service_facturation_id) AS service_facturation_id,
            MAX(COALESCE(taux_1,0)) AS taux_ghs_1
          FROM activite.p_sejours
          JOIN activite.p_factures ON p_factures.no_sejour = p_sejours.no_sejour
          JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
          JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid AND type_t2a = '1'
          LEFT JOIN activite.p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture AND
            prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code = 'GHS')
          WHERE p_sejours.est_budget_global = '1' AND
            p_sejours.date_sortie BETWEEN w_date_histo_18 AND w_date_traitement AND
            p_sejours.no_sejour NOT IN (SELECT no_sejour FROM w_actes_120) AND
            (p_sejours.date_sortie - p_sejours.date_entree) <= 30
          GROUP BY 1
          HAVING MIN(p_factures.code_facture) >= '1'
          ) subview
          GROUP BY 1
          ;
  
          INSERT INTO w_cti_encours_factures_histo_taux
          SELECT oid, 0, 0, ''::text AS regle_taux_texte
          FROM activite.t_services_facturation
          WHERE oid NOT IN (SELECT service_facturation_id FROM w_cti_encours_factures_histo_taux) AND
            est_budget_global = '1'
          ;
  
          UPDATE w_cti_encours_factures_histo_taux
          SET taux_ghs_1 = 
            round(CASE
              WHEN nb < 10 THEN (SELECT base.cti_division(SUM(taux_ghs_1*nb),SUM(nb)) FROM w_cti_encours_factures_histo_taux) 
              WHEN taux_ghs_1 > 99 THEN 100
              ELSE taux_ghs_1 
              END,2),
            nb = CASE
              WHEN nb < 10 THEN (SELECT SUM(nb) FROM w_cti_encours_factures_histo_taux) 
              ELSE w_cti_encours_factures_histo_taux.nb END
          ;
  
          UPDATE w_cti_encours_factures_histo_taux
          SET regle_taux_texte = 'Ticket modérateur moyen ' || to_char(100-taux_ghs_1,'FM9990D00%') || ' des ' || 
            to_char(nb,'FM99999990') || ' séjours Budget Global MCO facturés sortis depuis 18 mois (' || to_char(w_date_histo_18,'DD/MM/YYYY') || ') pour le service ' ||
            t_services_facturation.texte || ' (' || t_services_facturation.code || ')'
          FROM activite.t_services_facturation 
          WHERE service_facturation_id = t_services_facturation.oid AND
            nb >= 10
            ;
  
            
          UPDATE w_cti_encours_factures_histo_taux
          SET regle_taux_texte = 'Ticket modérateur moyen ' || to_char(100-taux_ghs_1,'FM9990D00%') || ' des ' || 
            to_char(nb,'FM99999990') || ' séjours Budget Global MCO sortis depuis 18 mois (' || to_char(w_date_histo_18,'DD/MM/YYYY') || ') pour tous les services'
          WHERE nb < 10
            ;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET coefficient = 0, prix_unitaire = 0, prix_unitaire_moyen_1 = 0, prix_unitaire_moyen_3 = 0
          FROM activite.t_services_facturation
          WHERE lieu_service_id = t_services_facturation.oid AND
            t_services_facturation.est_absence = '1'
          ;
  
          
            
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Sejours a traiter';  
          INSERT INTO w_cti_encours_sejours
          SELECT p_sejours.oid AS sejour_id,
            p_sejours.no_sejour, 
            p_sejours.type_sejour,
            p_sejours.est_budget_global,
            CASE WHEN p_sejours.est_budget_global = '1' THEN '1' ELSE '2' END AS secteur_tarif,
            t_medecins_administratifs.medecin_id AS medecin_sejour_id, 
            COALESCE(t_medecins.specialite_id,0) AS specialite_medecin_sejour_id,
            t_lieux.service_facturation_id AS lieu_sortie_service_id,
            t_lieux.unite_fonctionnelle_id AS lieu_sortie_unite_fonctionnelle_id,
            code_sorti,
            lieu_sortie_id,
            mode_sortie,
            date_groupage,
            tiers_payant_1_id,
            tiers_payant_2_id,
            COALESCE(SUM(nb_seances),1) AS nb_ghs,
            p_sejours.ghm_id,
            p_sejours.ghs_id,
            p_sejours.ghs_bebe1_id,
            p_sejours.ghs_bebe2_id,
            p_sejours.ghs_bebe3_id,
            COALESCE(t_services_facturation.particularites_encours,''),
            CASE WHEN p_sejours.type_sejour <> '3' THEN COALESCE(t_services_facturation.type_t2a,'0') ELSE '0' END 
          FROM w_cti_encours_calcul_parametres,
            activite.p_sejours
            JOIN activite.t_lieux ON lieu_sortie_id = t_lieux.oid
            JOIN activite.t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
            JOIN activite.t_medecins_administratifs ON p_sejours.medecin_sejour_id = t_medecins_administratifs.oid
            LEFT JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
            LEFT JOIN activite.p_mouvements_sejour ON
              p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND 
              p_sejours.type_sejour = '5' AND nb_seances > 0 
          WHERE p_sejours.etat = '' AND 
        code_prevu = '0' AND 
        date_entree <= w_date_traitement AND 
        (code_sorti = '1' OR date_sortie >= w_date_histo_18) AND 
        p_sejours.type_sejour <> '9'
      GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,17,18,19,20,21,22,23
      ;
  
      UPDATE w_cti_encours_sejours
      SET code_sorti = '1'
      WHERE type_sejour = '5' AND
        code_sorti <> '1'
      ;
  
      ANALYSE w_cti_encours_sejours
      ;
  
  RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Prix unitaire honoraires non factures' ;  
  
      UPDATE activite.p_factures_lignes_non_facturees_h
      SET prix_unitaire = subview.prix_unitaire
      FROM
      (
          SELECT acte_id, activite_ccam, modificateur_ccam_1, modificateur_ccam_2, modificateur_ccam_3, modificateur_ccam_4,
        base.cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
          FROM activite.p_factures_lignes_h
          WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
        montant_facture_1 > 0
          GROUP BY 1,2,3,4,5,6
          ) subview
      WHERE p_factures_lignes_non_facturees_h.prix_unitaire = 0 AND
        p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
        p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
        p_factures_lignes_non_facturees_h.modificateur_ccam_1 = subview.modificateur_ccam_1 AND
        p_factures_lignes_non_facturees_h.modificateur_ccam_2 = subview.modificateur_ccam_2 AND
        p_factures_lignes_non_facturees_h.modificateur_ccam_3 = subview.modificateur_ccam_3 AND
        p_factures_lignes_non_facturees_h.modificateur_ccam_4 = subview.modificateur_ccam_4 AND
        p_factures_lignes_non_facturees_h.prix_unitaire = 0
      ;
  
      UPDATE activite.p_factures_lignes_non_facturees_h
      SET prix_unitaire = subview.prix_unitaire
      FROM
      (
          SELECT acte_id, activite_ccam,
        base.Cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
          FROM activite.p_factures_lignes_h
          WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
        montant_facture_1 > 0
          GROUP BY 1,2
      ) subview
      WHERE p_factures_lignes_non_facturees_h.prix_unitaire = 0 AND
        p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
        p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
        p_factures_lignes_non_facturees_h.prix_unitaire = 0
  
      ;
  
      UPDATE activite.p_factures_lignes_non_facturees_h
      SET prix_unitaire = subview.prix_unitaire
      FROM
      (
      SELECT acte_id, prestation_id, (MAX(Array[date_debut::text,prix_unitaire::text]))[2]::numeric AS prix_unitaire
      FROM activite.p_factures_lignes_h
      WHERE prix_unitaire <> 0 AND
        acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0)
      GROUP BY 1,2
      ) subview
      WHERE p_factures_lignes_non_facturees_h.prix_unitaire = 0 AND
        p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
        p_factures_lignes_non_facturees_h.prestation_id = subview.prestation_id
      ;
      
  RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Historique facturation GHS' ;  
  
          -- Sur HM, il y a un séjour spécifique pour bébé, il ne faut donc pas tenir compte du GHS bébé du prestataire précédent pour calculer les moyennes
          -- Création d'une table de travail avec les GHS mères (cas de 2 prix unitaires GHS, on prend le plus grand)
          DROP TABLE IF EXISTS w_cti_encours_calcul_ghs_hm_mat_mere;
          CREATE TEMP TABLE w_cti_encours_calcul_ghs_hm_mat_mere AS
          SELECT p_factures_lignes_c.no_facture AS no_facture_mat_mere, 
            p_factures_lignes_c.prestation_id AS prestation_id_mat_mere, 
            MAX(prix_unitaire) AS prix_unitaire_mat_mere
          FROM activite.p_factures_lignes_c
          JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
          JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
          JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
          JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          JOIN (
            SELECT 1::integer AS ok_hm
            FROM activite.t_providers
            HAVING MAX(CASE WHEN oid = 0 AND code ILIKE 'HM' THEN 1 ELSE 0 END) = 1 AND
              MAX(CASE WHEN oid <> 0 AND code NOT ILIKE 'HM' THEN 1 ELSE 0 END) = 1
            ) subview ON ok_hm = 1
          WHERE t_prestations.code = 'GHS' AND p_factures.date_fin > '20170101' AND t_ghm.code LIKE '14%' AND
            montant_facture > 0
          GROUP BY 1,2
          HAVING count(DISTINCT prix_unitaire) > 1
          ;
  
          INSERT INTO w_cti_encours_histo_sejour_facture
          SELECT 
            w_cti_encours_sejours.no_sejour,
            p_factures.date_fin,
            CASE WHEN MAX(t_ghm.code) LIKE '05C19%' THEN '05C19' WHEN MAX(t_prestations.code) = 'I01' THEN 'I01' ELSE '' END AS classe_ghm,
            w_cti_encours_sejours.medecin_sejour_id, 
            w_cti_encours_sejours.specialite_medecin_sejour_id,
            w_cti_encours_sejours.lieu_sortie_service_id, 
            w_cti_encours_sejours.lieu_sortie_unite_fonctionnelle_id, 
            w_cti_encours_sejours.nb_ghs,
            CASE WHEN w_cti_encours_sejours.type_sejour = '5' THEN 'S'
              WHEN p_factures.date_fin - p_factures.date_debut <= 1 THEN '1' 
              WHEN p_factures.date_fin - p_factures.date_debut <= 3 THEN '2' 
              WHEN p_factures.date_fin - p_factures.date_debut <= 6 THEN '3' 
              WHEN p_factures.date_fin - p_factures.date_debut <= 10 THEN '4' 
              ELSE '5' END as tranche_sejour,
            CASE WHEN w_cti_encours_sejours.type_sejour = '5' THEN 0 ELSE p_factures.date_fin - p_factures.date_debut END as duree_sejour, 
            SUM(CASE WHEN base.cti_division(t_ghs_tarifs.tarif_ghs,t_ghs_tarifs_a.tarif_ghs) > 0 THEN montant_facture * base.cti_division(t_ghs_tarifs.tarif_ghs,t_ghs_tarifs_a.tarif_ghs) ELSE montant_facture END) AS montant_ghs, 
            SUM(montant_facture) AS montant_ghs_original,
            MAX(p_factures_lignes_c.taux_0),
            MAX(p_factures_lignes_c.taux_1),
            MAX(p_factures_lignes_c.taux_2+p_factures_lignes_c.taux_22)
          FROM activite.p_factures_lignes_c
            LEFT JOIN w_cti_encours_calcul_ghs_hm_mat_mere ON
              w_cti_encours_calcul_ghs_hm_mat_mere.no_facture_mat_mere = p_factures_lignes_c.no_facture AND
              w_cti_encours_calcul_ghs_hm_mat_mere.prestation_id_mat_mere = p_factures_lignes_c.prestation_id
            JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture AND 
                p_factures.date_fin BETWEEN w_date_histo_18 AND w_date_traitement AND
                p_factures.type_facture IN ('0','H','G') AND 
                p_factures.code_facture >= '1' AND p_factures.ghs_id > 0 AND p_factures.no_facture = p_factures.no_facture_reference
            JOIN w_cti_encours_sejours ON p_factures.no_sejour = w_cti_encours_sejours.no_sejour AND w_cti_encours_sejours.code_sorti = '1' 
            LEFT JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = p_factures.ghs_id AND 
              t_ghs_tarifs.secteur = w_cti_encours_sejours.secteur_tarif AND t_ghs_tarifs.tarif_ghs <> 0 AND
              w_date_encours BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
            LEFT JOIN base.t_ghs_tarifs t_ghs_tarifs_a ON t_ghs_tarifs_a.ghs_id = p_factures.ghs_id AND 
              t_ghs_tarifs_a.secteur = w_cti_encours_sejours.secteur_tarif AND t_ghs_tarifs_a.tarif_ghs <> 0 AND
              p_factures.date_fin BETWEEN t_ghs_tarifs_a.date_debut AND t_ghs_tarifs_a.date_fin
            LEFT JOIN base.t_ghm ON w_cti_encours_sejours.ghm_id = t_ghm.oid
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code IN ('GHS', 'EXH', 'I01')) AND 
            montant_facture <> 0 AND
            (
            w_cti_encours_calcul_ghs_hm_mat_mere.no_facture_mat_mere IS NULL OR
            w_cti_encours_calcul_ghs_hm_mat_mere.prix_unitaire_mat_mere = p_factures_lignes_c.prix_unitaire
            )
          GROUP BY 1,2,4,5,6,7,8,9,10;
          -- Ajustement pour QSP (plusieurs factures pour le GHS
          UPDATE w_cti_encours_histo_sejour_facture SET
            montant_ghs = montant_ghs / taux_1 * 100,
            montant_ghs_original = montant_ghs_original / taux_1 * 100
          WHERE taux_1 BETWEEN 80 AND 90 AND
            taux_0 = 0 AND
            taux_2 = 0
          ;
  
          -- Récupération historique d'un autre environnement (saint gatien)
          IF EXISTS (
            SELECT table_name 
            FROM information_schema.tables
            WHERE table_schema || '.' || table_name = 'activite.t_encours_histo_sejour_facture_histo' ) THEN
  
            INSERT INTO w_cti_encours_histo_sejour_facture
              (
              no_sejour, 
              date_fin, 
              classe_ghm, 
              medecin_sejour_id, 
              specialite_medecin_sejour_id, 
              lieu_sortie_service_id, 
              lieu_sortie_unite_fonctionnelle_id, 
              nb_ghs, 
              tranche_sejour, 
              duree_sejour, 
              montant_ghs,
              montant_ghs_original, 
              taux_0, 
              taux_1, 
              taux_2
              )
            SELECT 
              no_sejour, 
              date_fin, 
              classe_ghm, 
              medecin_sejour_id, 
              specialite_medecin_sejour_id, 
              lieu_sortie_service_id, 
              lieu_sortie_unite_fonctionnelle_id, 
              nb_ghs, 
              tranche_sejour, 
              duree_sejour, 
              montant_ghs,
              montant_ghs_original, 
              taux_0, 
              taux_1, 
              taux_2
            FROM activite.t_encours_histo_sejour_facture_histo
            ;
  
          END IF;
          
          INSERT INTO w_cti_encours_histo_ghs (
            classe_ghm,
            regle,
            medecin_sejour_id,
            specialite_medecin_sejour_id,
            lieu_sortie_service_id,
            lieu_sortie_unite_fonctionnelle_id,
            tranche_sejour,
            duree_sejour,
            nombre,
            montant_moyen_ghs
          )
          (SELECT 
            classe_ghm,'01-MSD12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'02-MST12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'03-MSD18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'04-MST18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'05-PSD12'::text AS regle, NULL::bigint AS medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'06-PST12'::text AS regle, NULL::bigint AS medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'07-MXD12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'08-MXT12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'09-MXD18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'10-MXT18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'11-PXD12'::text AS regle, NULL::bigint AS medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour::text, duree_sejour::integer,
            count(*) as nombre, AVG(montant_ghs / nb_ghs) as montant_moyen_ghs
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'12-PXT12'::text AS regle, NULL::bigint AS medecin_sejour_id, specialite_medecin_sejour_id, NULL::bigint, NULL::bigint, tranche_sejour, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'13-XSD18'::text AS regle, NULL::bigint, NULL::bigint, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, tranche_sejour, duree_sejour::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'21-MSX12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'22-MSX18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'51-MXX12'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, null::bigint, null::bigint, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 AND date_fin >= w_date_histo_12
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'52-MXX18'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, null::bigint, null::bigint, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0 
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT 
            classe_ghm,'61-XSX18'::text AS regle, null::bigint, null::bigint, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8
          HAVING count(*) >= _NBSEJMIN_HISTOGHS)
          UNION
          (SELECT classe_ghm,'99-XXX18'::text AS regle, null::bigint, null::bigint, null::bigint, null::bigint, null::text, null::integer,
            count(*) as nombre,	AVG(montant_ghs / nb_ghs)
          FROM w_cti_encours_histo_sejour_facture
          WHERE montant_ghs <> 0
          GROUP BY 1,2,3,4,5,6,7,8)
          ORDER BY 1,2,3,4;
  
          -- Textes
          UPDATE w_cti_encours_histo_ghs
          SET medecin_sejour_texte = t_medecins.nom || ' ' || t_medecins.prenom || ' (' || t_medecins.code || ')'
          FROM base.t_medecins
          WHERE medecin_sejour_id = t_medecins.oid AND
            medecin_sejour_id <> 0 AND
            medecin_sejour_id IS NOT NULL
          ;
          UPDATE w_cti_encours_histo_ghs
          SET specialite_medecin_sejour_texte = t_specialites_medecin.texte || ' (' || t_specialites_medecin.code || ')'
          FROM base.t_specialites_medecin
          WHERE specialite_medecin_sejour_id = t_specialites_medecin.oid AND
            specialite_medecin_sejour_id <> 0 AND
            specialite_medecin_sejour_id IS NOT NULL
          ;
          UPDATE w_cti_encours_histo_ghs
          SET lieu_sortie_service_texte = t_services_facturation.texte || ' (' || t_services_facturation.code || ')'
          FROM activite.t_services_facturation
          WHERE lieu_sortie_service_id = t_services_facturation.oid AND
            lieu_sortie_service_id <> 0 AND
            lieu_sortie_service_id IS NOT NULL
          ;
          UPDATE w_cti_encours_histo_ghs
          SET lieu_sortie_unite_fonctionnelle_texte = t_unites_fonctionnelles.texte || ' (' || t_unites_fonctionnelles.code || ')'
          FROM activite.t_unites_fonctionnelles
          WHERE lieu_sortie_unite_fonctionnelle_id = t_unites_fonctionnelles.oid AND
            lieu_sortie_unite_fonctionnelle_id <> 0 AND
            lieu_sortie_unite_fonctionnelle_id IS NOT NULL
          ;
          UPDATE w_cti_encours_histo_ghs
          SET tranche_sejour_texte =
            CASE tranche_sejour
            WHEN 'S' THEN 'Séances'
            WHEN '1' THEN '0 ou 1 nuit'
            WHEN '2' THEN '2 ou 3 nuits'
            WHEN '3' THEN '4,5 ou 6 nuits'
            WHEN '4' THEN '7,8,9 ou 10 nuits'
            WHEN '5' THEN '11 nuits et plus'
            END
          WHERE tranche_sejour IS NOT NULL
          ;
          UPDATE w_cti_encours_histo_ghs
          SET duree_sejour_texte =
            CASE duree_sejour
            WHEN 0 THEN '0 nuit'
            WHEN 1 THEN '1 nuit'
            ELSE duree_sejour::text || ' nuits'
            END
          WHERE duree_sejour IS NOT NULL
          ;
  
          -- Calcul moyennes DMS
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Historique DMS';  
          
          INSERT INTO w_cti_encours_histo_dms_sejours
          SELECT w_cti_encours_sejours.no_sejour, w_cti_encours_sejours.medecin_sejour_id, w_cti_encours_sejours.specialite_medecin_sejour_id, w_cti_encours_sejours.lieu_sortie_service_id, w_cti_encours_sejours.lieu_sortie_unite_fonctionnelle_id, 
            p_factures.date_fin, p_factures.date_debut
          FROM activite.p_factures
            JOIN w_cti_encours_sejours ON p_factures.no_sejour = w_cti_encours_sejours.no_sejour AND code_sorti = '1' 
          WHERE p_factures.date_fin BETWEEN w_date_histo_18 AND w_date_traitement AND type_facture IN ('0','H','G') AND p_factures.no_facture = p_factures.no_facture_reference;
          
          INSERT INTO w_cti_encours_histo_dms
          SELECT '1'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, round(AVG(date_fin - date_debut),0) AS dms, count(*) AS occurences
          FROM w_cti_encours_histo_dms_sejours
          GROUP BY 1,2,3,4,5
          HAVING count(*) >= _NBSEJMIN_HISTOGHS
          UNION
          SELECT '2'::text AS regle, medecin_sejour_id, specialite_medecin_sejour_id, null::bigint, null::bigint, round(AVG(date_fin - date_debut),0) AS dms, count(*) AS occurences
          FROM w_cti_encours_histo_dms_sejours
          GROUP BY 1,2,3,4,5
          HAVING count(*) >= _NBSEJMIN_HISTOGHS
          UNION
          SELECT '3'::text AS regle, null::bigint, null::bigint, lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, round(AVG(date_fin - date_debut),0) AS dms, count(*) AS occurences
          FROM w_cti_encours_histo_dms_sejours
          GROUP BY 1,2,3,4,5
          HAVING count(*) >= _NBSEJMIN_HISTOGHS
          UNION
          SELECT '9'::text AS regle, null::bigint, null::bigint, null::bigint, null::bigint, round(AVG(date_fin - date_debut),0) AS dms, count(*) AS occurences
          FROM w_cti_encours_histo_dms_sejours
          GROUP BY 1,2,3,4,5
          HAVING count(*) >= _NBSEJMIN_HISTOGHS;
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Extraction factures à valoriser'; 
          INSERT INTO w_cti_encours_factures(
            oid, sejour_id, no_sejour, type_sejour, classe_ghm, no_facture, no_facture_encours, no_facture_reference,
            etat, code_sorti, date_encours, date_debut, date_fin, lieu_sortie_id, mode_sortie,
            ghs_id, ghm_id, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, type_t2a, est_budget_global, secteur_tarif, code_cp_demandee, 
            lieu_sortie_service_id, lieu_sortie_unite_fonctionnelle_id, medecin_sejour_id, specialite_medecin_sejour_id,
            tiers_payant_1_id, tiers_payant_2_id, particularites_encours_service, uniquement_prestations_saisies)
          SELECT 
            p_factures.oid, w_cti_encours_sejours.sejour_id, p_factures.no_sejour, w_cti_encours_sejours.type_sejour, ''::text AS classe_ghm, p_factures.no_facture, 
            p_factures.no_facture || '.EC' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00'),
            p_factures.no_facture_reference, 
            CASE WHEN code_sorti <> '1' THEN 'E' WHEN p_factures.date_fin > w_date_traitement THEN 'E' ELSE 'S' END AS etat, 
            CASE WHEN code_sorti <> '1' THEN '0' WHEN p_factures.date_fin > w_date_traitement THEN '0' ELSE '1' END AS code_sorti, 
            w_cti_encours_calcul_parametres.date_encours, 
            p_factures.date_debut, 
            CASE WHEN date_fin <= w_date_traitement + interval '10 days' THEN p_factures.date_fin ELSE '20991231' END AS date_fin, 
            lieu_sortie_id,
            mode_sortie,
            CASE WHEN code_sorti <> '1' THEN 0 WHEN date_groupage <= w_date_traitement OR date_groupage = '20991231' THEN w_cti_encours_sejours.ghs_id ELSE 0 END AS ghs_id, 
            CASE WHEN code_sorti <> '1' THEN 0 WHEN date_groupage <= w_date_traitement OR date_groupage = '20991231' THEN w_cti_encours_sejours.ghm_id ELSE 0 END AS ghm_id, 
            CASE WHEN code_sorti <> '1' THEN 0 WHEN date_groupage <= w_date_traitement OR date_groupage = '20991231' THEN w_cti_encours_sejours.ghs_bebe1_id ELSE 0 END AS ghs_bebe1_id, 
            CASE WHEN code_sorti <> '1' THEN 0 WHEN date_groupage <= w_date_traitement OR date_groupage = '20991231' THEN w_cti_encours_sejours.ghs_bebe2_id ELSE 0 END AS ghs_bebe2_id, 
            CASE WHEN code_sorti <> '1' THEN 0 WHEN date_groupage <= w_date_traitement OR date_groupage = '20991231' THEN w_cti_encours_sejours.ghs_bebe3_id ELSE 0 END AS ghs_bebe3_id, 
            w_cti_encours_sejours.type_t2a,
            est_budget_global,
            CASE WHEN est_budget_global = '1' THEN '1' ELSE '2' END AS secteur_tarif,
            p_factures.code_cp_demandee, 
            lieu_sortie_service_id, 
            lieu_sortie_unite_fonctionnelle_id, 
            medecin_sejour_id,
            specialite_medecin_sejour_id,
            CASE WHEN p_factures.tiers_payant_1_id <> 0 THEN p_factures.tiers_payant_1_id ELSE w_cti_encours_sejours.tiers_payant_1_id END, 
            CASE WHEN p_factures.tiers_payant_1_id <> 0 THEN p_factures.tiers_payant_2_id ELSE w_cti_encours_sejours.tiers_payant_2_id END, 
            w_cti_encours_sejours.particularites_encours_service,
            CASE 
              WHEN p_factures.type_facture IN ('0','E') AND p_factures.no_facture = p_factures.no_facture_reference THEN '0'
              WHEN p_factures.code_facture = '0' AND p_factures.no_facture LIKE '%BG' THEN '0'
              WHEN est_budget_global = '1' THEN '0'
              ELSE '1' END AS uniquement_prestations_saisies
          FROM w_cti_encours_calcul_parametres, 
            activite.p_factures
            JOIN w_cti_encours_sejours ON w_cti_encours_sejours.no_sejour = p_factures.no_sejour
          WHERE 
              p_factures.type_facture <> 'P' AND 
              ((p_factures.type_facture IN ('0','E') AND 
              p_factures.no_facture = p_factures.no_facture_reference)
                OR
              (p_factures.code_facture = '0' AND 
              p_factures.no_facture IN (SELECT no_facture FROM activite.p_factures_lignes_non_facturees_c))
                OR
              (p_factures.code_facture = '0' AND 
              p_factures.no_facture LIKE '%BG'
              )
            ) AND
            p_factures.date_debut <= w_date_traitement AND
            (
              (p_factures.code_facture = '0' AND p_factures.date_debut <= w_date_traitement) 
              OR 
              (p_factures.code_facture >= '1' AND date_facture > w_date_traitement AND date_facture <> '20991231' AND date_vente > w_date_encours)
            ); 
        
      
          
          UPDATE w_cti_encours_factures
          SET date_fin = 
            GREATEST(date(date_debut + 
              COALESCE(
              w_cti_encours_histo_dms_1.dms,
              w_cti_encours_histo_dms_2.dms,
              w_cti_encours_histo_dms_3.dms,
              w_cti_encours_histo_dms_9.dms,
              0
              )::integer),w_date_sortie_max ),
            dms = COALESCE(
              w_cti_encours_histo_dms_1.dms,
              w_cti_encours_histo_dms_2.dms,
              w_cti_encours_histo_dms_3.dms,
              w_cti_encours_histo_dms_9.dms,
              0
              ),
            regle_dms =
              COALESCE(
              w_cti_encours_histo_dms_1.regle,
              w_cti_encours_histo_dms_2.regle,
              w_cti_encours_histo_dms_3.regle,
              w_cti_encours_histo_dms_9.regle,
              '0'
              )
          FROM w_cti_encours_sejours
            LEFT JOIN w_cti_encours_histo_dms w_cti_encours_histo_dms_1 ON 
              w_cti_encours_histo_dms_1.medecin_sejour_id = w_cti_encours_sejours.medecin_sejour_id AND 
              w_cti_encours_histo_dms_1.lieu_sortie_service_id = w_cti_encours_sejours.lieu_sortie_service_id AND
              w_cti_encours_histo_dms_1.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_sejours.lieu_sortie_unite_fonctionnelle_id
            LEFT JOIN w_cti_encours_histo_dms w_cti_encours_histo_dms_2 ON 
              w_cti_encours_histo_dms_2.medecin_sejour_id = w_cti_encours_sejours.medecin_sejour_id AND 
              w_cti_encours_histo_dms_2.lieu_sortie_service_id IS NULL AND
              w_cti_encours_histo_dms_2.lieu_sortie_unite_fonctionnelle_id IS NULL
            LEFT JOIN w_cti_encours_histo_dms w_cti_encours_histo_dms_3 ON 
              w_cti_encours_histo_dms_3.medecin_sejour_id IS NULL AND 
              w_cti_encours_histo_dms_3.lieu_sortie_service_id = w_cti_encours_sejours.lieu_sortie_service_id AND
              w_cti_encours_histo_dms_3.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_sejours.lieu_sortie_unite_fonctionnelle_id
            LEFT JOIN w_cti_encours_histo_dms w_cti_encours_histo_dms_9 ON 
              w_cti_encours_histo_dms_9.medecin_sejour_id IS NULL AND 
              w_cti_encours_histo_dms_9.lieu_sortie_service_id IS NULL AND
              w_cti_encours_histo_dms_9.lieu_sortie_unite_fonctionnelle_id IS NULL
          WHERE w_cti_encours_factures.no_sejour = w_cti_encours_sejours.no_sejour AND
            w_cti_encours_factures.code_sorti = '0' AND
            w_cti_encours_factures.type_sejour NOT IN ('2','3') AND
            w_cti_encours_factures.date_fin = '20991231';
          UPDATE w_cti_encours_factures
          SET date_fin = date_debut,
            dms = 0,
            regle_dms = '0'
          FROM w_cti_encours_sejours
          WHERE w_cti_encours_factures.no_sejour = w_cti_encours_sejours.no_sejour AND
            w_cti_encours_factures.code_sorti = '0' AND
            w_cti_encours_factures.type_sejour IN ('2','3') AND
            w_cti_encours_factures.date_fin = '20991231';
          
          UPDATE w_cti_encours_factures
          SET duree_sejour = CASE WHEN type_sejour <> '5' THEN date_fin - date_debut ELSE 0 END,
            tranche_sejour = 
              CASE 
              WHEN type_sejour = '5' THEN 'S'
              WHEN date_fin - date_debut <= 1 THEN '1' 
              WHEN date_fin - date_debut <= 3 THEN '2' 
              WHEN date_fin - date_debut <= 6 THEN '3' 
              WHEN date_fin - date_debut <= 10 THEN '4' 
              ELSE '5' END;
  
          -- En ESPIC, les actes non factures sont peut être sur une autre facture que BG
          UPDATE activite.p_factures_lignes_non_facturees_h
          SET no_facture = subview.no_facture_bg
          FROM
          (
          SELECT p_factures_lignes_non_facturees_h.no_facture, MAX(w_cti_encours_factures.no_facture) AS no_facture_bg
          FROM activite.p_factures_lignes_non_facturees_h
          JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
          JOIN w_cti_encours_factures ON 
            p_factures.no_sejour = w_cti_encours_factures.no_sejour AND
            w_cti_encours_factures.no_facture LIKE '%BG'
          WHERE p_factures_lignes_non_facturees_h.date_debut BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin 
          GROUP BY 1
          HAVING p_factures_lignes_non_facturees_h.no_facture <> MAX(w_cti_encours_factures.no_facture)
          ) subview
          WHERE p_factures_lignes_non_facturees_h.no_facture = subview.no_facture
          ;
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Extraction CPC deja facturee'; 
          INSERT INTO w_cti_encours_factures_deja_cpc(
            no_facture_reference)
          SELECT p_factures.no_facture_reference
          FROM activite.p_factures_lignes_c
          JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
          JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE p_factures_lignes_c.montant_facture <> 0 AND
            p_factures.no_facture_reference IN (SELECT no_facture_reference FROM w_cti_encours_factures) AND
              (t_prestations.code IN ('CPC', 'SHO', 'CP') OR
              t_prestations.type_valorisation_non_facture IN ('CP') 
              )
          GROUP BY 1
          HAVING SUM(nb_prestation) > 0
          ;
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Forcage code GHS'; 
          --UPDATE w_cti_encours_factures
          --SET ghs_id = t_ghs.oid
          --FROM activite.t_forcage_encours_factures
          --JOIN base.t_ghs ON t_ghs.code = t_forcage_encours_factures.ghs_code
          --WHERE w_cti_encours_factures.no_sejour = t_forcage_encours_factures.no_sejour AND
          --	t_forcage_encours_factures.etat_forcage_ghs = 'F' AND
          --	t_forcage_encours_factures.ghs_code <> 0 AND
          --	date_trunc('month',t_forcage_encours_factures.date_encours) = date_trunc('month',w_cti_encours_factures.date_encours)
          --;
      
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Generation des lignes valorisees'; 
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'GHS'; 
        
  
        -- Deux passages pour la valorisation
        -- premier passage sans tenir compte des GHS
        -- second en en tenant compte
        -- pour comparer les deux
        
        IF _ENCOURSECARTGHSV > 0 THEN
          w_simul = '';
        ELSE 
          w_simul = '1';
        END IF;
        WHILE w_simul <> '0' LOOP
          w_simul = CASE WHEN w_simul = '' THEN '1' ELSE '0' END;
  
          RAISE NOTICE '%. %' , w_date_encours_YYMM, 'GHS ' || w_simul; 
          TRUNCATE w_cti_encours_factures_lignes_c;
          
        INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, ghs_id,
            prix_unitaire, nb_prestation, montant_encours, lieu_id)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHS' AS type_ligne, date_debut, date_fin, GREATEST(date_fin - date_debut,1), 1, w_cti_encours_calcul_parametres.coefficient_mco, 
            COALESCE(w_cti_encours_calcul_parametres_services.prestation_ghs_id, w_cti_encours_calcul_parametres.prestation_ghs_id), 
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_id),
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_id),
            ghs_id,
            0, 1, 0, lieu_sortie_id
          FROM w_cti_encours_calcul_parametres, 
            w_cti_encours_factures
            LEFT JOIN w_cti_encours_calcul_parametres_services ON
              lieu_sortie_service_id = w_cti_encours_calcul_parametres_services.service_facturation_id AND
              w_cti_encours_factures.type_sejour = w_cti_encours_calcul_parametres_services.type_sejour
          WHERE w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.type_sejour <> '5' AND 
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_factures.ghm_id NOT IN (SELECT ghm_id FROM w_cti_encours_ghm_sans_ghs) AND
            w_cti_encours_factures.particularites_encours_service NOT ILIKE '%IVG%' AND
            COALESCE(w_cti_encours_calcul_parametres_services.prestation_ghs_id, w_cti_encours_calcul_parametres.prestation_ghs_id) <> 0 AND 
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_id) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND
            w_cti_encours_factures.no_facture NOT IN (
              SELECT no_facture 
              FROM activite.p_factures_lignes_non_facturees_c
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              WHERE t_prestations.code IN ('I01') 
              );
          
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, ghs_id,
            prix_unitaire, nb_prestation, montant_encours, lieu_id)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHS' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, nb_seances, 1, w_cti_encours_calcul_parametres.coefficient_mco, 
            COALESCE(w_cti_encours_calcul_parametres_services.prestation_ghs_id, w_cti_encours_calcul_parametres.prestation_ghs_sea_id), 
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_sea_id),
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_sea_id),
            ghs_id,
            0, nb_seances, 0, lieu_sortie_id
          FROM w_cti_encours_calcul_parametres, 
            w_cti_encours_factures
            LEFT JOIN w_cti_encours_calcul_parametres_services ON
              lieu_sortie_service_id = w_cti_encours_calcul_parametres_services.service_facturation_id AND
              w_cti_encours_factures.type_sejour = w_cti_encours_calcul_parametres_services.type_sejour
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour AND nb_seances > 0 AND p_mouvements_sejour.date BETWEEN w_cti_encours_factures.Date_debut AND w_cti_encours_factures.date_fin
          WHERE 
            w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.type_sejour = '5' AND
            uniquement_prestations_saisies <> '1' AND 
            COALESCE(w_cti_encours_calcul_parametres_services.prestation_ghs_id, w_cti_encours_calcul_parametres.prestation_ghs_sea_id) <> 0 AND 
            COALESCE(w_cti_encours_calcul_parametres_services.rubrique_facturation_ghs_id, w_cti_encours_calcul_parametres.rubrique_facturation_ghs_sea_id) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND
            lieu_sortie_service_id NOT IN (select lieu_service_id FROM w_cti_encours_calcul_parametres_services_prestations where prestation_code IN ('D09','D11','D13', 'D13', 'D15', 'D16', 'DTP') AND coefficient = 1);
  
          -- GHS déjà connu
          UPDATE w_cti_encours_factures_lignes_c SET
            prix_unitaire = t_ghs_tarifs.tarif_ghs,
            montant_encours = t_ghs_tarifs.tarif_ghs * w_cti_encours_factures_lignes_c.coefficient_mco,
            borne_basse = t_ghs_tarifs.borne_basse,
            borne_haute = t_ghs_tarifs.borne_haute,
            forfait_exb = t_ghs_tarifs.forfait_exb,
            tarif_exb = t_ghs_tarifs.tarif_exb,
            duree_sejour = w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut,
            regle_texte = 'GHS pour dossier groupé : ' || to_char(t_ghs.code,'FM0000') || ' (' || COALESCE(t_ghm.code || '-','') || COALESCE(t_ghm.texte,t_ghs.texte) || ')'
          FROM w_cti_encours_factures 
            JOIN base.t_ghs ON t_ghs.oid = w_cti_encours_factures.ghs_id
            JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid AND t_ghs_tarifs.secteur = w_cti_encours_factures.secteur_tarif AND w_cti_encours_factures.date_fin BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
            LEFT JOIN base.t_ghm ON t_ghm.oid = w_cti_encours_factures.ghm_id
          WHERE  w_simul = '0' AND
            w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            w_cti_encours_factures.ghs_id <> 0 AND
            type_ligne = 'GHS'
            ;
          -- EXB sur GHS déjà connus
          UPDATE w_cti_encours_factures_lignes_c
          SET montant_encours = 
            CASE 
              WHEN forfait_exb > 0 THEN round(prix_unitaire - forfait_exb * w_cti_encours_factures_lignes_c.coefficient_mco,2)
              WHEN forfait_exb = 0 AND tarif_exb > 0 AND duree_sejour = 0 THEN round(tarif_exb / 2 * coefficient_mco,2)
              WHEN forfait_exb = 0 AND tarif_exb > 0 THEN round(prix_unitaire - (tarif_exb * (borne_basse-duree_sejour) * coefficient_mco),2)
              ELSE montant_encours
            END,
            regle_texte = 'EXB pour dossier groupé'
          WHERE w_simul = '0' AND
            duree_sejour < borne_basse AND
            prix_unitaire <> 0 AND
            ghs_id <> 0 AND
            type_ligne = 'GHS';
            
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'EXH'; 
          -- EXH
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, nb_prestation, montant_encours, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'EXH' AS type_ligne, date(w_cti_encours_factures.date_debut + (t_ghs_tarifs.borne_haute || ' day')::interval), 
            w_cti_encours_factures.date_fin, w_cti_encours_factures.lieu_sortie_id, w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - t_ghs_tarifs.borne_haute, 1, w_cti_encours_calcul_parametres.coefficient_mco, 
            prestation_exh_id, rubrique_facturation_exh_id, rubrique_comptabilisation_ghs_id, 
            t_ghs_tarifs.tarif_exh, w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - t_ghs_tarifs.borne_haute, round(t_ghs_tarifs.tarif_exh * (w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - t_ghs_tarifs.borne_haute) * w_cti_encours_calcul_parametres.coefficient_mco,2),
            'EXH pour dossier groupé : Borne haute ' || t_ghs_tarifs.borne_haute || ' pour GHS ' || to_char(t_ghs.code,'FM0000') || ' (' || COALESCE(t_ghm.code || '-','') || COALESCE(t_ghm.texte,t_ghs.texte) || ')'
          FROM  w_cti_encours_calcul_parametres, w_cti_encours_factures
            JOIN base.t_ghs ON t_ghs.oid = w_cti_encours_factures.ghs_id
            LEFT JOIN base.t_ghm ON t_ghm.oid = w_cti_encours_factures.ghm_id
            JOIN base.t_ghs_tarifs ON t_ghs_tarifs.ghs_id = t_ghs.oid AND 
            t_ghs_tarifs.secteur = w_cti_encours_factures.secteur_tarif AND 
            w_cti_encours_factures.date_fin BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
          WHERE w_simul = '0' AND
            w_cti_encours_factures.type_t2a = '1' AND type_sejour <> '5' AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_factures.ghs_id > 0 AND
            t_ghs_tarifs.borne_haute > 0 AND
            w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut > t_ghs_tarifs.borne_haute AND 
            COALESCE(rubrique_facturation_exh_id,0) <> 0 AND 
            COALESCE(prestation_exh_id,0) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') ;
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'EXH (non groupes)'; 
          -- EXH
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, nb_prestation, montant_encours, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'EXHNG' AS type_ligne, date(w_cti_encours_factures.date_debut + (base.cti_to_number(t_divers_bh.valeur) || ' day')::interval), 
            w_cti_encours_factures.date_fin, w_cti_encours_factures.lieu_sortie_id, w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - base.cti_to_number(t_divers_bh.valeur), 1, 
            w_cti_encours_calcul_parametres.coefficient_mco, 
            prestation_exh_id, rubrique_facturation_exh_id, rubrique_comptabilisation_ghs_id, 
            base.cti_to_number(t_divers_xh.valeur), w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - base.cti_to_number(t_divers_bh.valeur), 
            round(base.cti_to_number(t_divers_xh.valeur) * (w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut - base.cti_to_number(t_divers_bh.valeur)) * w_cti_encours_calcul_parametres.coefficient_mco,2),
            'EXH fictif (pour dossiers non groupés) de ' || t_divers_xh.valeur || ' euros par journée au delà de ' || t_divers_bh.valeur || ' jours'
          FROM  w_cti_encours_calcul_parametres, w_cti_encours_factures
          JOIN activite.t_divers t_divers_bh ON t_divers_bh.code = 'ENCOURSBORNEHAUTE' AND base.cti_to_number(t_divers_bh.valeur) > 0
          JOIN activite.t_divers t_divers_xh ON t_divers_xh.code = 'ENCOURSEXHMOYEN' AND base.cti_to_number(t_divers_xh.valeur) > 0
          WHERE
            w_cti_encours_factures.type_t2a = '1' AND type_sejour <> '5' AND
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.ghs_id <= 0 OR w_simul = '1') AND
            w_cti_encours_factures.date_fin - w_cti_encours_factures.date_debut > base.cti_to_number(t_divers_bh.valeur) AND 
            COALESCE(rubrique_facturation_exh_id,0) <> 0 AND 
            COALESCE(prestation_exh_id,0) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') 
          ;
      
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'GHS bebes'; 
          -- GHS bébés
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, nb_prestation, montant_encours, lieu_id, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHSBB' AS type_ligne, w_cti_encours_factures.date_debut, w_cti_encours_factures.date_fin, 1, 1, w_cti_encours_calcul_parametres.coefficient_mco, 
              prestation_ghs_id, rubrique_facturation_ghs_id, rubrique_comptabilisation_ghs_id, 
              t_ghs_tarifs.tarif_ghs, 1, t_ghs_tarifs.tarif_ghs * w_cti_encours_calcul_parametres.coefficient_mco, lieu_sortie_id,
              'GHS bébé pour dossier groupé : ' || to_char(t_ghs.code,'FM0000') || ' (' || t_ghs.texte || ')'
          FROM w_cti_encours_calcul_parametres, w_cti_encours_factures
            JOIN base.t_ghs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe1_id
            JOIN base.t_ghs_tarifs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe1_id AND
                t_ghs_tarifs.ghs_id = t_ghs.oid AND t_ghs_tarifs.secteur = w_cti_encours_factures.secteur_tarif  AND w_cti_encours_factures.date_fin BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
          WHERE w_simul = '0' AND
            w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.ghs_bebe1_id > 0 AND
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG')
          UNION
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHSBB', w_cti_encours_factures.date_debut, w_cti_encours_factures.date_fin, 1, 1, w_cti_encours_calcul_parametres.coefficient_mco, 
              prestation_ghs_id, rubrique_facturation_ghs_id, rubrique_comptabilisation_ghs_id, 
              t_ghs_tarifs.tarif_ghs, 1, t_ghs_tarifs.tarif_ghs * w_cti_encours_calcul_parametres.coefficient_mco, lieu_sortie_id,
              'GHS bébé pour dossier groupé : ' || to_char(t_ghs.code,'FM0000') || ' (' || t_ghs.texte || ')'
          FROM w_cti_encours_calcul_parametres, w_cti_encours_factures
            JOIN base.t_ghs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe2_id
            JOIN base.t_ghs_tarifs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe2_id AND
                t_ghs_tarifs.ghs_id = t_ghs.oid AND t_ghs_tarifs.secteur = w_cti_encours_factures.secteur_tarif AND w_cti_encours_factures.date_fin BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
          WHERE w_simul = '0' AND
            w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.ghs_bebe2_id > 0 AND
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG')
          UNION
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHSBB', w_cti_encours_factures.date_debut, w_cti_encours_factures.date_fin, 1, 1, w_cti_encours_calcul_parametres.coefficient_mco, 
              prestation_ghs_id, rubrique_facturation_ghs_id, rubrique_comptabilisation_ghs_id, 
              t_ghs_tarifs.tarif_ghs, 1, t_ghs_tarifs.tarif_ghs * w_cti_encours_calcul_parametres.coefficient_mco, lieu_sortie_id,
              'GHS bébé pour dossier groupé : ' || to_char(t_ghs.code,'FM0000') || ' (' || t_ghs.texte || ')'
          FROM w_cti_encours_calcul_parametres, w_cti_encours_factures
            JOIN base.t_ghs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe3_id
            JOIN base.t_ghs_tarifs ON t_ghs.oid = w_cti_encours_factures.ghs_bebe3_id AND
                t_ghs_tarifs.ghs_id = t_ghs.oid AND t_ghs_tarifs.secteur = w_cti_encours_factures.secteur_tarif AND w_cti_encours_factures.date_fin BETWEEN t_ghs_tarifs.date_debut AND t_ghs_tarifs.date_fin
          WHERE w_simul = '0' AND
            w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.ghs_bebe3_id > 0 AND
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG');
          -- Valorisation non groupes
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Valorisation GHS non groupes';
  
          UPDATE w_cti_encours_factures
          SET classe_ghm = '05C19'
          WHERE EXISTS (
            SELECT no_sejour 
            FROM activite.p_factures_lignes_non_facturees_h 
              JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
              JOIN base.t_actes ON acte_id = t_actes.oid
            WHERE t_actes.code IN ('DELF013', 'DELF020', 'DELF014', 'DELF016', 'DELF086', 'DELA004','DEKA002')
              AND w_cti_encours_factures.no_sejour = p_factures.no_sejour
          );
  
          UPDATE w_cti_encours_factures
            SET classe_ghm = '05C19'
            WHERE EXISTS (
              SELECT no_sejour
              FROM activite.p_factures_lignes_h 
                JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
                JOIN base.t_actes ON acte_id = t_actes.oid
              WHERE t_actes.code IN ('DELF013', 'DELF020', 'DELF014', 'DELF016', 'DELA004','DEKA002') 
                AND classe_ghm = ''
                AND p_factures.no_sejour = w_cti_encours_factures.no_sejour
            )
            ;
  
          UPDATE w_cti_encours_factures
          SET classe_ghm = 'I01'
          WHERE EXISTS (
            SELECT no_sejour
            FROM activite.p_factures_lignes_non_facturees_h 
              JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
            WHERE acte_id = ANY(SELECT oid FROM base.t_actes WHERE code IN('JGNJ900'))
              AND w_cti_encours_factures.no_sejour = p_factures.no_sejour
           );
  
          UPDATE w_cti_encours_factures
          SET classe_ghm = 'I01'
          WHERE EXISTS (
            SELECT no_sejour
            FROM activite.p_factures_lignes_h
              JOIN activite.p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
            WHERE acte_id = ANY(SELECT oid FROM base.t_actes WHERE code IN('JGNJ900'))
              AND classe_ghm = ''
              AND w_cti_encours_factures.no_sejour = p_factures.no_sejour
          )
          ;
  
          UPDATE w_cti_encours_factures_lignes_c SET
            rubrique_facturation_id = rubrique_facturation_I01_id,
            rubrique_comptabilisation_id = rubrique_comptabilisation_I01_id,
            prestation_id = prestation_I01_id
          FROM activite.t_prestations,
            w_cti_encours_factures
            JOIN w_cti_encours_calcul_parametres ON 
              rubrique_facturation_I01_id IS NOT NULL AND
              rubrique_facturation_I01_id <> 0
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            w_cti_encours_factures_lignes_c.prestation_id = t_prestations.oid AND
            classe_ghm = 'I01' AND
            t_prestations.code = 'GHS'
          ;
          
  
          
          
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '01-MSD12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '02-MST12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '03-MSD18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '04-MST18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
  
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') de la spécialité ' || specialite_medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.specialite_medecin_sejour_id = w_cti_encours_factures.specialite_medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '05-PSD12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') de la spécialité ' || specialite_medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.specialite_medecin_sejour_id = w_cti_encours_factures.specialite_medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '06-PST12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
            
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '07-MXD12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '08-MXT12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '09-MXD18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '10-MXT18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
  
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') de la spécialité ' || specialite_medecin_sejour_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.specialite_medecin_sejour_id = w_cti_encours_factures.specialite_medecin_sejour_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '11-PXD12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') de la spécialité ' || specialite_medecin_sejour_texte || ' avec une durée de séjour de ' || tranche_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.specialite_medecin_sejour_id = w_cti_encours_factures.specialite_medecin_sejour_id AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '12-PXT12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
            
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') dans le service ' || lieu_sortie_service_texte || ' avec une durée de séjour de ' || duree_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              w_cti_encours_histo_ghs.duree_sejour = w_cti_encours_factures.duree_sejour AND
              w_cti_encours_histo_ghs.tranche_sejour = w_cti_encours_factures.tranche_sejour AND
              regle = '13-XSD18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
            
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              regle = '21-MSX12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte || ' dans le service ' || lieu_sortie_service_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              regle = '22-MSX18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 12 derniers mois (' || w_date_histo_12 || ') du médecin ' || medecin_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              regle = '51-MXX12'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') du médecin ' || medecin_sejour_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.medecin_sejour_id = w_cti_encours_factures.medecin_sejour_id AND
              regle = '52-MXX18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ') dans le service ' || lieu_sortie_service_texte,
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              w_cti_encours_histo_ghs.lieu_sortie_service_id = w_cti_encours_factures.lieu_sortie_service_id AND
              w_cti_encours_histo_ghs.lieu_sortie_unite_fonctionnelle_id = w_cti_encours_factures.lieu_sortie_unite_fonctionnelle_id AND
              regle = '61-XSX18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
      
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_moyen_ghs,
            prix_unitaire = montant_moyen_ghs,
            prix_unitaire_calcule = montant_moyen_ghs,
            regle_ghs = regle,
            regle_texte = 'P.U. Moyen GHS calculé sur les ' || nombre || ' séjours des 18 derniers mois (' || w_date_histo_18 || ')',
            type_ligne = 'GHSNG'
          FROM w_cti_encours_factures
            JOIN w_cti_encours_histo_ghs ON 
              w_cti_encours_histo_ghs.classe_ghm = w_cti_encours_factures.classe_ghm AND
              regle = '99-XXX18'
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            montant_encours = 0 AND
            type_ligne = 'GHS';
  
          -- Forcage prix GHS selon paramétrage dossier
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = prix_unitaire_force,
            prix_unitaire = prix_unitaire_force,
            regle_ghs = '00-FORCE',
            regle_texte = 'P.U. Moyen GHS forcé',
            type_ligne = 'GHSNG'
          FROM activite.t_calcul_encours
          WHERE w_cti_encours_factures_lignes_c.no_sejour = t_calcul_encours.no_sejour AND
            t_calcul_encours.type_ligne = 'GHSNG' AND
            t_calcul_encours.prix_unitaire_is_force = '1' AND
            w_cti_encours_factures_lignes_c.type_ligne = 'GHSNG';
  
          RAISE NOTICE '%. %' , w_date_encours_YYMM, 'GHS bebe moyen'; 
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, ghs_id,
            prix_unitaire, nb_prestation, montant_encours, lieu_id, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHSBBM' AS type_ligne, date_debut, date_fin, GREATEST(date_fin - date_debut,1), 1, w_cti_encours_calcul_parametres.coefficient_mco, 
            prestation_ghs_id, rubrique_facturation_ghs_id, rubrique_comptabilisation_ghs_id, -9981,
            base.cti_to_number(t_divers.valeur), 1, base.cti_to_number(t_divers.valeur), w_cti_encours_factures.lieu_sortie_id,
            'GHS Moyen paramétré pour les séjours bébés pour une maman dont le GHS est connu' AS regle_texte 
          FROM w_cti_encours_calcul_parametres, 
            w_cti_encours_factures
            JOIN activite.t_divers ON t_divers.code = 'ENCOURSGHSMBB' AND base.cti_to_number(t_divers.valeur) <> 0
          WHERE w_cti_encours_factures.type_t2a = '1' AND w_cti_encours_factures.type_sejour = '1' AND 
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.ghs_bebe1_id <= 0 OR w_simul = '1') AND
            w_cti_encours_factures.ghm_id NOT IN (SELECT oid FROM base.t_ghm WHERE code IN ('14Z08Z')) AND
            w_cti_encours_factures.ghm_id IN (SELECT oid FROM base.t_ghm WHERE code LIKE ('14%') AND (texte ILIKE '%sarienne%' OR texte ILIKE '%accouchement%') AND texte NOT ILIKE '%faux%')  AND
            COALESCE(rubrique_facturation_ghs_id,0) <> 0 AND 
            COALESCE(prestation_ghs_id,0) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') ;
  
            -- A la fin du premier passage, conserver le résultat
            IF _ENCOURSECARTGHSV > 0 AND w_simul = '1' THEN
              DROP TABLE IF EXISTS w_cti_encours_factures_lignes_c_simul_ng;
              CREATE TEMP TABLE w_cti_encours_factures_lignes_c_simul_ng AS
              SELECT w_cti_encours_factures_lignes_c.*
              FROM w_cti_encours_factures_lignes_c
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              WHERE t_prestations.code IN ('GHS','EXH')
              ;
            END IF;
  
            IF _ENCOURSECARTGHSV > 0 AND w_simul = '0' THEN
              INSERT INTO activite.t_prestations
                (code_original, code, texte, texte_court, clinique_honoraire)
              VALUES
                ('*GHSECARTV', 'GHS-ECART', 'Alerte écart valorisation GHS groupé', 'Alerte écart valorisation GHS groupé', '')
              ON CONFLICT ON CONSTRAINT t_prestations_code_key
              DO UPDATE SET
              code_original = EXCLUDED.code_original -- couvre le cas où code_original aurait été modifié (cf. import SIGEMS notamment)
                , texte = EXCLUDED.texte
                , texte_court = EXCLUDED.texte_court
                , clinique_honoraire = EXCLUDED.clinique_honoraire
              ;
                      
              -- A la fin du second passage, enregistrer les écarts importants
              INSERT INTO w_cti_encours_factures_lignes_c(
                no_sejour, 
                no_facture, 
                type_ligne, 
                date_debut, 
                date_fin, 
                nb_rubrique, 
                coefficient, 
                coefficient_mco, 
                prestation_id, 
                rubrique_facturation_id, 
                rubrique_comptabilisation_id, 
                ghs_id,
                prix_unitaire, 
                nb_prestation, 
                montant_encours, 
                lieu_id, 
                regle_texte)
            
              SELECT  subview_simul.no_sejour, 
                subview_simul.no_facture, 
                'GHSECART' AS type_ligne, 
                subview.date_debut, 
                subview.date_fin, 
                0::numeric AS nb_rubrique, 
                0::numeric AS coefficient, 
                0::numeric AS coefficient_mco, 
                t_prestations.oid AS prestation_id, 
                0::bigint AS rubrique_facturation_id, 
                0::bigint AS rubrique_comptabilisation_id, 
                subview.ghs_id,
                0::numeric AS prix_unitaire, 
                0::numeric AS nb_prestation, 
                0::numeric AS montant_encours, 
                subview.lieu_id, 
                'Montant GHS inférieur (-' || (montant_encours_simul-montant_encours)::text || 'E) / ' || subview_simul.regle_texte
              FROM
              (
              SELECT no_sejour, no_facture, 
                SUM(montant_encours) AS montant_encours_simul,
                MAX(CASE WHEN t_prestations.code = 'GHS' THEN regle_texte ELSE '' END) AS regle_texte
              FROM w_cti_encours_factures_lignes_c_simul_ng
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              WHERE t_prestations.code IN ('GHS','EXH')
              GROUP BY 1,2
              ) subview_simul
              JOIN 
              (
              SELECT no_sejour,
                no_facture,
                SUM(montant_encours) AS montant_encours,
                MAX(ghs_id) AS ghs_id,
                MIN(date_debut) AS date_debut,
                MAX(date_fin) AS date_fin,
                MAX(lieu_id) AS lieu_id
              FROM w_cti_encours_factures_lignes_c
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              WHERE t_prestations.code IN ('GHS','EXH')
              GROUP BY 1,2
              ) subview ON 
                subview_simul.no_sejour = subview.no_sejour AND
                subview_simul.no_facture = subview.no_facture
              JOIN activite.t_prestations ON t_prestations.code_original = '*GHSECARTV'
              left JOIN activite.t_rubriques_facturation ON t_rubriques_facturation.code_original = '*GHSECARTV'
              WHERE subview_simul.montant_encours_simul - montant_encours >= _ENCOURSECARTGHSV
              ;
            END IF;
          END LOOP;
  
          
          -- Ne pas générer ce qui est deja saisi en non facturé
          
          INSERT INTO w_cti_factures_lignes_non_facturees_c
          SELECT w_cti_encours_factures.no_sejour, 
            w_cti_encours_factures.no_facture, 
            CASE WHEN t_prestations.code IN ('FJA', 'FJR', 'FJS') THEN 'FJA' 
            WHEN t_prestations.code IN ('FJ') AND type_t2a = '1' THEN 'FJA' 
            ELSE t_prestations.code END AS prestation_code,
            MIN(CASE WHEN code_sorti = '1' AND type_sejour = '1' AND (p_factures_lignes_non_facturees_c.date_debut = w_cti_encours_factures.date_fin OR p_factures_lignes_non_facturees_c.date_fin = w_cti_encours_factures.date_fin AND nb_rubrique = 1) THEN '1' ELSE '0' END),
            MIN(COALESCE(t_prestations.type_valorisation_non_facture,'')) AS type_valorisation_non_facture				
          FROM w_cti_encours_factures
            JOIN activite.p_factures_lignes_non_facturees_c ON w_cti_encours_factures.no_facture = p_factures_lignes_non_facturees_c.no_facture
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE t_prestations.code NOT IN ('GHS', 'EXH', 'SRC', 'REA', 'STF') 
            OR
            (
            t_prestations.code IN ('SRC', 'REA', 'STF') AND
            w_cti_encours_factures.ghs_id > 0 AND
            w_OPTION_ENCOURSMCOSUP = '1'
            )
          GROUP BY 1,2,3
          UNION
          SELECT w_cti_encours_factures.no_sejour, 
            w_cti_encours_factures.no_facture, 
            CASE WHEN t_prestations.code IN ('FJA', 'FJR', 'FJS') THEN 'FJA' 
            WHEN t_prestations.code IN ('FJ') AND type_t2a = '1' THEN 'FJA' 
            ELSE t_prestations.code END AS prestation_code,
            MIN(CASE WHEN code_sorti = '1' AND type_sejour = '1' AND (p_factures_lignes_c.date_debut = w_cti_encours_factures.date_fin OR p_factures_lignes_c.date_fin = w_cti_encours_factures.date_fin AND nb_rubrique = 1) THEN '1' ELSE '0' END),
            MIN(COALESCE(t_prestations.type_valorisation_non_facture,'')) AS type_valorisation_non_facture						
          FROM w_cti_encours_factures
            JOIN activite.p_factures_lignes_c ON w_cti_encours_factures.no_facture = p_factures_lignes_c.no_facture
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE t_prestations.code NOT IN ('GHS', 'EXH', 'SRC', 'REA', 'STF', 'GMT') AND
            w_cti_encours_factures.particularites_encours_service NOT ILIKE '%MAT%' AND
            w_cti_encours_factures.particularites_encours_service NOT ILIKE '%PASDEFJA%' AND
            montant_facture <> 0 AND
            w_cti_encours_factures.date_fin <= w_date_traitement
          GROUP BY 1,2,3
          ;
  
          -- Si PJ en saisi, il faut considérer que le FJ est inclus si le FJ n'est pas saisi
          INSERT INTO w_cti_factures_lignes_non_facturees_c
          SELECT 
            w_cti_factures_lignes_non_facturees_c.no_sejour, 
            w_cti_factures_lignes_non_facturees_c.no_facture, 
            'FJ' AS prestation_code, 
            w_cti_factures_lignes_non_facturees_c.only_jour_sortie, 
            ''::text AS type_valorisation_non_facture
          FROM w_cti_factures_lignes_non_facturees_c 
          LEFT JOIN w_cti_factures_lignes_non_facturees_c w_cti_factures_lignes_non_facturees_c_fj ON
            w_cti_factures_lignes_non_facturees_c.no_sejour = w_cti_factures_lignes_non_facturees_c_fj.no_sejour AND
            w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_factures_lignes_non_facturees_c_fj.no_facture AND
            w_cti_factures_lignes_non_facturees_c_fj.prestation_code = 'FJ'
          WHERE w_cti_factures_lignes_non_facturees_c.prestation_code = 'PJ' AND
            w_cti_factures_lignes_non_facturees_c_fj.no_facture IS NULL
            ;
      
          -- PJ FJ ENT GMT
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'PJ FJ ENT GMT';          
          INSERT INTO w_cti_encours_factures_lignes_c(no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, prix_unitaire, montant_encours, lieu_id, regle_texte)
          SELECT 
              w_cti_encours_factures.no_sejour
              , w_cti_encours_factures.no_facture
              , CASE 
                  WHEN w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('PJ') THEN 'PJ'
                  WHEN w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('GMT') THEN 'GMT'
              ELSE w_cti_encours_calcul_parametres_services_prestations.prestation_code END AS type_ligne
              , p_mouvements_sejour.date
              , p_mouvements_sejour.date
              , 1
              , 1 
              , 1
              , 1
              , prestation_id
              , rubrique_facturation_id
              , rubrique_facturation_id
              , MAX(prix_unitaire)
              , MAX(round(prix_unitaire,2))
              , MAX(p_mouvements_sejour.lieu_id)
              , 'GMT et forfaits journaliers'
        FROM w_cti_encours_factures
        	JOIN activite.p_sejours ON w_cti_encours_factures.no_sejour = p_sejours.no_sejour
        	JOIN activite.t_divers ON t_divers.code = 'OPTADM_DAYOUT'
        	JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
        	JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
        	JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id 
        		AND t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id 
        		AND (
                      prestation_code IN ('GMT', 'PJ', 'FJ', 'ENT', 'PMS') 
                      OR w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('GMT', 'PJ','ENT')
                )
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture 
        	    AND w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code
        WHERE
        	type_t2a IN ('2','3') 
        	AND uniquement_prestations_saisies <> '1' 
        	AND (est_jour_hospitalisation = '1' 
        		 OR p_mouvements_sejour.nb_ambulatoires = 1) 
        	AND w_cti_factures_lignes_non_facturees_c.no_facture IS NULL 
        	AND (
                w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ', 'FJ') AND type_t2a = 3 AND nb_sorties_directes = 0 AND p_mouvements_sejour.date <> p_sejours.date_sortie 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ', 'FJ') AND type_t2a = 3 AND nb_sorties_directes = 1 AND p_mouvements_sejour.date = p_sejours.date_sortie AND (p_mouvements_sejour.heure_fin > 130000 OR t_divers.valeur = '2') 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ', 'FJ') AND type_t2a = 3 AND p_mouvements_sejour.nb_ambulatoires = 1 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('GMT', 'FJ') AND type_t2a = 2 AND nb_sorties_directes = 0 AND p_mouvements_sejour.date <> p_sejours.date_sortie 
        		OR  w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('GMT', 'FJ') AND type_t2a = 2 AND nb_sorties_directes = 1 AND p_mouvements_sejour.date = p_sejours.date_sortie AND (p_mouvements_sejour.heure_fin > 130000 OR t_divers.valeur = '2') 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('GMT', 'FJ') AND type_t2a = 2 AND p_mouvements_sejour.nb_ambulatoires = 1 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('PJ') AND nb_sorties_directes = 0 AND p_mouvements_sejour.date <> p_sejours.date_sortie 
        		OR  w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('PJ') AND nb_sorties_directes = 1 AND p_mouvements_sejour.date = p_sejours.date_sortie AND (p_mouvements_sejour.heure_fin > 130000 OR t_divers.valeur = '2') 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('PJ') AND p_mouvements_sejour.nb_ambulatoires = 1 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('ENT') AND nb_entrees_directes = 1 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('ENT') AND nb_entrees_directes = 1 
        		OR w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PMS') AND p_mouvements_sejour.jour_semaine = 7
  		    ) 
        	AND COALESCE(rubrique_facturation_id,0) <> 0 
        	AND COALESCE(prestation_id,0) <> 0 
        	AND (
                p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin 
        		OR service_facturation_id NOT IN (SELECT oid FROM activite.t_services_facturation WHERE avec_facturation_intermediaire = '1'
            )
        )
       	GROUP BY  
            w_cti_encours_factures.no_sejour
            , w_cti_encours_factures.no_facture
            , 3
            , p_mouvements_sejour.date
            , 6
            , 7
            , 8
            , 9
            , prestation_id
            , rubrique_facturation_id
            , 16
        ;

  		UPDATE w_cti_encours_factures_lignes_c
  		SET 
            montant_encours = p_gmt_valorises.montant_valorise_par_jour
            , prix_unitaire = p_gmt_valorises.montant_valorise_par_jour 
  		FROM activite.p_gmt_valorises
  		WHERE 1 = 1 
  			AND w_cti_encours_factures_lignes_c.no_sejour = p_gmt_valorises.no_sejour
  			AND w_cti_encours_factures_lignes_c.type_ligne = 'GMT'
  			AND w_cti_encours_factures_lignes_c.date_debut BETWEEN p_gmt_valorises.date_debut_gmt::date AND p_gmt_valorises.date_fin_gmt::date
  		;
  			
          -- Sur budget global, il faut générer le Ticket modérateur
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'TM Budget Global MCO';
          
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'TMBG' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, (100-taux_ghs_1)/100, 1, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire*(100-taux_ghs_1)/100), p_mouvements_sejour.lieu_id,
            regle_taux_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              (prestation_code IN ('PJ') 
              )
            JOIN w_cti_encours_factures_histo_taux ON lieu_sortie_service_id = w_cti_encours_factures_histo_taux.service_facturation_id AND taux_ghs_1 < 100
          
          WHERE 
            type_t2a = '1' AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_factures.no_facture NOT LIKE '%BG' AND
            w_cti_encours_factures.no_sejour IN (SELECT no_sejour FROM w_cti_encours_factures_lignes_c WHERE prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code = 'GHS')) AND
            (est_jour_hospitalisation = '1' OR p_mouvements_sejour.nb_ambulatoires = 1) AND
            (
            w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ') AND nb_sorties_directes = 0 AND p_mouvements_sejour.date <> w_cti_encours_factures.date_fin OR 
            w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ') AND nb_sorties_directes = 0 AND p_mouvements_sejour.date = w_cti_encours_factures.date_fin AND p_mouvements_sejour.heure_fin > 130000 OR
            w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('PJ') AND p_mouvements_sejour.nb_ambulatoires = 1
            ) AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            (p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin ) AND
            w_cti_encours_factures.duree_sejour <= 30 AND
            w_cti_encours_factures.no_sejour NOT IN (SELECT no_sejour FROm w_actes_120)
          ;
  
          -- Sur budget global, il faut générer éventuellement les suppléments irradiation
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Suppléments irradiation';
          
          
          
          -- GHT (HAD)
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'GHT'; 
  
          -- Tranche manquante
          DROP TABLE IF EXISTS w_cti_encours_calcul_parametres_services_prestations_t;
          CREATE TEMP TABLE w_cti_encours_calcul_parametres_services_prestations_t AS
          SELECT w_cti_encours_calcul_parametres_services_prestations.*,
            tranche_ght_req
          FROM w_cti_encours_calcul_parametres_services_prestations
          JOIN (
            SELECT tranche_ght_req, lieu_service_id, lieu_unite_fonctionnelle_id, MAX(tranche_ght) AS tranche_ght_sel
            FROM w_cti_encours_calcul_parametres_services_prestations
            JOIN 
            (SELECT '1'::text AS tranche_ght_req UNION SELECT '2'::text UNION SELECT '3' UNION SELECT '9') subview ON 1=1
            WHERE prestation_code = 'GHT' AND
              (lieu_service_id || '-' || lieu_unite_fonctionnelle_id) NOT IN 
                (SELECT lieu_service_id || '-' || lieu_unite_fonctionnelle_id 
                FROM w_cti_encours_calcul_parametres_services_prestations
                WHERE prestation_code = 'GHT' AND
                  tranche_ght = tranche_ght_req
                )
                GROUP BY 1,2,3
            ) subview ON 
              w_cti_encours_calcul_parametres_services_prestations.lieu_service_id = subview.lieu_service_id AND
              w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id = subview.lieu_unite_fonctionnelle_id AND
              w_cti_encours_calcul_parametres_services_prestations.tranche_ght = tranche_ght_sel
          ;
  
          UPDATE w_cti_encours_calcul_parametres_services_prestations_t
          SET tranche_ght = tranche_ght_req
          ;
  
          ALTER TABLE w_cti_encours_calcul_parametres_services_prestations_t DROP COLUMN tranche_ght_req
          ;
  
          INSERT INTO w_cti_encours_calcul_parametres_services_prestations
          SELECT *
          FROM w_cti_encours_calcul_parametres_services_prestations_t
          ;
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'GHT' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, p_mouvements_sejour.lieu_id, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient,2), regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN activite.p_factures ON w_cti_encours_factures.no_facture = p_factures.no_facture
            JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('GHT') AND
              CASE 
                WHEN p_mouvements_sejour.date - p_sejours.date_entree <= 3 THEN '1'
                WHEN p_mouvements_sejour.date - p_sejours.date_entree BETWEEN 4 AND 8 THEN '2'
                WHEN p_mouvements_sejour.date - p_sejours.date_entree BETWEEN 9 AND 30 THEN '3'
                ELSE '9' END = tranche_ght
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code
          WHERE 
            type_t2a <> '1' AND
            uniquement_prestations_saisies <> '1' AND
            est_jour_hospitalisation = '1' AND
            p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin AND
            (p_mouvements_sejour.date <> w_cti_encours_factures.date_fin OR p_mouvements_sejour.heure_fin > 130000 OR p_sejours.date_sortie = p_sejours.date_entree) AND
            (nb_sorties_directes = 0 OR p_sejours.date_sortie = p_sejours.date_entree) AND
            coefficient > 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0
          ORDER BY 1,4;
            
          -- Chambres particulières
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Chambres particulieres'; 
  
          -- Si plusieurs factures de référence (SSR), essayer de trouver la bonne prestation
          DROP TABLE IF EXISTS w_cti_encours_sejour_deja_cpc;
          CREATE TEMP TABLE w_cti_encours_sejour_deja_cpc AS
          SELECT p_factures.no_sejour, 
            prestation_id, 
            MAX(t_prestations.code) AS prestation_code,
            MAX(rubrique_facturation_id) AS rubrique_facturation_id, 
            MAX(p_factures_lignes_c.date_debut) AS date_debut, 
            (MAX(Array[p_factures_lignes_c.date_debut::text, 
            to_char(prix_unitaire,'FM000000000.00')]))[2]::numeric AS prix_unitaire
          FROM activite.p_factures_lignes_c
          JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
          JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE p_factures_lignes_c.montant_facture <> 0 AND
            p_factures.no_sejour IN (SELECT no_sejour FROM w_cti_encours_factures) AND
            p_factures.no_sejour IN (SELECT no_sejour FROM activite.p_factures WHERE no_facture = no_facture_reference GROUP BY 1 HAVING count(*) > 1) AND
              (t_prestations.code IN ('CPC', 'SHO', 'CP') OR
              t_prestations.type_valorisation_non_facture IN ('CP') 
              )
          GROUP BY 1,2
          HAVING SUM(nb_prestation) > 0
          ;
          
          DELETE FROM w_cti_encours_sejour_deja_cpc
          USING
          (
          SELECT no_sejour, MAX(date_debut) AS date_debut
          FROM w_cti_encours_sejour_deja_cpc
          GROUP BY 1
          HAVING count(DISTINCT date_debut) > 1
          ) subview
          WHERE w_cti_encours_sejour_deja_cpc.no_sejour = subview.no_sejour AND
            w_cti_encours_sejour_deja_cpc.date_debut < subview.date_debut
          ;
  
          -- Pas de CPC déjà facturées, prendre les moyennes
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, regle_coefficient, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'CPC' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, p_mouvements_sejour.lieu_id, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient,2), coefficient,
            regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN activite.p_factures ON w_cti_encours_factures.no_facture = p_factures.no_facture
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
              (w_cti_encours_calcul_parametres_services_prestations.prestation_code IN ('CPC', 'SHO', 'CP') OR
              w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation IN ('CP')
              ) 
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              (
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('CPC', 'SHO', 'CP', 'FORAMB') OR
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code OR
              w_cti_factures_lignes_non_facturees_c.type_valorisation_non_facture IN ('CP')
              ) AND
              only_jour_sortie <> '1'
          WHERE 
            (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_ambulatoires = 1) AND
            est_chambre_particuliere = '1' AND
            coefficient <> 0 AND
            uniquement_prestations_saisies <> '1' AND
            (p_mouvements_sejour.date <> w_cti_encours_factures.date_fin OR p_mouvements_sejour.heure_fin > 130000 OR p_mouvements_sejour.nb_ambulatoires = 1) AND
            p_mouvements_sejour.date <= w_cti_encours_factures.date_fin AND
            (p_factures.code_cp_demandee = '1' OR w_OPTION_ENCOURSVALOCP = '1') AND
            nb_sorties_directes = 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            w_cti_encours_factures.no_facture NOT LIKE '%BG' AND
            w_cti_encours_factures.no_facture_reference NOT IN (SELECT no_facture_reference FROM w_cti_encours_factures_deja_cpc) AND
            w_cti_encours_factures.no_sejour NOT IN (SELECT no_sejour FROM w_cti_encours_sejour_deja_cpc) AND
            (
            p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin OR
            service_facturation_id NOT IN (SELECT oid FROM activite.t_services_facturation WHERE avec_facturation_intermediaire = '1')
            )
            
          ORDER BY 1,4;
  
          -- CPC déjà facturées, prendre le dernier PU
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, regle_coefficient, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'CPC' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, p_mouvements_sejour.lieu_id, 1, 1, 1::numeric AS coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            w_cti_encours_sejour_deja_cpc.prix_unitaire, w_cti_encours_sejour_deja_cpc.prix_unitaire, 1::numeric AS coefficient,
            'Reconduite facturation antérieure ('||w_cti_encours_sejour_deja_cpc.date_debut::text||')' AS regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN activite.p_factures ON w_cti_encours_factures.no_facture = p_factures.no_facture
            JOIN w_cti_encours_sejour_deja_cpc ON w_cti_encours_factures.no_sejour = w_cti_encours_sejour_deja_cpc.no_sejour
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              (
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('CPC', 'SHO', 'CP', 'FORAMB') OR
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_sejour_deja_cpc.prestation_code OR
              w_cti_factures_lignes_non_facturees_c.type_valorisation_non_facture IN ('CP')
              ) AND
              only_jour_sortie <> '1'
          WHERE 
            (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_ambulatoires = 1) AND
            est_chambre_particuliere = '1' AND
            uniquement_prestations_saisies <> '1' AND
            (p_mouvements_sejour.date <> w_cti_encours_factures.date_fin OR p_mouvements_sejour.heure_fin > 130000 OR p_mouvements_sejour.nb_ambulatoires = 1) AND
            p_mouvements_sejour.date <= w_cti_encours_factures.date_fin AND
            nb_sorties_directes = 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            w_cti_encours_factures.no_facture NOT LIKE '%BG' AND
            w_cti_encours_factures.no_facture_reference NOT IN (SELECT no_facture_reference FROM w_cti_encours_factures_deja_cpc) AND
            (
            p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin OR
            service_facturation_id NOT IN (SELECT oid FROM activite.t_services_facturation WHERE avec_facturation_intermediaire = '1')
            )
          ORDER BY 1,4;
          
          -- SRC, REA, STF
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'SRC, REA, STF'; 
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_coefficient, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'SSS' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient * coefficient_mco), (MAX(Array[p_mouvements_sejour.heure_fin,p_mouvements_sejour.lieu_id]))[2],
            coefficient, regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              prestation_code IN ('SRC', 'REA', 'STF')
          WHERE 
            
            type_t2a = '1' AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
            coefficient > 0 AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            p_mouvements_sejour.date <= w_cti_encours_factures.date_fin AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND
            NOT (
              w_OPTION_ENCOURSMCOSUP = '1' AND
              w_cti_encours_factures.ghs_id > 0 
              )
          GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17
          HAVING 
            (MAX(p_mouvements_sejour.heure_fin) = 240000 OR MIN(p_mouvements_sejour.heure_debut) > 0 AND MAX(p_mouvements_sejour.heure_fin) < 240000 OR 
            MAX(nb_sorties_directes) = 1 AND MAX(mode_sortie) IN ('9'))
          ;
          -- IGM, IGP, IMD, IMI, IPD
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'AMD, AMF, APD, IGM, IGP, IMD, IMI, IPD, IVG'; 
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_coefficient,regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'IVG' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient * coefficient_mco), p_mouvements_sejour.lieu_id,
            coefficient, regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              prestation_code IN ('AMD', 'AMF', 'APD', 'IGM', 'IGP', 'IMD', 'IMI', 'IPD', 'IVG')
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_sejour = w_cti_encours_factures.no_sejour AND
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('AMD', 'AMF', 'APD', 'IGM', 'IGP', 'IMD', 'IMI', 'IPD', 'IVG')
          WHERE 
            (
              p_mouvements_sejour.nb_externes = 1 OR 
              p_mouvements_sejour.nb_ambulatoires = 1 AND type_t2a <> '1' OR 
              w_cti_encours_factures.particularites_encours_service ILIKE '%IVG%' OR
              w_cti_encours_factures.ghm_id IN (SELECT oid FROM base.t_ghm WHERE code IN ('14Z08Z'))
            ) AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
            (p_mouvements_sejour.nb_externes = 1 OR p_mouvements_sejour.nb_ambulatoires = 1 OR p_mouvements_sejour.nb_entrees_directes = 1) AND
            coefficient > 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0;
      -- NN1, NN2, NN3
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'NN1, NN2, NN3'; 
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_coefficient, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'NNX' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            (MAX(ARRAY[p_mouvements_sejour.heure_fin,prix_unitaire]))[2],
            (MAX(ARRAY[p_mouvements_sejour.heure_fin,round(prix_unitaire * coefficient * coefficient_mco)]))[2],
            (MAX(ARRAY[p_mouvements_sejour.heure_fin,p_mouvements_sejour.lieu_id]))[2],
            (MAX(ARRAY[p_mouvements_sejour.heure_fin,coefficient]))[2],
            (MAX(ARRAY[to_char(p_mouvements_sejour.heure_fin,'000000'),regle_prestation_texte]))[2]
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour AND
              p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              prestation_code IN ('NN1', 'NN2', 'NN3')
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code LIKE 'NN%'
          WHERE 
            (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.heure_debut > 0 AND p_mouvements_sejour.heure_fin < 240000) AND
            type_t2a = '1' AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
            coefficient > 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG')
           GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12;
      -- D09 D11 D13
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Dxx'; 
          -- Seances de dialyse dans les actes non facturés
          DROP TABLE IF EXISTS w_actes_seance_jvj;
          CREATE TEMP TABLE w_actes_seance_jvj AS
          SELECT p_factures.no_sejour, p_factures_lignes_non_facturees_h.date_debut AS date_seance
            FROM activite.p_factures_lignes_non_facturees_h
            JOIN activite.p_factures ON p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
            JOIN base.t_actes ON acte_id = t_actes.oid
            WHERE t_actes.code LIKE 'JVJ%' AND t_actes.code NOT LIKE 'JVJF002%'
          GROUP BY 1,2
          ;
          -- Seances deja facturées
          DROP TABLE IF EXISTS w_cti_factures_seances_deja_facturees;
          CREATE TEMP TABLE w_cti_factures_seances_deja_facturees AS
          SELECT p_sejours.no_sejour, p_factures_lignes_c.date_debut
          FROM activite.p_factures
          JOIN activite.p_sejours ON p_sejours.no_sejour = p_factures.no_sejour
          JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
          JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE type_sejour = '5' AND
            montant_facture <> 0 AND
            t_prestations.code IN ('D09','D11','D13', 'D13', 'D15', 'D16', 'DTP') AND
            p_sejours.no_sejour IN (SElECT no_sejour FROM activite.p_factures WHERE code_facture = '0') 
          GROUP BY 1,2
          HAVING SUM(montant_facture) > 0	
          ;
  
          CREATE INDEX i_w_cti_factures_seances_deja_facturees_1
              ON w_cti_factures_seances_deja_facturees
              USING btree (no_sejour)
              ;
  
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_coefficient, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'DIA' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient * coefficient_mco), p_mouvements_sejour.lieu_id,
            coefficient, regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour AND p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            LEFT JOIN w_actes_seance_jvj ON w_actes_seance_jvj.no_sejour = w_cti_encours_factures.no_sejour AND
                    w_actes_seance_jvj.date_seance = p_mouvements_sejour.date
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              prestation_code IN ('D09','D11','D13', 'D13', 'D15', 'D16', 'DTP')
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code
            LEFT JOIN w_cti_factures_seances_deja_facturees ON 
              p_mouvements_sejour.no_sejour = w_cti_factures_seances_deja_facturees.no_sejour AND
              p_mouvements_sejour.date = w_cti_factures_seances_deja_facturees.date_debut
              
          WHERE 
            (p_mouvements_sejour.nb_seances > 0) AND
            coefficient > 0 AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND
            w_cti_factures_seances_deja_facturees.no_sejour IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            (w_actes_seance_jvj.no_sejour IS NOT NULL OR w_cti_encours_factures.type_sejour = '5') AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG');
          -- FJA
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'FJA'; 
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'FJA' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, 1, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, prix_unitaire, p_mouvements_sejour.lieu_id, 'Forfait jour de sortie (Sauf maternité) '
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              prestation_code IN ('FJA')
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code
          WHERE nb_sorties_directes = 1 AND
            mode_sortie IN ('6', '8') AND
            uniquement_prestations_saisies <> '1' AND
            base.cti_division(w_cti_encours_calcul_parametres_services_prestations.nombre,w_cti_encours_calcul_parametres_services_prestations.nb_journees)*100 >= 1 AND
            w_cti_encours_factures.particularites_encours_service NOT ILIKE '%MAT%' AND
            w_cti_encours_factures.particularites_encours_service NOT ILIKE '%PASDEFJA%' AND
            prix_unitaire > 0 AND
            w_cti_encours_factures.duree_sejour > 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            w_cti_encours_factures.no_facture NOT LIKE '%BG' AND
            (p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin OR
            service_facturation_id NOT IN (SELECT oid FROM activite.t_services_facturation WHERE avec_facturation_intermediaire = '1')
            );
          -- ATU
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'ATU'; 
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_coefficient)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'ATU' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, coefficient, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire * coefficient), p_mouvements_sejour.lieu_id,
            coefficient
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              (
              prestation_code = 'ATU' AND p_mouvements_sejour.date <= '20211231' OR
              prestation_code = 'FPU' AND p_mouvements_sejour.date >= '20220101'
              )
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_sejour = w_cti_encours_factures.no_sejour AND
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('ATU','FPU')
          WHERE 
            p_mouvements_sejour.nb_externes = 1 AND
            p_mouvements_sejour.nb_externes = 1 AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation <> ('*SAISIE') AND
            coefficient > 0 AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0;
          
          
          -- Identification des SE pour ne pas générer de GHS
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'SE1, SE2, SE3, SE4'; 
          INSERT INTO w_cti_encours_actes_se1234
          SELECT t_actes.oid, t_actes.code,
            CASE 
            WHEN t_actes.code IN ('FEJF003') 
              THEN 'SE4'
            WHEN t_actes.code IN ('AGLB001', 'AHLB003', 'AHLB015', 'AHLB016', 'AHLH014', 'GGHB002', 'GGJB001', 'GGJB002', 'HPJB001', 'JGHB001', 'JGHB002', 'JGHD001', 'JGHJ001', 'JGHJ002', 'JPHJ001', 'JPHJ002') 
              THEN 'SE3'
            WHEN t_actes.code IN ('AELB002', 'AHHA001', 'AHHA002', 'BAGA001', 'BBGA001', 'BDCA003', 'BEJB001', 'BEJB002', 'BELB001', 'BEPA001', 'BGHA001', 'BGJB001', 'BGLB001', 'BGLB002', 'BKLB001', 'CAEA002', 'CAFA006', 'CBLD001', 'CBLD003', 'EBGA001', 'EBHA001', 'EBNE002', 'EGFA007', 'FCFA012', 'FCFA028', 'GBJD002', 'JAHB001', 'JAHJ002', 'JAHJ006', 'JAKD001', 'JCKD001', 'JDLF001', 'JHSB001', 'LHNH001', 'MDGB001', 'MHDB001', 'NJAB001', 'NJMB001', 'PAGB002', 'PAGH001', 'PDFA001', 'QAGA004', 'QZFA001', 'QZFA002', 'QZFA005', 'QZFA007', 'QZGA003', 'QZGA006')
              THEN 'SE2'
            WHEN t_actes.code IN ('BBCE001', 'DZQJ001', 'DZQJ008', 'DZQJ010', 'DZQJ011', 'GBQA002', 'GDQE004', 'GEQE002', 'GEQE004', 'GEQE006', 'GEQE007', 'GEQE009', 'GEQE010', 'GEQH002', 'HEGE001', 'HEGE002', 'HEQE001', 'HEQE002', 'HEQE003', 'HEQE005', 'HGNE001', 'HGQE002', 'HJQE001', 'HMQH007', 'JCGE003', 'JCGE004', 'JDQE001', 'JDQE002', 'JDQE003', 'JEGE001', 'JEHE002')
              THEN 'SE1'
            ELSE '' 
            END AS prestation_code
          FROM base.t_actes
          WHERE t_actes.code IN ('FEJF003',
                  'AGLB001', 'AHLB003', 'AHLB015', 'AHLB016', 'AHLH014', 'GGHB002', 'GGJB001', 'GGJB002', 'HPJB001', 'JGHB001', 'JGHB002', 'JGHD001', 'JGHJ001', 'JGHJ002', 'JPHJ001', 'JPHJ002',
                  'AELB002', 'AHHA001', 'AHHA002', 'BAGA001', 'BBGA001', 'BDCA003', 'BEJB001', 'BEJB002', 'BELB001', 'BEPA001', 'BGHA001', 'BGJB001', 'BGLB001', 'BGLB002', 'BKLB001', 'CAEA002', 'CAFA006', 'CBLD001', 'CBLD003', 'EBGA001', 'EBHA001', 'EBNE002', 'EGFA007', 'FCFA012', 'FCFA028', 'GBJD002', 'JAHB001', 'JAHJ002', 'JAHJ006', 'JAKD001', 'JCKD001', 'JDLF001', 'JHSB001', 'LHNH001', 'MDGB001', 'MHDB001', 'NJAB001', 'NJMB001', 'PAGB002', 'PAGH001', 'PDFA001', 'QAGA004', 'QZFA001', 'QZFA002', 'QZFA005', 'QZFA007', 'QZGA003', 'QZGA006',
                  'BBCE001', 'DZQJ001', 'DZQJ008', 'DZQJ010', 'DZQJ011', 'GBQA002', 'GDQE004', 'GEQE002', 'GEQE004', 'GEQE006', 'GEQE007', 'GEQE009', 'GEQE010', 'GEQH002', 'HEGE001', 'HEGE002', 'HEQE001', 'HEQE002', 'HEQE003', 'HEQE005', 'HGNE001', 'HGQE002', 'HJQE001', 'HMQH007', 'JCGE003', 'JCGE004', 'JDQE001', 'JDQE002', 'JDQE003', 'JEGE001', 'JEHE002'
                  )
          ;
          INSERT INTO w_cti_encours_se1234
          SELECT p_factures_lignes_h.no_facture,
             (MAX(ARRAY[w_cti_encours_actes_se1234.prestation_code,w_cti_encours_actes_se1234.code]))[2] AS acte_se,
             (MAX(ARRAY[w_cti_encours_actes_se1234.prestation_code,w_cti_encours_actes_se1234.code]))[1] AS type_se
          FROM activite.p_factures_lignes_h 
            JOIN w_cti_encours_factures ON p_factures_lignes_h.no_facture = w_cti_encours_factures.no_facture AND type_sejour IN ('3')
            JOIN w_cti_encours_actes_se1234 ON acte_id = w_cti_encours_actes_se1234.oid 
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = p_factures_lignes_h.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('SE1','SE2','SE3','SE4','SE5','SE6','SE7')
          WHERE w_cti_factures_lignes_non_facturees_c.no_facture IS NULL
          GROUP BY 1;
          INSERT INTO w_cti_encours_se1234 
          SELECT p_factures_lignes_non_facturees_h.no_facture,
            (MAX(ARRAY[w_cti_encours_actes_se1234.prestation_code,w_cti_encours_actes_se1234.code]))[2] AS acte_se,
             (MAX(ARRAY[w_cti_encours_actes_se1234.prestation_code,w_cti_encours_actes_se1234.code]))[1] AS type_se
          FROM activite.p_factures_lignes_non_facturees_h 
            JOIN w_cti_encours_factures ON p_factures_lignes_non_facturees_h.no_facture = w_cti_encours_factures.no_facture AND type_sejour IN ('3')
            JOIN w_cti_encours_actes_se1234 ON acte_id = w_cti_encours_actes_se1234.oid 
            LEFT JOIN w_cti_encours_se1234 ON p_factures_lignes_non_facturees_h.no_facture = w_cti_encours_se1234.no_facture
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = p_factures_lignes_non_facturees_h.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code IN ('SE1','SE2','SE3','SE4','SE5','SE6','SE7')
          WHERE w_cti_encours_se1234.no_facture IS NULL AND w_cti_factures_lignes_non_facturees_c.no_facture IS NULL
          GROUP BY 1;
          
          
    
              
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, lieu_id, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'SEH' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, 1, 1, 1, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, prix_unitaire, p_mouvements_sejour.lieu_id,
            'Prestation générée par l''acte : '||acte_se AS regle_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour AND nb_externes > 0
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN w_cti_encours_se1234 ON w_cti_encours_factures.no_facture = w_cti_encours_se1234.no_facture
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id
          WHERE 
            prix_unitaire > 0 AND
            uniquement_prestations_saisies <> '1' AND
            w_cti_encours_se1234.type_se = prestation_code AND 
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG');
            
          -- Prestations valorisées selon prix unitaire moyen par jour de présence dans service
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Prestations selon PU moyen par jour'; 
          
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, lieu_id, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, regle_texte)
          SELECT 
            w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'PRESTAM' AS type_ligne, p_mouvements_sejour.date, p_mouvements_sejour.date, p_mouvements_sejour.lieu_id, 1, 1, 1, 1,
            prestation_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(prix_unitaire,2), regle_prestation_texte
          FROM w_cti_encours_factures
            JOIN activite.p_mouvements_sejour ON w_cti_encours_factures.no_sejour = p_mouvements_sejour.no_sejour
            JOIN activite.t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
            JOIN activite.p_factures ON w_cti_encours_factures.no_facture = p_factures.no_facture
            JOIN w_cti_encours_calcul_parametres_services_prestations ON t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation = '*AVGJOUSER'
            LEFT JOIN w_cti_factures_lignes_non_facturees_c ON w_cti_factures_lignes_non_facturees_c.no_facture = w_cti_encours_factures.no_facture AND
              w_cti_factures_lignes_non_facturees_c.prestation_code = w_cti_encours_calcul_parametres_services_prestations.prestation_code 
          WHERE 
            (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.heure_debut > 0 AND p_mouvements_sejour.heure_fin < 240000) AND
            w_cti_factures_lignes_non_facturees_c.no_facture IS NULL AND 
            w_cti_encours_calcul_parametres_services_prestations.prix_unitaire > 0 AND
            COALESCE(rubrique_facturation_id,0) <> 0 AND 
            COALESCE(prestation_id,0) <> 0 AND
            uniquement_prestations_saisies <> '1' AND
            (w_cti_encours_factures.est_budget_global <> '1' OR w_cti_encours_factures.no_facture LIKE '%BG') AND
            (p_mouvements_sejour.date BETWEEN w_cti_encours_factures.date_debut AND w_cti_encours_factures.date_fin OR
            service_facturation_id NOT IN (SELECT oid FROM activite.t_services_facturation WHERE avec_facturation_intermediaire = '1')
            )
          ORDER BY 1,4;
          -- Prestations saisies
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Prestations saisies'; 
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, lpp_id, ucd_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours, regle_texte)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'SAISIE' AS type_ligne, p_factures_lignes_non_facturees_c.date_debut, p_factures_lignes_non_facturees_c.date_fin, nb_rubrique, nb_rubrique, coefficient, 
            COALESCE(p_factures_lignes_non_facturees_c.coefficient_mco,1) AS coefficient_mco,
            prestation_id, COALESCE(p_factures_lignes_non_facturees_c.lpp_id,0) AS lpp_id, COALESCE(p_factures_lignes_non_facturees_c.ucd_id,0) AS ucd_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, round(nb_rubrique * coefficient * COALESCE(p_factures_lignes_non_facturees_c.coefficient_mco,1) * prix_unitaire * CASE WHEN t_prestations.code IN ('PJ', 'GMT') AND taux_1_bg BETWEEN 1 AND 99 THEN 100-taux_1_bg ELSE 100 END / 100,2), 'Prestation saisie'
          FROM w_cti_encours_factures
            JOIN activite.p_factures_lignes_non_facturees_c ON w_cti_encours_factures.no_facture = p_factures_lignes_non_facturees_c.no_facture
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid
            LEFT JOIN
              (
                SELECT p_factures.no_sejour, MAX(taux_1) AS taux_1_bg
                FROM activite.p_factures_lignes_c
                JOIN activite.p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
                JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                JOIN w_cti_encours_factures ON p_factures.no_sejour = w_cti_encours_factures.no_sejour
                WHERE p_factures.no_facture LIKE '%BG' AND t_prestations.code = 'GHS' AND taux_1 > 0
                GROUP BY 1
              ) subview_fac_bg ON w_cti_encours_factures.no_sejour = subview_fac_bg.no_sejour
          WHERE 
  			  (
              t_prestations.code NOT IN ('GHS', 'EXH', 'SRC', 'REA', 'STF') 
  			  OR w_OPTION_ENCOURSMCOSUP = '1' 
  				  AND w_cti_encours_factures.ghs_id > 0
  				  AND t_prestations.code IN ('SRC', 'REA', 'STF'))
  			      AND (
              	      t_prestations.code NOT IN ('GMT', 'PJ','PII') 
              	      OR t_prestations.code IN ('PII') AND est_budget_global <> '1' 
             		  OR t_prestations.code IN ('GMT', 'PJ') AND type_t2a <> '1'  
             		  OR t_prestations.code IN ('GMT', 'PJ','PII') 
  					  AND est_budget_global = '1' 
  					  AND NOT EXISTS (
                  	  	  SELECT no_sejour 
                  	  	  FROM w_cti_encours_factures_lignes_c
                  	  	  	  JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                  	  	  WHERE 
                              t_prestations.code = 'GHS'
                  	  	  	  AND w_cti_encours_factures.no_sejour = w_cti_encours_factures_lignes_c.no_sejour
  				      )
  				  AND taux_1_bg IS DISTINCT FROM 100 
  			  OR t_prestations.code IN ('PII') 
  				  AND est_budget_global = '1' 
  				  AND w_cti_encours_factures.no_facture LIKE '%BG'
              )
          ;
          INSERT INTO w_cti_encours_factures_lignes_c(
            no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
            prestation_id, lpp_id, ucd_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
            prix_unitaire, montant_encours)
          SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'SAISIE' AS type_ligne, p_factures_lignes_c.date_debut, p_factures_lignes_c.date_fin, nb_rubrique, nb_rubrique, coefficient, 1,
            prestation_id, COALESCE(p_factures_lignes_c.lpp_id,0) AS lpp_id, COALESCE(p_factures_lignes_c.ucd_id,0) AS ucd_id, rubrique_facturation_id, rubrique_facturation_id,
            prix_unitaire, montant_facture
          FROM w_cti_encours_factures
            JOIN activite.p_factures_lignes_c ON w_cti_encours_factures.no_facture = p_factures_lignes_c.no_facture
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid
          WHERE t_prestations.code NOT IN ('GHS', 'EXH', 'SRC', 'REA', 'STF') AND
            montant_facture <> 0 AND 
            w_cti_encours_factures.date_fin <= w_date_traitement;
            
          -- En budget global, supprimer en cours GHS si 100% PJ facturé sur mutuelles ou patient ou tp1
          DELETE FROM w_cti_encours_factures_lignes_c
          USING
          (
          SELECT no_sejour,
            MAX(no_facture_bg) AS no_facture_bg,
            MAX(taux_mut) AS taux_mut
          FROM
          (
          SELECT p_factures.no_sejour, 
            NULL::text AS no_facture_bg,  
            MAX(taux_0+CASE WHEN montant_facture_1 <> 0 THEN taux_1 ELSE 0 END+taux_2) AS taux_mut
          FROM activite.p_factures
          JOIN activite.p_sejours on p_factures.no_sejour = p_sejours.no_sejour
          JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
          JOIN activite.t_prestations on prestation_id = t_prestations.oid 
          WHERE est_budget_global = '1' and t_prestations.code IN ('PJ') and
            p_factures.no_facture NOT LIKE '%BG' AND
            code_facture <> '0' AND
            (
              montant_facture_0 <> 0 OR
              montant_facture_1 <> 0 OR
              montant_facture_2 <> 0
            )
          GROUP BY 1
          HAVING MAX(taux_0+CASE WHEN montant_facture_1 <> 0 THEN taux_1 ELSE 0 END+taux_2) = 100 AND
            SUM(montant_facture_0+montant_facture_1+montant_facture_2) <> 0
          UNION
          SELECT p_factures.no_sejour, 
            MAX(p_factures.no_facture) AS no_facture_bg,  
            0 AS taux_mut
          FROM activite.p_factures
          JOIN activite.p_sejours on p_factures.no_sejour = p_sejours.no_sejour
          JOIN w_cti_encours_factures_lignes_c ON p_factures.no_facture = w_cti_encours_factures_lignes_c.no_facture
          JOIN activite.t_prestations on prestation_id = t_prestations.oid 
          WHERE est_budget_global = '1' and t_prestations.code IN ('GHS') and
            p_factures.no_facture LIKE '%BG' AND
            code_facture = '0' 
          GROUP BY 1
          ) subview
          GROUP BY 1
          HAVING MAX(no_facture_bg) IS NOT NULL AND
            MAX(taux_mut) = 100
          ) subview
          WHERE w_cti_encours_factures_lignes_c.no_facture = subview.no_facture_bg
  		;
  		
          -- En budget global, diminuer en cours GHS si 20% PJ facturé sur mutuelles ou patient
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours = montant_encours*(100-LEAST(taux_mut,20))/100,
            regle_texte = regle_texte || ' - TM facturé déduit'
          FROM
          (
          SELECT no_sejour,
            MAX(no_facture_bg) AS no_facture_bg,
            MAX(taux_mut) AS taux_mut
          FROM
          (
          SELECT p_factures.no_sejour, 
            NULL::text AS no_facture_bg,  
            MAX(taux_0+taux_2) AS taux_mut
          FROM activite.p_factures
          JOIN activite.p_sejours on p_factures.no_sejour = p_sejours.no_sejour
          JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
          JOIN activite.t_prestations on prestation_id = t_prestations.oid 
          WHERE est_budget_global = '1' and t_prestations.code IN ('PJ') and
            p_factures.no_facture NOT LIKE '%BG' AND
            code_facture <> '0' AND
            (
              montant_facture_0 <> 0 OR
              montant_facture_2 <> 0
            )
          GROUP BY 1
          HAVING MAX(taux_0+taux_2) <> 0 AND
            SUM(montant_facture_0+montant_facture_2) <> 0
          UNION
          SELECT p_factures.no_sejour, 
            MAX(p_factures.no_facture) AS no_facture_bg,  
            0 AS taux_mut
          FROM activite.p_factures
          JOIN activite.p_sejours on p_factures.no_sejour = p_sejours.no_sejour
          JOIN w_cti_encours_factures_lignes_c ON p_factures.no_facture = w_cti_encours_factures_lignes_c.no_facture
          JOIN activite.t_prestations on prestation_id = t_prestations.oid 
          WHERE est_budget_global = '1' and t_prestations.code IN ('GHS') and
            p_factures.no_facture LIKE '%BG' AND
            code_facture = '0' 
          GROUP BY 1
          ) subview
          GROUP BY 1
          HAVING MAX(no_facture_bg) IS NOT NULL AND
            MAX(taux_mut) <> 0
          ) subview
          WHERE w_cti_encours_factures_lignes_c.no_facture = subview.no_facture_bg
  		;
  		
          -- En budget global, diminuer en cours GHS de l'encours TM
          UPDATE w_cti_encours_factures_lignes_c
          SET montant_encours = montant_encours - montant_encours_tm,
            regle_texte = regle_texte || ' - TM moyen déduit'
          FROM
          (
            SELECT w_cti_encours_factures_lignes_c.no_sejour, 
              SUM(montant_encours) AS montant_encours_tm
            FROM w_cti_encours_factures_lignes_c
            JOIN activite.p_sejours on w_cti_encours_factures_lignes_c.no_sejour = p_sejours.no_sejour
          
            JOIN activite.t_prestations on prestation_id = t_prestations.oid 
            WHERE est_budget_global = '1' and 
              prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code IN ('PJ')) and
              w_cti_encours_factures_lignes_c.no_facture NOT LIKE '%BG' 
            GROUP BY 1
            HAVING SUM(montant_encours) > 0
            ORDER BY 1
            ) subview 
          WHERE w_cti_encours_factures_lignes_c. no_sejour = subview.no_sejour AND
            prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code IN ('GHS')) AND
            w_cti_encours_factures_lignes_c.no_facture LIKE '%BG'
          ;
  		
      -- Honoraires medecins salaries
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Honoraires medecins salaries'; 
  
          IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSMEDSAL' AND valeur = '1') THEN
  
            DROP TABLE IF EXISTS w_cti_encours_prestation_rubrique
            ;
            CREATE TEMP TABLE w_cti_encours_prestation_rubrique AS
            SELECT prestation_id, (MAX(Array[nb,rubrique_facturation_id]))[2]::bigint AS rubrique_facturation_id
            FROM
            (
            SELECT prestation_id, rubrique_facturation_id, count(*) AS nb
            FROM activite.p_factures_lignes_c
            WHERE montant_comptabilise > 0
            GROUP BY 1,2
            ORDER BY 1,2
            ) subview
            GROUP BY 1
            ;
  
            UPDATE activite.p_factures_lignes_non_facturees_h
            SET prix_unitaire = subview.prix_unitaire
            FROM
            (
                SELECT acte_id, activite_ccam, modificateur_ccam_1, modificateur_ccam_2, modificateur_ccam_3, modificateur_ccam_4,
              base.Cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
                FROM activite.p_factures_lignes_h
                WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
              montant_facture_1 > 0
                GROUP BY 1,2,3,4,5,6
                ) subview
                WHERE p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
              p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_1 = subview.modificateur_ccam_1 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_2 = subview.modificateur_ccam_2 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_3 = subview.modificateur_ccam_3 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_4 = subview.modificateur_ccam_4 AND
              p_factures_lignes_non_facturees_h.prix_unitaire = 0
            ;
  
            UPDATE activite.p_factures_lignes_non_facturees_h
            SET prix_unitaire = subview.prix_unitaire
            FROM
            (
                SELECT acte_id, activite_ccam,
              base.Cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
                FROM activite.p_factures_lignes_h
                WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
              montant_facture_1 > 0
                GROUP BY 1,2
            ) subview
            WHERE p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
              p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
              p_factures_lignes_non_facturees_h.prix_unitaire = 0
  
            ;
  
            INSERT INTO w_cti_encours_factures_lignes_c(
              no_sejour, no_facture, type_ligne, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, 
              prestation_id, rubrique_facturation_id, rubrique_comptabilisation_id, 
              prix_unitaire, montant_encours, regle_texte)
            SELECT w_cti_encours_factures.no_sejour, w_cti_encours_factures.no_facture, 'SAISIE' AS type_ligne, p_factures_lignes_non_facturees_h.date_debut, p_factures_lignes_non_facturees_h.date_fin, nb_rubrique, nb_rubrique, coefficient, 1,
              p_factures_lignes_non_facturees_h.prestation_id, w_cti_encours_prestation_rubrique.rubrique_facturation_id, w_cti_encours_prestation_rubrique.rubrique_facturation_id,
              prix_unitaire, round(nb_rubrique * coefficient * prix_unitaire,2), 'Honoraire salarié saisi'
            FROM w_cti_encours_factures
              JOIN activite.p_factures_lignes_non_facturees_h ON w_cti_encours_factures.no_facture = p_factures_lignes_non_facturees_h.no_facture
              JOIN activite.t_prestations ON p_factures_lignes_non_facturees_h.prestation_id = t_prestations.oid
              JOIN activite.t_medecins_administratifs ON medecin_facture_id = t_medecins_administratifs.oid
              JOIN w_cti_encours_prestation_rubrique ON p_factures_lignes_non_facturees_h.prestation_id = w_cti_encours_prestation_rubrique.prestation_id
            WHERE t_medecins_administratifs.est_medecin_salarie = 1 
            ;
  
          END IF;
          
            
          -- Réaffectation forfait journalier sur GHS
          RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Deduction FJ du GHS'; 
              UPDATE w_cti_encours_factures_lignes_c
              SET montant_encours = w_cti_encours_factures_lignes_c.montant_encours - mt_fjpas,
                regle_texte = regle_texte || ' - FJ Déduit'
              FROM
              (
              SELECT w_cti_encours_factures.no_facture, 
                SUM(CASE WHEN t_prestations.code = 'GHS' THEN 1 ELSE 0 END) AS nb_ghs, 
                MAX(CASE WHEN t_prestations.code = 'GHS' THEN w_cti_encours_factures_lignes_c.CTID ELSE NULL END) AS CTID_ghs,
                SUM(CASE WHEN t_prestations.code IN ('FJ','PAS') THEN montant_encours ELSE 0 END) AS mt_fjpas
              FROM w_cti_encours_factures_lignes_c
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              JOIN w_cti_encours_factures ON
                w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture
              WHERE w_cti_encours_factures.ghs_id > 0 AND
                type_ligne <> 'GHSBB' AND 
                type_ligne <> 'GHSBBM' AND 
                w_cti_encours_factures.no_facture NOT LIKE '%BG' AND
                t_prestations.code IN ('GHS','FJ', 'PAS')
              GROUP BY 1
              HAVING SUM(CASE WHEN t_prestations.code IN ('FJ','PAS') THEN montant_encours ELSE 0 END) <> 0 AND
                SUM(CASE WHEN t_prestations.code = 'GHS' THEN 1 ELSE 0 END) = 1
              ) subview
              WHERE w_cti_encours_factures_lignes_c.no_facture = subview.no_facture AND
                w_cti_encours_factures_lignes_c.CTID = subview.CTID_ghs
  	    	  ;
  
            --Déduction du FJ du GHS dans le cas où le PJ facturé et valorisé est à 0
              DROP TABLE IF EXISTS w_montant_fj_par_sejour
              ;
              CREATE TEMP TABLE w_montant_fj_par_sejour AS
              SELECT
                  p_sejours.no_sejour
                  ,SUM(CASE WHEN t_prestations.code LIKE 'FJ%'
                  THEN montant_facture_0 + montant_facture_2
                  ELSE 0 
                  END) as montant_fj
              FROM activite.p_sejours
              JOIN activite.p_factures ON p_sejours.no_sejour = p_factures.no_sejour
              JOIN activite.p_factures_lignes_c on p_factures.no_facture = p_factures_lignes_c.no_facture
              JOIN activite.t_prestations on p_factures_lignes_c.prestation_id = t_prestations.oid
              WHERE p_factures.no_facture NOT LIKE '%BG'
                  AND p_sejours.no_sejour IN (
                      SELECT DISTINCT(no_sejour) FROM w_cti_encours_factures_lignes_c
                  )
              GROUP BY p_sejours.no_sejour
              HAVING  
                  SUM(CASE WHEN t_prestations.code LIKE 'PJ%'
                      THEN montant_facture_0 + montant_facture_2 + p_factures_lignes_c.montant_encours
                      ELSE 0 END) = 0 AND
                  SUM(CASE WHEN t_prestations.code LIKE 'FJ%'
                    THEN montant_facture_0 + montant_facture_2
                    ELSE 0 END) <> 0
              ;
    
              UPDATE w_cti_encours_factures_lignes_c 
              SET
                  montant_encours = montant_encours - montant_fj
                  ,regle_texte = regle_texte || ' - FJ facturé déduit'
              FROM w_montant_fj_par_sejour
              WHERE w_cti_encours_factures_lignes_c.no_sejour = w_montant_fj_par_sejour.no_sejour 
                  AND w_cti_encours_factures_lignes_c.no_facture LIKE '%BG' 
                  AND prestation_id = (
                      SELECT oid 
  			  	  FROM activite.t_prestations 
  			  	  WHERE code = 'GHS'
                  )
              ;
      
          -- Réaffectation forfait journalier sur GMT
  		WITH factures_smr_avec_fj AS (
  			SELECT 
  	      		w_cti_encours_factures.no_facture
  	      		, MAX(CASE WHEN t_prestations.code = 'GMT' AND type_ligne = 'GMT' THEN prestation_id ELSE 0 END) AS prestation_gmt_id
  	      		, SUM(CASE WHEN t_prestations.code = 'FJ' THEN montant_encours ELSE 0 END) AS montant_fj_total
  	      		, SUM(CASE WHEN t_prestations.code = 'GMT' AND type_ligne = 'GMT' THEN 1 ELSE 0 END) AS nb_lignes_gmt
  			FROM w_cti_encours_factures_lignes_c
  	      		JOIN activite.t_prestations ON prestation_id = t_prestations.oid
  	      		JOIN w_cti_encours_factures ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture
  			WHERE w_cti_encours_factures.no_facture NOT LIKE '%BG'
  				AND t_prestations.code IN ('GMT','FJ')
  			GROUP BY 
  				w_cti_encours_factures.no_facture
  			HAVING SUM(CASE WHEN t_prestations.code = 'FJ' THEN montant_encours ELSE 0 END) <> 0
  				AND SUM(CASE WHEN t_prestations.code = 'GMT' AND type_ligne = 'GMT' THEN 1 ELSE 0 END) > 0
  	        ),
  	        montant_fj_ventile_par_jour AS (
  	        	SELECT 
  	        		no_facture
  	        		, prestation_gmt_id
  	        		, round(montant_fj_total / nb_lignes_gmt, 2) AS prix_unitaire_fj
  	        	FROM factures_smr_avec_fj
  	        )
   	        UPDATE w_cti_encours_factures_lignes_c
  	        SET 
  	        	montant_encours = w_cti_encours_factures_lignes_c.montant_encours - prix_unitaire_fj,
  	        	regle_texte = regle_texte || ' - FJ Déduit'
  	        FROM montant_fj_ventile_par_jour
  	        WHERE w_cti_encours_factures_lignes_c.no_facture = montant_fj_ventile_par_jour.no_facture
  	        	AND w_cti_encours_factures_lignes_c.prestation_id = montant_fj_ventile_par_jour.prestation_gmt_id 
  	        	AND w_cti_encours_factures_lignes_c.type_ligne = 'GMT'
             ;
    
        -- Pour la valorisation SMR, les lignes de rubrique de facturation TJP ne doivent pas être valorisées
            UPDATE w_cti_encours_factures_lignes_c
            SET montant_encours = 0
            FROM activite.t_rubriques_facturation
            WHERE w_cti_encours_factures_lignes_c.rubrique_facturation_id = t_rubriques_facturation.oid
                AND t_rubriques_facturation.code ILIKE 'TJP%'
                AND w_cti_encours_factures_lignes_c.montant_encours <> 0
            ;
  
      -- Factures à ignorer
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Factures ignorees'; 
          UPDATE w_cti_encours_factures 
          SET ignorer = '1'
          FROM activite.t_calcul_encours
          WHERE t_calcul_encours.no_facture = w_cti_encours_factures.no_facture AND
            t_calcul_encours.type_ligne = 'FACTURE' AND
            t_calcul_encours.ignorer = '1'
          ;
  
      -- Forcage par dossier et prestation
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Lignes forcees ou ignorees'; 
          -- Paramètres de génération
          UPDATE w_cti_encours_calcul_parametres_services_prestations
          SET type_ligne = 'PRESTA-' || 
              CASE 
              WHEN prestation_code IN ('SRC', 'REA', 'STF', 'AMD', 'AMF', 'IGM', 'IGP', 'APD', 'IMD', 'IMI', 'IPD', 'IVG', 'NN1', 'NN2', 'NN3', 'GHT') THEN 'PC'
              WHEN prestation_code IN ('CPC', 'SHO', 'CP') THEN 'PC'
              WHEN prestation_code IN ('D09', 'D11', 'D13', 'D13', 'D15', 'D16', 'DTP') THEN 'PC'
              WHEN prestation_code IN ('ATU','FPU') THEN 'PC'
              WHEN prestation_type_valorisation IN ('CP') THEN 'PC'
              WHEN prestation_code IN ('GMT', 'PJ', 'FJ', 'FJA', 'ENT', 'PMS') THEN 'PU'
              WHEN prestation_type_valorisation IN ('ENT') THEN 'PU'
              WHEN prestation_code IN ('SE1','SE2','SE3','SE4','SE5','SE6','SE7') THEN 'PU'
              WHEN prestation_type_valorisation = '*AVGJOUSER' THEN 'PU'
              ELSE '' END
          ;
  
          -- Initialisation coefficient et prix unitaire calcule
          UPDATE w_cti_encours_factures_lignes_c
          SET coefficient_calcule = w_cti_encours_factures_lignes_c.coefficient
          FROM activite.t_lieux, 
            w_cti_encours_calcul_parametres_services_prestations 
          WHERE 
            w_cti_encours_factures_lignes_c.lieu_id = t_lieux.oid AND
            t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
            w_cti_encours_factures_lignes_c.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
            w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
            w_cti_encours_calcul_parametres_services_prestations.type_ligne LIKE 'PRESTA%' AND 
            w_cti_encours_factures_lignes_c.coefficient_calcule = 0
            ;
  
          UPDATE w_cti_encours_factures_lignes_c
          SET prix_unitaire_calcule = w_cti_encours_factures_lignes_c.prix_unitaire
          FROM activite.t_lieux, 
            w_cti_encours_calcul_parametres_services_prestations 
          WHERE 
            w_cti_encours_factures_lignes_c.lieu_id = t_lieux.oid AND
            t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
            w_cti_encours_factures_lignes_c.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
            w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
            w_cti_encours_calcul_parametres_services_prestations.type_ligne LIKE 'PRESTA%' AND 
            w_cti_encours_factures_lignes_c.prix_unitaire_calcule = 0
            ;
  
          UPDATE w_cti_encours_factures_lignes_c SET
            coefficient = CASE WHEN t_calcul_encours.coefficient_is_force = '1' THEN t_calcul_encours.coefficient_force ELSE w_cti_encours_factures_lignes_c.coefficient END,
            prix_unitaire = CASE WHEN t_calcul_encours.prix_unitaire_is_force = '1' THEN t_calcul_encours.prix_unitaire_force ELSE w_cti_encours_factures_lignes_c.prix_unitaire END,
            ignorer = CASE WHEN t_calcul_encours.ignorer = '1' THEN '1' ELSE '0' END,
            regle_texte = CASE 
              WHEN t_calcul_encours.coefficient_is_force = '1' AND w_cti_encours_factures_lignes_c.regle_texte ILIKE 'COEFF%' THEN 'Coefficient forcé dans paramétrage facture : ' || t_calcul_encours.coefficient_force 
              WHEN t_calcul_encours.prix_unitaire_is_force = '1' AND w_cti_encours_factures_lignes_c.regle_texte ILIKE 'P.U.%' THEN 'P.U. forcé dans paramétrage facture : ' || t_calcul_encours.prix_unitaire_force 
              ELSE regle_texte END,
            montant_encours = 
              CASE WHEN t_calcul_encours.ignorer IS DISTINCT from '1' THEN
                CASE WHEN t_calcul_encours.coefficient_is_force = '1' THEN t_calcul_encours.coefficient_force ELSE w_cti_encours_factures_lignes_c.coefficient END *
                CASE WHEN t_calcul_encours.prix_unitaire_is_force = '1' THEN t_calcul_encours.prix_unitaire_force ELSE w_cti_encours_factures_lignes_c.prix_unitaire END *
                nb_prestation
              ELSE 0 END
          FROM activite.t_lieux, 
            w_cti_encours_calcul_parametres_services_prestations,
            activite.t_calcul_encours 
          WHERE 
            w_cti_encours_factures_lignes_c.lieu_id = t_lieux.oid AND
            t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
            t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
            w_cti_encours_factures_lignes_c.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
            w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
            w_cti_encours_calcul_parametres_services_prestations.type_ligne LIKE 'PRESTA%' AND
            
            t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
            t_calcul_encours.lieu_service_id = t_lieux.service_facturation_id AND
            t_calcul_encours.prestation_id = w_cti_encours_factures_lignes_c.prestation_id AND
            t_calcul_encours.rubrique_facturation_id = w_cti_encours_factures_lignes_c.rubrique_facturation_id AND
            t_calcul_encours.type_ligne LIKE 'PRESEJ%'  AND
            (
            t_calcul_encours.coefficient_is_force = '1' OR
            t_calcul_encours.prix_unitaire_is_force = '1' OR
            t_calcul_encours.ignorer = '1'
            )
          ;
  
          -- Ecriture du justificatif
          IF w_date_encours = w_date_encours_actuelle THEN
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Ecriture justificatif'; 
            TRUNCATE activite.p_facture_ligne_valorise_c;
  
            INSERT INTO activite.p_facture_ligne_valorise_c(
                no_facture, facture_id, date_debut, date_fin, lieu_id, nb_rubrique, 
                nb_prestation, coefficient, coefficient_mco, rubrique_facturation_id, 
                prestation_id, lpp_id, ucd_id, prix_unitaire, montant_encours, type_ligne_code, mode_calcul_code, 
                mode_calcul_texte)
  
            SELECT 
              w_cti_encours_factures.no_facture, 
              w_cti_encours_factures.oid,
              MIN(w_cti_encours_factures_lignes_c.date_debut), 
              MAX(w_cti_encours_factures_lignes_c.date_fin),
              CASE WHEN t_prestations.code LIKE 'GHS%' THEN w_cti_encours_factures.lieu_sortie_id ELSE w_cti_encours_factures_lignes_c.lieu_id END,
              SUM(nb_rubrique), 
              SUM(nb_prestation),
              coefficient, 
              coefficient_mco, 
              w_cti_encours_factures_lignes_c.rubrique_facturation_id,
              prestation_id,
              lpp_id, 
              ucd_id, 
              prix_unitaire, 
              SUM(CASE WHEN w_cti_encours_factures.ignorer IS DISTINCT FROM '1' AND w_cti_encours_factures_lignes_c.ignorer IS DISTINCT FROM '1' THEN montant_encours ELSE 0 END),
              w_cti_encours_factures_lignes_c.type_ligne,
              CASE 
                WHEN w_cti_encours_factures.ignorer = '1' AND w_cti_encours_factures_lignes_c.regle_ghs <> '' THEN '00-FORCE' 
                WHEN w_cti_encours_factures_lignes_c.ignorer = '1' AND w_cti_encours_factures_lignes_c.regle_ghs <> '' THEN '00-FORCE' 
                ELSE w_cti_encours_factures_lignes_c.regle_ghs END,
              CASE 
                WHEN w_cti_encours_factures.ignorer = '1' THEN 'FACTURE IGNOREE.' 
                WHEN w_cti_encours_factures_lignes_c.ignorer = '1' THEN 'LIGNE IGNOREE.' 
                ELSE w_cti_encours_factures_lignes_c.regle_texte END
            FROM w_cti_encours_factures_lignes_c
              JOIN w_cti_encours_factures ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture 
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid
            WHERE w_cti_encours_factures_lignes_c.rubrique_facturation_id IS NOT NULL AND 
              (montant_encours <> 0 OR
              w_cti_encours_factures_lignes_c.ignorer = '1' OR
              type_ligne = 'GHSECART'
              )
            GROUP BY 1,2,5,8,9,10,11,12,13,14,16,17,18
            ORDER BY 1;
  
            
            -- Stockage des paramètres de calcul
            INSERT INTO activite.t_calcul_encours 
            (
              type_ligne,
              coefficient_mco,
              lieu_service_id,
              lieu_unite_fonctionnelle_id,
              nb_ambulatoires,
              nb_externes,
              nb_seances,
              nb_journees,
              nb_journees_cp,
              prestation_id,
              prestation_type_valorisation,
              rubrique_facturation_id,
              nb_prestations_facturees,
              prix_unitaire_calcule,
              coefficient_calcule
            )
            SELECT 
              w_cti_encours_calcul_parametres_services_prestations.type_ligne,
              w_cti_encours_calcul_parametres_services_prestations.coefficient_mco,
              w_cti_encours_calcul_parametres_services_prestations.lieu_service_id,
              w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id,
              w_cti_encours_calcul_parametres_services_prestations.nb_ambulatoires,
              w_cti_encours_calcul_parametres_services_prestations.nb_externes,
              w_cti_encours_calcul_parametres_services_prestations.nb_seances,
              w_cti_encours_calcul_parametres_services_prestations.nb_journees,
              w_cti_encours_calcul_parametres_services_prestations.nb_journees_cp,
              w_cti_encours_calcul_parametres_services_prestations.prestation_id,
              w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation,
              w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id,
              w_cti_encours_calcul_parametres_services_prestations.nombre AS nb_prestations_facturees,
              w_cti_encours_calcul_parametres_services_prestations.prix_unitaire_calcule,
              w_cti_encours_calcul_parametres_services_prestations.coefficient_calcule
            FROM w_cti_encours_calcul_parametres_services_prestations
            LEFT JOIN activite.t_calcul_encours ON
              t_calcul_encours.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_calcul_encours.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              t_calcul_encours.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'PRESTA%'
            WHERE t_calcul_encours.oid IS NULL
            ;
  
            UPDATE activite.t_calcul_encours SET
              type_ligne = w_cti_encours_calcul_parametres_services_prestations.type_ligne,
              nb_ambulatoires = w_cti_encours_calcul_parametres_services_prestations.nb_ambulatoires,
              nb_externes = w_cti_encours_calcul_parametres_services_prestations.nb_externes,
              nb_seances = w_cti_encours_calcul_parametres_services_prestations.nb_seances,
              nb_journees = w_cti_encours_calcul_parametres_services_prestations.nb_journees,
              nb_journees_cp = w_cti_encours_calcul_parametres_services_prestations.nb_journees_cp,
              prestation_type_valorisation = w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation,
              nb_prestations_facturees = w_cti_encours_calcul_parametres_services_prestations.nombre,
              prix_unitaire_calcule = w_cti_encours_calcul_parametres_services_prestations.prix_unitaire_calcule,
              coefficient_calcule = w_cti_encours_calcul_parametres_services_prestations.coefficient_calcule
            FROM w_cti_encours_calcul_parametres_services_prestations
            WHERE t_calcul_encours.lieu_service_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_calcul_encours.lieu_unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              t_calcul_encours.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'PRESTA%' AND
              (
              t_calcul_encours.type_ligne IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.type_ligne OR
              t_calcul_encours.nb_ambulatoires IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nb_ambulatoires OR
              t_calcul_encours.nb_externes IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nb_externes OR
              t_calcul_encours.nb_seances IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nb_seances OR
              t_calcul_encours.nb_journees IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nb_journees OR
              t_calcul_encours.nb_journees_cp IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nb_journees_cp OR
              t_calcul_encours.prestation_type_valorisation IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.prestation_type_valorisation OR
              t_calcul_encours.nb_prestations_facturees IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.nombre OR
              t_calcul_encours.prix_unitaire_calcule IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.prix_unitaire_calcule OR
              t_calcul_encours.coefficient_calcule IS DISTINCT FROM w_cti_encours_calcul_parametres_services_prestations.coefficient_calcule
              )
            ;
  
            -- Stockage des données de calcul par séjour (GHS)
            
            INSERT INTO activite.t_calcul_encours 
            (
              type_ligne,
              no_sejour,
              no_facture,
              coefficient_mco,
              lieu_service_id,
              lieu_unite_fonctionnelle_id,
              nb_ambulatoires,
              nb_externes,
              nb_seances,
              nb_journees,
              nb_journees_cp,
              prestation_id,
              prestation_type_valorisation,
              rubrique_facturation_id,
              nb_prestations_facturees,
              prix_unitaire_calcule,
              coefficient_calcule
            )
            SELECT 
              w_cti_encours_factures_lignes_c.type_ligne,
              w_cti_encours_factures_lignes_c.no_sejour,
              w_cti_encours_factures_lignes_c.no_facture,
              w_cti_encours_factures_lignes_c.coefficient_mco,
              t_lieux.service_facturation_id AS lieu_service_id,
              t_lieux.unite_fonctionnelle_id AS lieu_unite_fonctionnelle_id,
              0::numeric AS nb_ambulatoires,
              0::numeric AS nb_externes,
              0::numeric AS nb_seances,
              0::numeric AS nb_journees,
              0::numeric AS nb_journees_cp,
              w_cti_encours_factures_lignes_c.prestation_id,
              w_cti_encours_factures_lignes_c.regle_ghs AS prestation_type_valorisation,
              w_cti_encours_factures_lignes_c.rubrique_facturation_id,
              w_cti_encours_factures_lignes_c.nb_prestation AS nb_prestations_facturees,
              w_cti_encours_factures_lignes_c.prix_unitaire_calcule,
              0::numeric AS coefficient_calcule
            FROM w_cti_encours_factures_lignes_c
            JOIN activite.t_lieux ON lieu_id = t_lieux.oid
            LEFT JOIN activite.t_calcul_encours ON
              t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
              t_calcul_encours.prestation_id = w_cti_encours_factures_lignes_c.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_factures_lignes_c.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'GHSNG%'
            WHERE w_cti_encours_factures_lignes_c.type_ligne = 'GHSNG' AND
              t_calcul_encours.no_facture IS NULL
            ;
  
            UPDATE activite.t_calcul_encours SET
              type_ligne = w_cti_encours_factures_lignes_c.type_ligne,
              prix_unitaire_calcule = w_cti_encours_factures_lignes_c.prix_unitaire_calcule
            FROM w_cti_encours_factures_lignes_c
            WHERE t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
              t_calcul_encours.prestation_id = w_cti_encours_factures_lignes_c.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_factures_lignes_c.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'GHSNG%' AND
              (
              t_calcul_encours.type_ligne IS DISTINCT FROM w_cti_encours_factures_lignes_c.type_ligne OR
              t_calcul_encours.prix_unitaire_calcule IS DISTINCT FROM w_cti_encours_factures_lignes_c.prix_unitaire_calcule
              )
            ; 
  
            DELETE FROM activite.t_calcul_encours
            WHERE type_ligne = 'GHSNG' AND
              no_facture NOT IN (SELECT no_facture FROM w_cti_encours_factures_lignes_c WHERE w_cti_encours_factures_lignes_c.type_ligne = 'GHSNG')
            ;
  
            -- Stockage des séjours calculés (prestations)
  
            INSERT INTO activite.t_calcul_encours 
            (
              type_ligne,
              no_sejour,
              no_facture,
              coefficient_mco,
              lieu_service_id,
              lieu_unite_fonctionnelle_id,
              nb_ambulatoires,
              nb_externes,
              nb_seances,
              nb_journees,
              nb_journees_cp,
              prestation_id,
              prestation_type_valorisation,
              rubrique_facturation_id,
              nb_prestations_facturees,
              prix_unitaire_calcule,
              coefficient_calcule
            )
            SELECT 
              replace(w_cti_encours_calcul_parametres_services_prestations.type_ligne,'PRESTA','PRESEJ') AS type_ligne,
              w_cti_encours_factures_lignes_c.no_sejour,
              w_cti_encours_factures_lignes_c.no_facture,
              w_cti_encours_factures_lignes_c.coefficient_mco,
              t_lieux.service_facturation_id AS lieu_service_id,
              t_lieux.unite_fonctionnelle_id AS lieu_unite_fonctionnelle_id,
              0::numeric AS nb_ambulatoires,
              0::numeric AS nb_externes,
              0::numeric AS nb_seances,
              0::numeric AS nb_journees,
              0::numeric AS nb_journees_cp,
              w_cti_encours_factures_lignes_c.prestation_id,
              w_cti_encours_factures_lignes_c.regle_ghs AS prestation_type_valorisation,
              w_cti_encours_factures_lignes_c.rubrique_facturation_id,
              SUM(w_cti_encours_factures_lignes_c.nb_prestation) AS nb_prestations_facturees,
              w_cti_encours_factures_lignes_c.prix_unitaire_calcule,
              w_cti_encours_factures_lignes_c.coefficient_calcule
            FROM w_cti_encours_factures_lignes_c
            JOIN activite.t_lieux ON lieu_id = t_lieux.oid
            JOIN w_cti_encours_calcul_parametres_services_prestations ON 
              t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
              t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
              w_cti_encours_factures_lignes_c.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
              w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id
            LEFT JOIN activite.t_calcul_encours ON
              t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
              t_calcul_encours.lieu_service_id = t_lieux.service_facturation_id AND
              t_calcul_encours.prestation_id = w_cti_encours_factures_lignes_c.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_factures_lignes_c.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'PRESEJ%' 
            WHERE w_cti_encours_factures_lignes_c.type_ligne <> 'SAISIE' AND
              w_cti_encours_calcul_parametres_services_prestations.type_ligne LIKE 'PRESTA%' AND
              t_calcul_encours.no_facture IS NULL
            GROUP BY 1,2,3,4,5,6,12,13,14,16,17
            ;
  
            UPDATE activite.t_calcul_encours SET 
              coefficient_calcule = w_cti_encours_factures_lignes_c.coefficient_calcule,
              prix_unitaire_calcule = w_cti_encours_factures_lignes_c.prix_unitaire_calcule
            FROM w_cti_encours_factures_lignes_c
            JOIN activite.t_lieux ON lieu_id = t_lieux.oid
            WHERE t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
              t_calcul_encours.lieu_service_id = t_lieux.service_facturation_id AND
              t_calcul_encours.prestation_id = w_cti_encours_factures_lignes_c.prestation_id AND
              t_calcul_encours.rubrique_facturation_id = w_cti_encours_factures_lignes_c.rubrique_facturation_id AND
              t_calcul_encours.type_ligne LIKE 'PRESEJ%' AND
              (
              t_calcul_encours.coefficient_calcule IS DISTINCT FROM w_cti_encours_factures_lignes_c.coefficient OR
              t_calcul_encours.prix_unitaire_calcule IS DISTINCT FROM w_cti_encours_factures_lignes_c.prix_unitaire
              )
            ;
  
            DELETE
            FROM activite.t_calcul_encours
            WHERE t_calcul_encours.type_ligne LIKE 'PRESEJ%' AND
              (
              t_calcul_encours.no_facture || '-' ||
              t_calcul_encours.lieu_service_id || '-' ||
              t_calcul_encours.prestation_id || '-' ||
              t_calcul_encours.rubrique_facturation_id
              ) NOT IN
              (SELECT
                w_cti_encours_factures_lignes_c.no_facture || '-' ||
                t_lieux.service_facturation_id || '-' ||
                w_cti_encours_factures_lignes_c.prestation_id || '-' ||
                w_cti_encours_factures_lignes_c.rubrique_facturation_id
              FROM w_cti_encours_factures_lignes_c
              JOIN activite.t_lieux ON lieu_id = t_lieux.oid
              JOIN w_cti_encours_calcul_parametres_services_prestations ON 
                t_lieux.service_facturation_id = w_cti_encours_calcul_parametres_services_prestations.lieu_service_id AND
                t_lieux.unite_fonctionnelle_id = w_cti_encours_calcul_parametres_services_prestations.lieu_unite_fonctionnelle_id AND
                w_cti_encours_factures_lignes_c.prestation_id = w_cti_encours_calcul_parametres_services_prestations.prestation_id AND
                w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_calcul_parametres_services_prestations.rubrique_facturation_id
              WHERE w_cti_encours_factures_lignes_c.type_ligne <> 'SAISIE' AND
                w_cti_encours_calcul_parametres_services_prestations.type_ligne LIKE 'PRESTA%'
              )
            ;
  
            
            -- Stockage des séjours calculés (pour paramétrer séjours à ne pas calculer)
            INSERT INTO activite.t_calcul_encours 
            (
              type_ligne,
              no_sejour,
              no_facture,
              coefficient_mco,
              lieu_service_id,
              lieu_unite_fonctionnelle_id,
              nb_ambulatoires,
              nb_externes,
              nb_seances,
              nb_journees,
              nb_journees_cp,
              prestation_id,
              prestation_type_valorisation,
              rubrique_facturation_id,
              nb_prestations_facturees,
              prix_unitaire_calcule,
              coefficient_calcule
            )
            SELECT 
              'FACTURE'::text,
              w_cti_encours_factures_lignes_c.no_sejour,
              w_cti_encours_factures_lignes_c.no_facture,
              0::numeric AS coefficient_mco,
              0::bigint AS lieu_service_id,
              0::bigint AS lieu_unite_fonctionnelle_id,
              0::numeric AS nb_ambulatoires,
              0::numeric AS nb_externes,
              0::numeric AS nb_seances,
              0::numeric AS nb_journees,
              0::numeric AS nb_journees_cp,
              0::bigint AS prestation_id,
              0::bigint AS prestation_type_valorisation,
              0::bigint AS rubrique_facturation_id,
              0::bigint AS nb_prestation,
              SUM(montant_encours) AS prix_unitaire_calcule,
              0::numeric AS coefficient_calcule
            FROM w_cti_encours_factures_lignes_c
            LEFT JOIN activite.t_calcul_encours ON
              t_calcul_encours.no_facture = w_cti_encours_factures_lignes_c.no_facture AND
              t_calcul_encours.type_ligne LIKE 'FACTURE%'
            WHERE t_calcul_encours.no_facture IS NULL
            GROUP BY 2,3
            ;
  
            DELETE FROM activite.t_calcul_encours
            WHERE type_ligne = 'FACTURE' AND
              no_facture NOT IN (SELECT no_facture FROM w_cti_encours_factures_lignes_c)
            ;
  
          END IF;
          -- Eclatement des prestations jour par jour
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Eclatement jour par jour'; 
          INSERT INTO w_cti_encours_factures_lignes_sup_c
          SELECT
            w_cti_encours_factures_lignes_c.oid AS from_oid,
            t_prestations.code AS prestation_code,
            date(p_sejours.date_entree) AS date_debut_ghs,
            date(date_fin - interval '1 day') AS date_fin_ghs,
            (date(date_fin) - date(date_entree)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
            w_cti_encours_factures_lignes_c.*
          FROM w_cti_encours_factures_lignes_c
            JOIN activite.p_sejours ON w_cti_encours_factures_lignes_c.no_sejour = p_sejours.no_sejour
            JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code IN ('GMT', 'PJ', 'FJ', 'PHJ','SSM', 'GHS', 'GHT', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') 
          WHERE type_sejour = '1' AND (nb_prestation > 1 or nb_prestation < -1 OR (t_prestations.code = 'GHS' AND date(date_fin) - date(date_entree) > 1 )) ;
          UPDATE w_cti_encours_factures_lignes_sup_c SET 
            date_fin_ghs = date(date_debut_exh - interval '1 day'),
            nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
          FROM (
            SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
            FROM w_cti_encours_factures_lignes_c
              JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
            GROUP BY 1) subview
          WHERE w_cti_encours_factures_lignes_sup_c.no_facture = subview.no_facture ;
          
          INSERT INTO w_cti_encours_factures_lignes_sup_c_gen
          SELECT
            from_oid,
            no_sejour,
            no_facture,
            date AS date_debut,
            date AS date_fin,
            lieu_id,
            rubrique_facturation_id,
            rubrique_comptabilisation_id,
            prestation_id,
            lpp_id, 
            ucd_id, 
            CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs AND t_rubriques_facturation.code = '111' THEN 1 WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
            CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
            coefficient,
            coefficient_mco,
            prix_unitaire,
            w_cti_encours_factures_lignes_sup_c.oid,
            round(montant_encours / ABS(CASE WHEN prestation_code <> 'GHS' THEN nb_prestation ELSE nb_prestation_ghs END),2) AS montant_encours,
            type_ligne,
            regle_ghs,
            regle_coefficient,
            regle_texte
          FROM w_cti_encours_factures_lignes_sup_c
            JOIN base.p_calendrier ON date_debut BETWEEN p_calendrier.date - ABS(CASE WHEN prestation_code <> 'GHS' THEN nb_prestation ELSE nb_prestation_ghs END)::integer + 1 AND p_calendrier.date AND 
                  p_calendrier.date <> date_debut 
            JOIN activite.t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid;
  
          
          INSERT INTO w_cti_encours_factures_lignes_sup_c_gen_tot
          SELECT from_oid,
            SUM(nb_rubrique) AS nb_rubrique,
            SUM(nb_prestation) AS nb_prestation,
            SUM(montant_encours) AS montant_encours
          FROM w_cti_encours_factures_lignes_sup_c_gen
          GROUP BY 1;
          UPDATE w_cti_encours_factures_lignes_c
          SET
            date_fin = w_cti_encours_factures_lignes_c.date_debut,
            nb_rubrique = w_cti_encours_factures_lignes_c.nb_rubrique - w_cti_encours_factures_lignes_sup_c_gen_tot.nb_rubrique,
            nb_prestation = w_cti_encours_factures_lignes_c.nb_prestation - w_cti_encours_factures_lignes_sup_c_gen_tot.nb_prestation,
            montant_encours = w_cti_encours_factures_lignes_c.montant_encours - w_cti_encours_factures_lignes_sup_c_gen_tot.montant_encours
          FROM w_cti_encours_factures_lignes_sup_c_gen_tot
          WHERE w_cti_encours_factures_lignes_c.oid = from_oid;
          UPDATE w_cti_encours_factures_lignes_c
          SET
            nb_rubrique = nb_prestation
          FROM activite.t_rubriques_facturation, activite.t_prestations
          WHERE w_cti_encours_factures_lignes_c.prestation_id = t_prestations.oid AND t_prestations.code = 'GHS' AND
            w_cti_encours_factures_lignes_c.rubrique_facturation_id = t_rubriques_facturation.oid AND t_rubriques_facturation.code <> '111';
          INSERT INTO w_cti_encours_factures_lignes_c (
            no_sejour,
            no_facture,
            date_debut,
            date_fin,
            nb_rubrique,
            coefficient,
            coefficient_mco,
            prestation_id,
            lpp_id, 
            ucd_id, 
            rubrique_facturation_id,
            rubrique_comptabilisation_id,
            prix_unitaire,
            nb_prestation,
            montant_encours,
            type_ligne,
            regle_ghs,
            lieu_id,
            regle_coefficient,
            regle_texte)
          SELECT
            no_sejour,
            no_facture,
            date_debut,
            date_fin,
            nb_rubrique,
            coefficient,
            coefficient_mco,
            prestation_id,
            lpp_id, 
            ucd_id, 
            rubrique_facturation_id,
            rubrique_comptabilisation_id,
            prix_unitaire,
            nb_prestation,
            montant_encours,
            type_ligne,
            regle_ghs,
            lieu_id,
            regle_coefficient,
            regle_texte
          FROM w_cti_encours_factures_lignes_sup_c_gen;
          -- sur ambulatoires avec une nuit,
    
          UPDATE w_cti_encours_factures_lignes_c
          SET date_fin = date_debut 
          WHERE prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code = 'GHS') AND
            nb_rubrique = 1 AND
            date_fin - date_debut = 1;
                  
          
          -- Lieu
          UPDATE w_cti_encours_factures_lignes_c
          SET lieu_id = p_mouvements_sejour.lieu_id
          FROM 
            activite.p_factures, 
            activite.p_mouvements_sejour
          WHERE
            w_cti_encours_factures_lignes_c.no_facture = p_factures.no_facture AND
            p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
            w_cti_encours_factures_lignes_c.date_fin = p_mouvements_sejour.date AND
            (230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
            nb_entrees_directes = 1 AND heure_fin = 240000 OR 
            nb_sorties_directes = 1 ) AND 
            p_mouvements_sejour.lieu_id IS DISTINCT FROM w_cti_encours_factures_lignes_c.lieu_id;
          
          UPDATE w_cti_encours_factures_lignes_c
          SET lieu_id = p_sejours.lieu_sortie_id
          FROM activite.p_sejours
          WHERE w_cti_encours_factures_lignes_c.no_sejour = p_sejours.no_sejour
            AND (lieu_id = 0 OR lieu_id is null);
  
          -- Lieu des lignes de factures (en tenant compte des absences) 
          DROP TABLE IF EXISTS w_mouvements_sejour_lieu_jour;
          CREATE TEMP TABLE w_mouvements_sejour_lieu_jour AS
          SELECT no_sejour, 
              date,
              (MAX(CASE WHEN est_absence <> '1' THEN Array[heure_fin, lieu_id] ELSE NULL END))[2] AS lieu_id,
              (MAX(Array[heure_fin, lieu_id]))[2] AS lieu_id_avec_absence
          FROM activite.p_mouvements_sejour
          JOIN activite.t_lieux ON lieu_id = t_lieux.oid
          JOIN activite.t_services_facturation On service_facturation_id = t_services_facturation.oid
          WHERE p_mouvements_sejour.no_sejour IN (SELECT no_sejour FROM w_cti_encours_factures_lignes_c )
          GROUP BY 1,2
          HAVING MAX(est_absence) = '1'
          ;
  
          UPDATE w_cti_encours_factures_lignes_c
              SET lieu_id = COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
              FROM w_mouvements_sejour_lieu_jour
              WHERE w_cti_encours_factures_lignes_c.no_sejour = w_mouvements_sejour_lieu_jour.no_sejour AND
                w_cti_encours_factures_lignes_c.date_fin = w_mouvements_sejour_lieu_jour.date AND
                w_cti_encours_factures_lignes_c.lieu_id <> COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
          ;
  
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Reaffectation prestation TDE sur budget global'; 
          DROP TABLE IF EXISTS w_factures_e;
          CREATE TEMP TABLE w_factures_e AS
          SELECT p_factures.no_sejour,
            p_factures_bg.no_facture AS no_facture_bg,
            p_factures.no_facture AS no_facture_nbg
          FROM w_cti_encours_factures p_factures
          JOIN w_cti_encours_factures p_factures_bg ON p_factures_bg.no_sejour = p_factures.no_sejour AND p_factures_bg.no_facture LIKE '%BG'
          WHERE p_factures.no_facture NOT LIKE '%BG' 
          ;
  
          ANALYSE w_factures_e
          ;
  
          UPDATE w_cti_encours_factures_lignes_c p_factures_lignes_c
          SET no_facture = no_facture_bg
          FROM w_factures_e, activite.t_prestations
          WHERE p_factures_lignes_c.no_facture = no_facture_nbg AND
            prestation_id = t_prestations.oid AND
            t_prestations.code LIKE 'TDE%' 
          ;
    
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Repartition par tiers payant'; 
          UPDATE w_cti_encours_factures_lignes_c SET
            montant_encours_1 = CASE WHEN tiers_payant_1_id <> 0 THEN round(montant_encours * coeff_1,2) ELSE 0 END,
            montant_encours_2 = CASE WHEN tiers_payant_2_id <> 0 THEN round(montant_encours * coeff_2,2) ELSE 0 END,
            montant_encours_0 = montant_encours - CASE WHEN tiers_payant_1_id <> 0 THEN round(montant_encours * coeff_1,2) ELSE 0 END
                    - CASE WHEN tiers_payant_2_id <> 0 THEN round(montant_encours * coeff_2,2) ELSE 0 END
          FROM w_cti_encours_factures, w_cti_encours_repartition_tp
          WHERE w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
            w_cti_encours_factures_lignes_c.rubrique_facturation_id = w_cti_encours_repartition_tp.rubrique_facturation_id;
          UPDATE w_cti_encours_factures SET
            regle_ghs = COALESCE(subview.regle_ghs,'0'),
            montant_valorise_c = COALESCE(subview.montant_valorise,0),
            montant_valorise_0_c = COALESCE(subview.montant_valorise_0,0),
            montant_valorise_1_c = COALESCE(subview.montant_valorise_1,0),
            montant_valorise_2_c = COALESCE(subview.montant_valorise_2,0),
            montant_encours_c = COALESCE(subview.montant_encours,0),
            montant_encours_0_c = COALESCE(subview.montant_encours_0,0),
            montant_encours_1_c = COALESCE(subview.montant_encours_1,0),
            montant_encours_2_c = COALESCE(subview.montant_encours_2,0),
            etat = ''
          FROM 
            (SELECT w_cti_encours_factures.no_facture, 
              MAX(w_cti_encours_factures_lignes_c.regle_ghs) AS regle_ghs,
              SUM(montant_encours) AS montant_valorise, 
              SUM(montant_encours_0) AS montant_valorise_0, 
              SUM(montant_encours_1) AS montant_valorise_1, 
              SUM(montant_encours_2) AS montant_valorise_2, 
              SUM(CASE WHEN w_cti_encours_factures_lignes_c.date_fin <= w_cti_encours_factures.date_encours THEN montant_encours ELSE 0 END) AS montant_encours, 
              SUM(CASE WHEN w_cti_encours_factures_lignes_c.date_fin <= w_cti_encours_factures.date_encours THEN montant_encours_0 ELSE 0 END) AS montant_encours_0, 
              SUM(CASE WHEN w_cti_encours_factures_lignes_c.date_fin <= w_cti_encours_factures.date_encours THEN montant_encours_1 ELSE 0 END) AS montant_encours_1, 
              SUM(CASE WHEN w_cti_encours_factures_lignes_c.date_fin <= w_cti_encours_factures.date_encours THEN montant_encours_2 ELSE 0 END) AS montant_encours_2
            FROM w_cti_encours_factures
              LEFT JOIN w_cti_encours_factures_lignes_c ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture AND
                w_cti_encours_factures_lignes_c.ignorer IS DISTINCT FROM '1'
            WHERE w_cti_encours_factures.ignorer IS DISTINCT FROM '1'
            GROUP BY 1
            ) subview 
          WHERE subview.no_facture = w_cti_encours_factures.no_facture;
      
      -- Génération encours
      
      IF w_date_encours = w_date_encours_actuelle THEN
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Generation valorisation non factures'; 
            DELETE FROM activite.p_factures_lignes_c WHERE montant_encours <> 0;
            DELETE FROM activite.p_factures_lignes_h WHERE montant_encours <> 0;
  
            DELETE 
            FROM activite.p_factures_lignes_c 
            WHERE montant_encours = 0 AND 
              montant_facture = 0 AND 
              montant_comptabilise = 0 AND
              no_facture IN (SELECT no_facture FROM w_cti_encours_factures_lignes_c)
            ;
  
            DELETE
            FROM activite.p_factures_lignes_c
            USING activite.p_factures
            WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
              p_factures.montant_encours_c <> 0
            ;
            DELETE
            FROM activite.p_factures_lignes_h
            USING activite.p_factures
            WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
              p_factures.montant_encours_c <> 0
            ;
            
            UPDATE activite.p_factures SET 
              montant_encours_c = 0,
              montant_encours_0_c = 0,
              montant_encours_1_c = 0,
              montant_encours_2_c = 0,
              montant_encours_22_c = 0,
              montant_encours_h = 0,
              montant_encours_0_h = 0,
              montant_encours_1_h = 0,
              montant_encours_2_h = 0,
              montant_encours_22_h = 0
            WHERE montant_encours_c <> 0 OR montant_encours_h <> 0;
            
            INSERT INTO activite.p_factures_lignes_c(
              facture_id, no_facture, date_debut, date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, prix_unitaire, 
              prestation_id, lpp_id, ucd_id, rubrique_facturation_id, rubrique_comptabilisation_id, lieu_id, 
              montant_facture, montant_facture_0, montant_facture_1, montant_facture_2, montant_facture_22, 
              taux_0, taux_1, taux_2, taux_22, 
              montant_comptabilise, montant_comptabilise_0, montant_comptabilise_1, montant_comptabilise_2, montant_comptabilise_22, 
              montant_encours, montant_encours_1, montant_encours_2, montant_encours_0)
            SELECT 
              w_cti_encours_factures.oid, w_cti_encours_factures.no_facture, w_cti_encours_factures_lignes_c.date_debut, w_cti_encours_factures_lignes_c.date_fin, nb_rubrique, nb_prestation, coefficient, coefficient_mco, prix_unitaire, 
              prestation_id, lpp_id, ucd_id, w_cti_encours_factures_lignes_c.rubrique_facturation_id, rubrique_comptabilisation_id, lieu_id,
              0, 0, 0, 0, 0,
              0, 0, 0, 0, 
              0, 0, 0, 0, 0,
              montant_encours,
              montant_encours_1,
              montant_encours_2,
              montant_encours_0
            FROM w_cti_encours_factures_lignes_c
              JOIN w_cti_encours_factures ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture
            WHERE w_cti_encours_factures_lignes_c.rubrique_facturation_id IS NOT NULL AND 
              w_cti_encours_factures.ignorer IS DISTINCT FROM '1' AND
              w_cti_encours_factures_lignes_c.ignorer IS DISTINCT FROM '1' AND
              type_ligne <> 'GHSECART';
              
            UPDATE activite.p_factures SET
              tiers_payant_1_id = w_cti_encours_factures.tiers_payant_1_id,
              tiers_payant_2_id = w_cti_encours_factures.tiers_payant_2_id,
              montant_encours_c = w_cti_encours_factures.montant_valorise_c,
              montant_encours_1_c = w_cti_encours_factures.montant_valorise_1_c,
              montant_encours_2_c = w_cti_encours_factures.montant_valorise_2_c,
              montant_encours_0_c = w_cti_encours_factures.montant_valorise_0_c
            FROM w_cti_encours_factures
            WHERE w_cti_encours_factures.no_facture = p_factures.no_facture AND
              w_cti_encours_factures.ignorer <> '1';
  
              
            UPDATE activite.p_factures_lignes_non_facturees_h
            SET prix_unitaire = subview.prix_unitaire
            FROM
            (
                                              SELECT acte_id, activite_ccam, modificateur_ccam_1, modificateur_ccam_2, modificateur_ccam_3, modificateur_ccam_4,
              base.Cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
            FROM activite.p_factures_lignes_h
            WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
              montant_facture_1 > 0
            GROUP BY 1,2,3,4,5,6
            ) subview
            WHERE p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
              p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_1 = subview.modificateur_ccam_1 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_2 = subview.modificateur_ccam_2 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_3 = subview.modificateur_ccam_3 AND
              p_factures_lignes_non_facturees_h.modificateur_ccam_4 = subview.modificateur_ccam_4 AND
              p_factures_lignes_non_facturees_h.prix_unitaire = 0
            ;
  
            UPDATE activite.p_factures_lignes_non_facturees_h
            SET prix_unitaire = subview.prix_unitaire
            FROM
            (
                                              SELECT acte_id, activite_ccam,
              base.Cti_division(SUM(montant_facture_1),SUM(nb_prestation*coefficient)) AS prix_unitaire
            FROM activite.p_factures_lignes_h
            WHERE acte_id IN (SELECT acte_id FROM activite.p_factures_lignes_non_facturees_h WHERE prix_unitaire = 0) AND
              montant_facture_1 > 0
            GROUP BY 1,2
            ) subview
            WHERE p_factures_lignes_non_facturees_h.acte_id = subview.acte_id AND
              p_factures_lignes_non_facturees_h.activite_ccam = subview.activite_ccam AND
              p_factures_lignes_non_facturees_h.prix_unitaire = 0
  
            ;
  
            INSERT INTO activite.p_factures_lignes_h (
              no_facture,
              facture_id,
              date_debut,
              heure_debut,
              date_fin,
              coefficient,
              coefficient_mco,
              lieu_id,
              prestation_id,
              rubrique_facturation_id,
              rubrique_comptabilisation_id,
              acte_id,
              phase_ccam,
              activite_ccam,
              extension_ccam,
              modificateur_ccam_1,
              modificateur_ccam_2,
              modificateur_ccam_3,
              modificateur_ccam_4,
              medecin_facture_id,
              medecin_comptabilise_id,
              nb_rubrique,
              nb_prestation,
              prix_unitaire,
              taux_0,
              taux_1,
              taux_2,
              taux_22,
              montant_facture,
              montant_facture_0,
              montant_facture_1,
              montant_facture_2,
              montant_facture_22,
              montant_comptabilise,
              montant_comptabilise_0,
              montant_comptabilise_1,
              montant_comptabilise_2,
              montant_comptabilise_22,
              montant_depassement,
              montant_encours,
              montant_encours_0,
              montant_encours_1,
              montant_encours_2,
              montant_encours_22,
              montant_non_facture
            )
            SELECT 
              w_cti_encours_factures.no_facture,
              w_cti_encours_factures.oid AS facture_id,
              p_factures_lignes_non_facturees_h.date_debut,
              p_factures_lignes_non_facturees_h.heure_debut,
              p_factures_lignes_non_facturees_h.date_fin,
              p_factures_lignes_non_facturees_h.coefficient,
              1::numeric AS coefficient_mco,
              w_cti_encours_factures.lieu_sortie_id AS lieu_id,
              p_factures_lignes_non_facturees_h.prestation_id,
              0::bigint AS rubrique_facturation_id,
              0::bigint AS rubrique_comptabilisation_id,
              p_factures_lignes_non_facturees_h.acte_id,
              p_factures_lignes_non_facturees_h.phase_ccam,
              p_factures_lignes_non_facturees_h.activite_ccam,
              p_factures_lignes_non_facturees_h.extension_ccam,
              p_factures_lignes_non_facturees_h.modificateur_ccam_1,
              p_factures_lignes_non_facturees_h.modificateur_ccam_2,
              p_factures_lignes_non_facturees_h.modificateur_ccam_3,
              p_factures_lignes_non_facturees_h.modificateur_ccam_4,
              p_factures_lignes_non_facturees_h.medecin_facture_id,
              p_factures_lignes_non_facturees_h.medecin_facture_id AS medecin_comptabilise_id,
              p_factures_lignes_non_facturees_h.nb_rubrique,
              p_factures_lignes_non_facturees_h.nb_rubrique AS nb_prestation,
              p_factures_lignes_non_facturees_h.prix_unitaire,
              0::numeric AS taux_0,
              0::numeric AS taux_1,
              0::numeric AS taux_2,
              0::numeric AS taux_22,
              0::numeric AS montant_facture,
              0::numeric AS montant_facture_0,
              0::numeric AS montant_facture_1,
              0::numeric AS montant_facture_2,
              0::numeric AS montant_facture_22,
              0::numeric AS montant_comptabilise,
              0::numeric AS montant_comptabilise_0,
              0::numeric AS montant_comptabilise_1,
              0::numeric AS montant_comptabilise_2,
              0::numeric AS montant_comptabilise_22,
              0::numeric AS montant_depassement,
              nb_rubrique * prix_unitaire * p_factures_lignes_non_facturees_h.coefficient AS montant_encours,
              0::numeric AS montant_encours_0,
              nb_rubrique * prix_unitaire * p_factures_lignes_non_facturees_h.coefficient AS montant_encours_1,
              0::numeric AS montant_encours_2,
              0::numeric AS montant_encours_22,
              nb_rubrique * prix_unitaire * p_factures_lignes_non_facturees_h.coefficient AS montant_non_facture
            FROM activite.p_factures_lignes_non_facturees_h
            JOIN w_cti_encours_factures ON p_factures_lignes_non_facturees_h.no_facture = w_cti_encours_factures.no_facture
            WHERE w_cti_encours_factures.ignorer <> '1'
            ;
  
            -- Total honoraires valorisés
            UPDATE activite.p_factures SET
              montant_encours_h = COALESCE(subview.montant_valorise,0)
            FROM 
              (SELECT 
                w_cti_encours_factures.no_facture,
                SUM(nb_rubrique * prix_unitaire * p_factures_lignes_non_facturees_h.coefficient) AS montant_valorise
              FROM activite.p_factures_lignes_non_facturees_h
              JOIN w_cti_encours_factures ON p_factures_lignes_non_facturees_h.no_facture = w_cti_encours_factures.no_facture
              WHERE w_cti_encours_factures.ignorer <> '1'
              GROUP BY 1
              ) subview 
            WHERE subview.no_facture = p_factures.no_facture;
            
      END IF;
      -- Transformation factures non valorisées en en cours
          UPDATE activite.p_factures_lignes_c SET
            montant_encours = montant_facture,
            montant_encours_0 = montant_facture_0,
            montant_encours_1 = montant_facture_1,
            montant_encours_2 = montant_facture_2,
            montant_encours_22 = montant_facture_22,
            montant_facture = 0,
            montant_facture_0 = 0,
            montant_facture_1 = 0,
            montant_facture_2 = 0,
            montant_facture_22 = 0
          FROM activite.p_factures
          WHERE p_factures.no_facture = p_factures_lignes_c.no_facture AND
            p_factures.code_facture = '3';
          UPDATE activite.p_factures_lignes_h SET
            montant_encours = montant_facture,
            montant_encours_0 = montant_facture_0,
            montant_encours_1 = montant_facture_1,
            montant_encours_2 = montant_facture_2,
            montant_encours_22 = montant_facture_22,
            montant_facture = 0,
            montant_facture_0 = 0,
            montant_facture_1 = 0,
            montant_facture_2 = 0,
            montant_facture_22 = 0
          FROM activite.p_factures
          WHERE p_factures.no_facture = p_factures_lignes_h.no_facture AND
            p_factures.code_facture = '3';
          UPDATE activite.p_factures SET
            type_facture = 'E',
            code_facture = '0',
            montant_encours_c = montant_facture_c,
            montant_encours_0_c = montant_facture_0_c,
            montant_encours_1_c = montant_facture_1_c,
            montant_encours_2_c = montant_facture_2_c,
            montant_encours_22_c = montant_facture_22_c,
            montant_facture_c = 0,
            montant_facture_0_c = 0,
            montant_facture_1_c = 0,
            montant_facture_2_c = 0,
            montant_facture_22_c = 0,
            montant_encours_h = montant_facture_h,
            montant_encours_0_h = montant_facture_0_h,
            montant_encours_1_h = montant_facture_1_h,
            montant_encours_2_h = montant_facture_2_h,
            montant_encours_22_h = montant_facture_22_h,
            montant_facture_h = 0,
            montant_facture_0_h = 0,
            montant_facture_1_h = 0,
            montant_facture_2_h = 0,
            montant_facture_22_h = 0
          WHERE code_facture = '3';
            -- Génération encours comptables
      IF (i_option NOT ILIKE '%-nogen%') THEN
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Generation en-cours comptables'; 
   
            IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN
      
              -- Effacer encours Budget Global
              DELETE FROM activite.p_factures_encours 
              WHERE code_origine = 'C' AND no_facture LIKE '%BG%' AND
                (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVEBG') IS DISTINCT FROM '1';
              -- Effacer factures encours comptabilisées sur même mois
              DELETE FROM activite.p_factures_encours
              USING activite.p_factures
              WHERE code_origine = 'C' AND 
                p_factures_encours.no_facture_reference = p_factures.no_facture AND
                p_factures.code_vente = '1' AND p_factures_encours.date_encours >= p_factures.date_vente AND
                date(date_trunc('month',p_factures_encours.date_encours)) >=
                  (SELECT date(date_trunc('month',t_divers.valeur_date)) FROM activite.t_divers WHERE t_divers.code = 'ENCOURSNOW');
              
              
              -- Effacer génération précédente
              DELETE FROM activite.p_factures_encours
              USING w_cti_encours_calcul_parametres
              WHERE date_trunc('month',p_factures_encours.date_encours) = date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND 
                code_origine = 'C';
              -- Lignes non référencées
              DELETE FROM activite.p_factures_encours_lignes_c
              WHERE NOT EXISTS (SELECT 'NOT_TO_DELETE' FROM activite.p_factures_encours WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture)
              AND p_factures_encours_lignes_c IS NOT NULL;
              DELETE FROM activite.p_facture_encours_ligne_valorise_c
              WHERE NOT EXISTS (SELECT 'NOT_TO_DELETE' FROM activite.p_factures_encours WHERE p_factures_encours.no_facture = p_facture_encours_ligne_valorise_c.no_facture)
              AND p_facture_encours_ligne_valorise_c IS NOT NULL;
              
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Entetes (valorisees)'; 
              
              -- Ajout encours
              INSERT INTO activite.p_factures_encours(
                sejour_id,
                no_sejour,
                no_facture,
                no_facture_reference,
                date_debut,
                date_fin,
                code_origine,
                code_sorti,
                date_encours,
                date_calcul,
                tiers_payant_1_id,
                tiers_payant_2_id,
                tiers_payant_22_id,
                tiers_payant_0_id,
                ghs_id,
                ghs_bebe1_id,
                ghs_bebe2_id,
                ghs_bebe3_id,
                code_cp_demandee,
                montant_encours_c,
                montant_encours_0_c,
                montant_encours_1_c,
                montant_encours_2_c,
                montant_encours_22_c,
                montant_encours_h,
                montant_encours_0_h,
                montant_encours_1_h,
                montant_encours_2_h,
                montant_encours_22_h,
                date_entree,
                heure_entree,
                date_sortie,
                heure_sortie,
                type_sejour,
                lieu_sortie_id,
                date_groupage,
                provider_id,
                ghm_id,
                filiere_soin_principale_id
              )
              SELECT
                w_cti_encours_factures.sejour_id,
                w_cti_encours_factures.no_sejour,
                w_cti_encours_factures.no_facture_encours,
                p_factures.no_facture_reference,
                w_cti_encours_factures.date_debut,
                w_cti_encours_factures.date_fin,
                'C' AS code_origine,
                CASE 
                  WHEN p_sejours.code_sorti = '1' AND p_sejours.type_sejour <> '3' AND date_trunc('month',p_sejours.date_sortie) <= date_trunc('month',w_cti_encours_factures.date_encours) THEN '1' 
                  WHEN p_sejours.type_sejour = '3' THEN '1' 
                  ELSE '0' END AS code_sorti,
                w_cti_encours_factures.date_encours AS date_encours,
                w_NOW AS date_calcul,
                w_cti_encours_factures.tiers_payant_1_id,
                w_cti_encours_factures.tiers_payant_2_id,
                0 AS tiers_payant_22_id,
                p_factures.tiers_payant_0_id,
                w_cti_encours_factures.ghs_id,
                w_cti_encours_factures.ghs_bebe1_id,
                w_cti_encours_factures.ghs_bebe2_id,
                w_cti_encours_factures.ghs_bebe3_id,
                w_cti_encours_factures.code_cp_demandee,
                w_cti_encours_factures.montant_encours_c,
                w_cti_encours_factures.montant_encours_0_c,
                w_cti_encours_factures.montant_encours_1_c,
                w_cti_encours_factures.montant_encours_2_c,
                0 AS montant_encours_22_c,
                0 AS montant_encours_h,
                0 AS montant_encours_0_h,
                0 AS montant_encours_1_h,
                0 AS montant_encours_2_h,
                0 AS montant_encours_22_h,
                p_sejours.date_entree,
                p_sejours.heure_entree,
                p_sejours.date_sortie,
                p_sejours.heure_sortie,
                p_sejours.type_sejour,
                p_sejours.lieu_sortie_id,
                p_sejours.date_groupage,
                p_sejours.provider_id,
                p_sejours.ghm_id,
                p_sejours.filiere_soin_principale_id
              FROM w_cti_encours_factures
                JOIN activite.p_factures ON w_cti_encours_factures.no_facture = p_factures.no_facture
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                LEFT JOIN activite.t_divers t_divers_encoreactivebg ON t_divers_encoreactivebg.code = 'ENCOURSACTIVEBG'
              WHERE w_cti_encours_factures.montant_encours_c <> 0 AND
                w_cti_encours_factures.date_debut <= w_cti_encours_factures.date_encours AND
                (
                w_cti_encours_factures.no_facture NOT LIKE '%BG' OR
                t_divers_encoreactivebg.valeur = '1'
                ) AND
                w_cti_encours_factures.ignorer <> '1';
              -- detail encours
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Lignes (valorisees)'; 
              
              INSERT INTO activite.p_factures_encours_lignes_c(
                facture_id,
                no_facture,
                date_debut,
                date_fin,
                nb_rubrique,
                coefficient,
                coefficient_mco,
                rubrique_facturation_id,
                prestation_id,
                lpp_id, 
                ucd_id, 
                prix_unitaire,
                lieu_id,
                nb_prestation,
                rubrique_comptabilisation_id,
                montant_encours,
                montant_encours_0,
                montant_encours_1,
                montant_encours_2,
                montant_encours_22
              )
              SELECT 
                p_factures_encours.oid AS facture_id,
                w_cti_encours_factures.no_facture_encours,
                MIN(w_cti_encours_factures_lignes_c.date_debut),
                LEAST(MAX(w_cti_encours_factures_lignes_c.date_fin),MAX(p_factures_encours.date_encours)),
                SUM(w_cti_encours_factures_lignes_c.nb_rubrique),
                w_cti_encours_factures_lignes_c.coefficient,
                w_cti_encours_factures_lignes_c.coefficient_mco,
                w_cti_encours_factures_lignes_c.rubrique_facturation_id,
                w_cti_encours_factures_lignes_c.prestation_id,
                w_cti_encours_factures_lignes_c.lpp_id, 
                w_cti_encours_factures_lignes_c.ucd_id, 
                w_cti_encours_factures_lignes_c.prix_unitaire,
                w_cti_encours_factures_lignes_c.lieu_id,
                SUM(w_cti_encours_factures_lignes_c.nb_prestation),
                w_cti_encours_factures_lignes_c.rubrique_comptabilisation_id,
                SUM(w_cti_encours_factures_lignes_c.montant_encours),
                SUM(w_cti_encours_factures_lignes_c.montant_encours_0),
                SUM(w_cti_encours_factures_lignes_c.montant_encours_1),
                SUM(w_cti_encours_factures_lignes_c.montant_encours_2),
                SUM(w_cti_encours_factures_lignes_c.montant_encours_22)
              FROM w_cti_encours_factures_lignes_c
                JOIN w_cti_encours_factures ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture
                JOIN activite.p_factures_encours ON w_cti_encours_factures.no_facture_encours = p_factures_encours.no_facture
                LEFT JOIN activite.t_divers t_divers_encoreactivebg ON t_divers_encoreactivebg.code = 'ENCOURSACTIVEBG'
              WHERE w_cti_encours_factures_lignes_c.montant_encours <> 0 AND
                w_cti_encours_factures_lignes_c.date_debut <= w_cti_encours_factures.date_encours AND
                w_cti_encours_factures_lignes_c.rubrique_facturation_id IS NOT NULL AND
                (
                w_cti_encours_factures.no_facture NOT LIKE '%BG' OR
                t_divers_encoreactivebg.valeur = '1'
                ) AND
                w_cti_encours_factures.ignorer <> '1' AND
                w_cti_encours_factures_lignes_c.ignorer <> '1'
              GROUP BY
                p_factures_encours.oid,
                date_trunc('month',w_cti_encours_factures_lignes_c.date_fin),
                w_cti_encours_factures.no_facture_encours,
                w_cti_encours_factures_lignes_c.coefficient,
                w_cti_encours_factures_lignes_c.coefficient_mco,
                w_cti_encours_factures_lignes_c.rubrique_facturation_id,
                w_cti_encours_factures_lignes_c.prestation_id,
                w_cti_encours_factures_lignes_c.lpp_id, 
                w_cti_encours_factures_lignes_c.ucd_id, 
                w_cti_encours_factures_lignes_c.prix_unitaire,
                w_cti_encours_factures_lignes_c.lieu_id,
                w_cti_encours_factures_lignes_c.rubrique_comptabilisation_id;
  
              -- Justificatif valorisation
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Justificatif (valorisees)'; 
              INSERT INTO activite.p_facture_encours_ligne_valorise_c(
                no_facture, facture_id, date_debut, date_fin, lieu_id, nb_rubrique, 
                nb_prestation, coefficient, coefficient_mco, rubrique_facturation_id, 
                prestation_id, lpp_id, ucd_id, prix_unitaire, montant_valorise_total, montant_encours, type_ligne_code, mode_calcul_code, 
                mode_calcul_texte)
              SELECT 
                w_cti_encours_factures.no_facture_encours,
                p_factures_encours.oid AS facture_id,
                MIN(w_cti_encours_factures_lignes_c.date_debut), 
                MAX(w_cti_encours_factures_lignes_c.date_fin),
                CASE 
                  WHEN t_prestations.code LIKE 'GHS%' THEN w_cti_encours_factures.lieu_sortie_id 
                  WHEN w_cti_encours_factures_lignes_c.type_ligne = 'SAISIE' THEN 0
                  ELSE w_cti_encours_factures_lignes_c.lieu_id END,
                SUM(nb_rubrique), 
                SUM(nb_prestation),
                coefficient, 
                coefficient_mco, 
                w_cti_encours_factures_lignes_c.rubrique_facturation_id,
                prestation_id,
                lpp_id, 
                ucd_id,
                prix_unitaire, 
                SUM(CASE WHEN w_cti_encours_factures.ignorer IS DISTINCT FROM '1' AND w_cti_encours_factures_lignes_c.ignorer IS DISTINCT FROM '1' THEN montant_encours ELSE 0 END),
                SUM(CASE WHEN w_cti_encours_factures.ignorer IS DISTINCT FROM '1' AND w_cti_encours_factures_lignes_c.ignorer IS DISTINCT FROM '1' AND w_cti_encours_factures_lignes_c.date_debut <= w_cti_encours_factures.date_encours THEN montant_encours ELSE 0 END),
                w_cti_encours_factures_lignes_c.type_ligne,
                CASE 
                  WHEN w_cti_encours_factures.ignorer = '1' AND w_cti_encours_factures_lignes_c.regle_ghs <> '' THEN '00-FORCE' 
                  WHEN w_cti_encours_factures_lignes_c.ignorer = '1' AND w_cti_encours_factures_lignes_c.regle_ghs <> '' THEN '00-FORCE' 
                  ELSE w_cti_encours_factures_lignes_c.regle_ghs END,
                CASE 
                  WHEN w_cti_encours_factures.ignorer = '1' THEN 'FACTURE IGNOREE.' 
                  WHEN w_cti_encours_factures_lignes_c.ignorer = '1' THEN 'LIGNE IGNOREE.' 
                  ELSE w_cti_encours_factures_lignes_c.regle_texte END
              FROM w_cti_encours_factures_lignes_c
                JOIN w_cti_encours_factures ON w_cti_encours_factures_lignes_c.no_facture = w_cti_encours_factures.no_facture 
                JOIN activite.p_factures_encours ON w_cti_encours_factures.no_facture_encours = p_factures_encours.no_facture
                JOIN activite.t_prestations ON prestation_id = t_prestations.oid
              WHERE w_cti_encours_factures_lignes_c.rubrique_facturation_id IS NOT NULL AND 
                (montant_encours <> 0 OR
                w_cti_encours_factures_lignes_c.ignorer = '1'
                )
              GROUP BY 1,2,5,8,9,10,11,12,13,14,17,18,19
              ORDER BY 1;
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Entetes (facturees debut de mois)'; 
              
              -- Ajout encours
              INSERT INTO activite.p_factures_encours(
                sejour_id,
                no_sejour,
                no_facture,
                no_facture_reference,
                date_debut,
                date_fin,
                code_origine,
                code_sorti,
                date_encours,
                date_calcul,
                tiers_payant_1_id,
                tiers_payant_2_id,
                tiers_payant_22_id,
                tiers_payant_0_id,
                ghs_id,
                ghs_bebe1_id,
                ghs_bebe2_id,
                ghs_bebe3_id,
                code_cp_demandee,
                montant_encours_c,
                montant_encours_0_c,
                montant_encours_1_c,
                montant_encours_2_c,
                montant_encours_22_c,
                montant_encours_h,
                montant_encours_0_h,
                montant_encours_1_h,
                montant_encours_2_h,
                montant_encours_22_h,
                date_entree,
                heure_entree,
                date_sortie,
                heure_sortie,
                type_sejour,
                lieu_sortie_id,
                date_groupage,
                provider_id,
                ghm_id,
                filiere_soin_principale_id
              )
              SELECT
                p_factures.sejour_id,
                p_factures.no_sejour,
                p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00') AS no_facture_encours,
                p_factures.no_facture_reference,
                p_factures.date_debut,
                p_factures.date_fin,
                'C' AS code_origine,
                CASE 
                  WHEN p_sejours.code_sorti = '1' AND p_sejours.type_sejour <> '3' AND date_trunc('month',p_sejours.date_sortie) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) THEN '1' 
                  WHEN p_sejours.type_sejour = '3' THEN '1'
                  ELSE '0' END AS code_sorti,
                w_cti_encours_calcul_parametres.date_encours AS date_encours,
                w_NOW AS date_calcul,
                p_factures.tiers_payant_1_id,
                p_factures.tiers_payant_2_id,
                0 AS tiers_payant_22_id,
                p_factures.tiers_payant_0_id,
                p_factures.ghs_id,
                p_factures.ghs_bebe1_id,
                p_factures.ghs_bebe2_id,
                p_factures.ghs_bebe3_id,
                p_factures.code_cp_demandee,
                p_factures.montant_comptabilise_c AS montant_encours_c,
                p_factures.montant_comptabilise_0_c AS montant_encours_0_c,
                p_factures.montant_comptabilise_1_c AS montant_encours_1_c,
                p_factures.montant_comptabilise_2_c AS montant_encours_2_c,
                0 AS montant_encours_22_c,
                0 AS montant_encours_h,
                0 AS montant_encours_0_h,
                0 AS montant_encours_1_h,
                0 AS montant_encours_2_h,
                0 AS montant_encours_22_h,
                p_sejours.date_entree,
                p_sejours.heure_entree,
                p_sejours.date_sortie,
                p_sejours.heure_sortie,
                p_sejours.type_sejour,
                p_sejours.lieu_sortie_id,
                p_sejours.date_groupage,
                p_sejours.provider_id,
                p_sejours.ghm_id,
                p_sejours.filiere_soin_principale_id
              FROM activite.p_factures 
              JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
              JOIN w_cti_encours_calcul_parametres ON 1=1
              WHERE date_trunc('month',p_factures.date_fin) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG';
        
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Lignes (facturees debut de mois)'; 
              INSERT INTO activite.p_factures_encours_lignes_c(
                facture_id,
                no_facture,
                date_debut,
                date_fin,
                nb_rubrique,
                coefficient,
                coefficient_mco,
                rubrique_facturation_id,
                prestation_id,
                prix_unitaire,
                lieu_id,
                nb_prestation,
                rubrique_comptabilisation_id,
                compte_produit_id,
                montant_encours,
                montant_encours_0,
                montant_encours_1,
                montant_encours_2,
                montant_encours_22
              )
              SELECT 
                p_factures_encours.oid AS facture_id,
                p_factures_encours.no_facture AS no_facture_encours,
                MIN(p_factures_lignes_c.date_debut),
                MAX(p_factures_lignes_c.date_fin),
                SUM(p_factures_lignes_c.nb_rubrique),
                p_factures_lignes_c.coefficient,
                p_factures_lignes_c.coefficient_mco,
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire,
                p_factures_lignes_c.lieu_id,
                SUM(p_factures_lignes_c.nb_prestation),
                p_factures_lignes_c.rubrique_comptabilisation_id,
                p_factures_lignes_c.compte_produit_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)
              FROM activite.p_factures 
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN w_cti_encours_calcul_parametres ON 1=1
                JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
                JOIN activite.p_factures_encours ON (p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00')) = p_factures_encours.no_facture
              WHERE date_trunc('month',p_factures.date_fin) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG' AND
                p_factures_lignes_c.montant_comptabilise <> 0
              GROUP BY
                p_factures_encours.oid,
                p_factures_encours.no_facture,
                date_trunc('month',p_factures_lignes_c.date_fin),
                p_factures_lignes_c.coefficient,
                p_factures_lignes_c.coefficient_mco,
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire,
                p_factures_lignes_c.lieu_id,
                p_factures_lignes_c.rubrique_comptabilisation_id,
                p_factures_lignes_c.compte_produit_id
              ;
              -- Justificatif valorisation
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Justificatif (facturees debut de mois)'; 
              INSERT INTO activite.p_facture_encours_ligne_valorise_c(
                no_facture, facture_id, date_debut, date_fin, lieu_id, nb_rubrique, 
                nb_prestation, coefficient, coefficient_mco, rubrique_facturation_id, 
                prestation_id, prix_unitaire, montant_valorise_total, montant_encours, type_ligne_code, mode_calcul_code, 
                mode_calcul_texte)
              SELECT 
                p_factures_encours.no_facture,
                p_factures_encours.oid AS facture_id,
                MIN(p_factures_lignes_c.date_debut), 
                MAX(p_factures_lignes_c.date_fin),
                CASE WHEN t_prestations.code LIKE 'GHS%' THEN p_sejours.lieu_sortie_id ELSE p_factures_lignes_c.lieu_id END,
                SUM(p_factures_lignes_c.nb_rubrique), 
                SUM(p_factures_lignes_c.nb_prestation),
                p_factures_lignes_c.coefficient, 
                p_factures_lignes_c.coefficient_mco, 
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire, 
                SUM(p_factures_lignes_c.montant_comptabilise),
                SUM(p_factures_lignes_c.montant_comptabilise),
                CASE 
                  WHEN t_prestations.code = 'GHS' AND p_sejours.ghs_id > 0 THEN 'GHS'
                  WHEN t_prestations.code = 'GHS' AND p_sejours.ghs_id <= 0 THEN 'GHSNG'
                  WHEN t_prestations.code = 'EXH' AND p_sejours.ghs_id > 0 THEN 'EXH'
                  WHEN t_prestations.code = 'EXH' AND p_sejours.ghs_id <= 0 THEN 'EXHNG'
                  WHEN t_prestations.code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN 'PJ'
  				  WHEN t_prestations.code = 'GMT' OR type_valorisation_non_facture = 'GMT' THEN 'GMT'
                  WHEN t_prestations.code = 'FJ' THEN 'FJ'
                  WHEN t_prestations.code = 'PMS' THEN 'PMS'
                  WHEN t_prestations.code = 'ENT' OR type_valorisation_non_facture = 'ENT' THEN 'ENT'
                  WHEN t_prestations.code IN ('SRC','STF','REA') THEN 'SSS'
                  WHEN t_prestations.code IN ('NN1','NN2','NN3') THEN 'NNX'
                  WHEN t_prestations.code IN ('FJA') THEN 'FJA'
                  WHEN t_prestations.code IN ('CPC') OR type_valorisation_non_facture = 'CP' THEN 'CPC'
                  WHEN t_prestations.code LIKE 'ATU' THEN 'ATU'
                  WHEN t_prestations.code LIKE 'FPU' THEN 'ATU'
                  WHEN t_prestations.code LIKE 'SE%' THEN 'SEH'
                  ELSE '' END AS type_ligne,
                CASE 
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti = '1' THEN 'FROMJVTSOR'
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti <> '1' THEN 'FROMJVTPRE'
                  ELSE 'NOJUSTIF'::text END AS mode_calcul_code,
                CASE 
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti = '1' THEN 'Encours depuis facturation (sorti)'
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti <> '1' THEN 'Encours depuis facturation (présent)'
                  ELSE 'Sans justificatif de valorisation'::text END AS mode_calcul_texte
              FROM activite.p_factures 
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN w_cti_encours_calcul_parametres ON 1=1
                JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
                JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                JOIN activite.p_factures_encours ON (p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00')) = p_factures_encours.no_facture
              WHERE date_trunc('month',p_factures.date_fin) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG' AND
                p_factures_lignes_c.montant_comptabilise <> 0
              GROUP BY 1,2,5,8,9,10,11,12,15,16,17
              ;
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Entetes (facturees debut de mois a cheval)'; 
              
              -- Ajout encours
              INSERT INTO activite.p_factures_encours(
                sejour_id,
                no_sejour,
                no_facture,
                no_facture_reference,
                date_debut,
                date_fin,
                code_origine,
                code_sorti,
                date_encours,
                date_calcul,
                tiers_payant_1_id,
                tiers_payant_2_id,
                tiers_payant_22_id,
                tiers_payant_0_id,
                ghs_id,
                ghs_bebe1_id,
                ghs_bebe2_id,
                ghs_bebe3_id,
                code_cp_demandee,
                montant_encours_c,
                montant_encours_0_c,
                montant_encours_1_c,
                montant_encours_2_c,
                montant_encours_22_c,
                montant_encours_h,
                montant_encours_0_h,
                montant_encours_1_h,
                montant_encours_2_h,
                montant_encours_22_h,
                date_entree,
                heure_entree,
                date_sortie,
                heure_sortie,
                type_sejour,
                lieu_sortie_id,
                date_groupage,
                provider_id,
                ghm_id,
                filiere_soin_principale_id
              )
              SELECT
                p_factures.sejour_id,
                p_factures.no_sejour,
                p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00') AS no_facture_encours,
                p_factures.no_facture_reference,
                p_factures.date_debut,
                p_factures.date_fin,
                'C' AS code_origine,
                CASE 
                  WHEN p_sejours.code_sorti = '1' AND p_sejours.type_sejour <> '3' AND date_trunc('month',p_sejours.date_sortie) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) THEN '1' 
                  WHEN p_sejours.type_sejour = '3'  THEN '1' 
                  ELSE '0' END AS code_sorti,
                w_cti_encours_calcul_parametres.date_encours AS date_encours,
                w_NOW AS date_calcul,
                p_factures.tiers_payant_1_id,
                p_factures.tiers_payant_2_id,
                0 AS tiers_payant_22_id,
                p_factures.tiers_payant_0_id,
                p_factures.ghs_id,
                p_factures.ghs_bebe1_id,
                p_factures.ghs_bebe2_id,
                p_factures.ghs_bebe3_id,
                p_factures.code_cp_demandee,
                SUM(p_factures_lignes_c.montant_comptabilise) AS montant_encours_c,
                SUM(p_factures_lignes_c.montant_comptabilise_0) AS montant_encours_0_c,
                SUM(p_factures_lignes_c.montant_comptabilise_1) AS montant_encours_1_c,
                SUM(p_factures_lignes_c.montant_comptabilise_2) AS montant_encours_2_c,
                0 AS montant_encours_22_c,
                0 AS montant_encours_h,
                0 AS montant_encours_0_h,
                0 AS montant_encours_1_h,
                0 AS montant_encours_2_h,
                0 AS montant_encours_22_h,
                p_sejours.date_entree,
                p_sejours.heure_entree,
                p_sejours.date_sortie,
                p_sejours.heure_sortie,
                p_sejours.type_sejour,
                p_sejours.lieu_sortie_id,
                p_sejours.date_groupage,
                p_sejours.provider_id,
                p_sejours.ghm_id,
                p_sejours.filiere_soin_principale_id
              FROM activite.p_factures 
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN w_cti_encours_calcul_parametres ON 1=1
                JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
              WHERE date_trunc('month',p_factures.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                date_trunc('month',p_factures.date_fin) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                date_trunc('month',p_factures_lignes_c.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG' AND
                p_factures_lignes_c.montant_comptabilise <> 0
              GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,30,31,32,33,34,35,36,37,38,39
              ;
        
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Lignes (facturees debut de mois a cheval)'; 
              INSERT INTO activite.p_factures_encours_lignes_c(
                facture_id,
                no_facture,
                date_debut,
                date_fin,
                nb_rubrique,
                coefficient,
                coefficient_mco,
                rubrique_facturation_id,
                prestation_id,
                prix_unitaire,
                lieu_id,
                nb_prestation,
                rubrique_comptabilisation_id,
                compte_produit_id,
                montant_encours,
                montant_encours_0,
                montant_encours_1,
                montant_encours_2,
                montant_encours_22
              )
              SELECT 
                p_factures_encours.oid AS facture_id,
                p_factures_encours.no_facture AS no_facture_encours,
                MIN(p_factures_lignes_c.date_debut),
                MAX(p_factures_lignes_c.date_fin),
                SUM(p_factures_lignes_c.nb_rubrique),
                p_factures_lignes_c.coefficient,
                p_factures_lignes_c.coefficient_mco,
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire,
                p_factures_lignes_c.lieu_id,
                SUM(p_factures_lignes_c.nb_prestation),
                p_factures_lignes_c.rubrique_comptabilisation_id,
                p_factures_lignes_c.compte_produit_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)
              FROM activite.p_factures 
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN w_cti_encours_calcul_parametres ON 1=1
                JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
                JOIN activite.p_factures_encours ON (p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00')) = p_factures_encours.no_facture
              WHERE date_trunc('month',p_factures.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                date_trunc('month',p_factures.date_fin) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                date_trunc('month',p_factures_lignes_c.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG' AND
                p_factures_lignes_c.montant_comptabilise <> 0
              GROUP BY
                p_factures_encours.oid,
                p_factures_encours.no_facture,
                date_trunc('month',p_factures_lignes_c.date_fin),
                p_factures_lignes_c.coefficient,
                p_factures_lignes_c.coefficient_mco,
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire,
                p_factures_lignes_c.lieu_id,
                p_factures_lignes_c.rubrique_comptabilisation_id,
                p_factures_lignes_c.compte_produit_id
              ;
  
              -- Justificatif valorisation
        RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Justificatif (facturees debut de mois a cheval)'; 
              INSERT INTO activite.p_facture_encours_ligne_valorise_c(
                no_facture, facture_id, date_debut, date_fin, lieu_id, nb_rubrique, 
                nb_prestation, coefficient, coefficient_mco, rubrique_facturation_id, 
                prestation_id, prix_unitaire, montant_valorise_total, montant_encours, type_ligne_code, mode_calcul_code, 
                mode_calcul_texte)
              SELECT 
                p_factures_encours.no_facture,
                p_factures_encours.oid AS facture_id,
                MIN(p_factures_lignes_c.date_debut), 
                MAX(p_factures_lignes_c.date_fin),
                CASE WHEN t_prestations.code LIKE 'GHS%' THEN p_sejours.lieu_sortie_id ELSE p_factures_lignes_c.lieu_id END,
                SUM(p_factures_lignes_c.nb_rubrique), 
                SUM(p_factures_lignes_c.nb_prestation),
                p_factures_lignes_c.coefficient, 
                p_factures_lignes_c.coefficient_mco, 
                p_factures_lignes_c.rubrique_facturation_id,
                p_factures_lignes_c.prestation_id,
                p_factures_lignes_c.prix_unitaire, 
                SUM(p_factures_lignes_c.montant_comptabilise),
                SUM(CASE WHEN date_trunc('month',p_factures_lignes_c.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) THEN p_factures_lignes_c.montant_comptabilise ELSE 0 END),
                CASE 
                  WHEN t_prestations.code = 'GHS' AND p_sejours.ghs_id > 0 THEN 'GHS'
                  WHEN t_prestations.code = 'GHS' AND p_sejours.ghs_id <= 0 THEN 'GHSNG'
                  WHEN t_prestations.code = 'EXH' AND p_sejours.ghs_id > 0 THEN 'EXH'
                  WHEN t_prestations.code = 'EXH' AND p_sejours.ghs_id <= 0 THEN 'EXHNG'
                  WHEN t_prestations.code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN 'PJ'
  				  WHEN t_prestations.code = 'GMT' OR type_valorisation_non_facture = 'GMT' THEN 'GMT'
                  WHEN t_prestations.code = 'FJ' THEN 'FJ'
                  WHEN t_prestations.code = 'PMS' THEN 'PMS'
                  WHEN t_prestations.code = 'ENT' OR type_valorisation_non_facture = 'ENT' THEN 'ENT'
                  WHEN t_prestations.code IN ('SRC','STF','REA') THEN 'SSS'
                  WHEN t_prestations.code IN ('NN1','NN2','NN3') THEN 'NNX'
                  WHEN t_prestations.code IN ('FJA') THEN 'FJA'
                  WHEN t_prestations.code IN ('CPC') OR type_valorisation_non_facture = 'CP' THEN 'CPC'
                  WHEN t_prestations.code LIKE 'ATU' THEN 'ATU'
                  WHEN t_prestations.code LIKE 'FPU' THEN 'ATU'
                  WHEN t_prestations.code LIKE 'SE%' THEN 'SEH'
                  ELSE '' END AS type_ligne,
                CASE 
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti = '1' THEN 'FROMJVTSOR'
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti <> '1' THEN 'FROMJVTPRE'
                  ELSE 'NOJUSTIF'::text END AS mode_calcul_code,
                CASE 
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti = '1' THEN 'Encours depuis facturation (sorti)'
                  WHEN p_factures_encours.no_facture LIKE '%.EV%' AND p_factures_encours.code_sorti <> '1' THEN 'Encours depuis facturation (présent)'
                  ELSE 'Sans justificatif de valorisation'::text END AS mode_calcul_texte
              FROM activite.p_factures 
                JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN w_cti_encours_calcul_parametres ON 1=1
                JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
                JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                JOIN activite.p_factures_encours ON (p_factures.no_facture || '.EV' || substr(to_char(date_part('year', w_cti_encours_calcul_parametres.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_cti_encours_calcul_parametres.date_encours),'FM00')) = p_factures_encours.no_facture
              WHERE date_trunc('month',p_factures.date_debut) <= date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                date_trunc('month',p_factures.date_fin) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.code_facture >= '1' AND
                date_trunc('month',p_factures.date_vente) > date_trunc('month',w_cti_encours_calcul_parametres.date_encours) AND
                p_factures.no_facture NOT LIKE '%BG' AND
                p_factures_lignes_c.montant_comptabilise <> 0
              GROUP BY 1,2,5,8,9,10,11,12,15,16,17
              ;
            END IF;
        
      END IF;
    END LOOP;
    -- Moulinettes sur encours déjà calculés
    IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN	
      -- Réactualisation oid séjour
      UPDATE activite.p_factures_encours
      SET no_sejour = p_factures.no_sejour
      FROM activite.p_factures
      WHERE code_origine = 'C' AND
        p_factures_encours.no_facture_reference = p_factures.no_facture AND
        (p_factures_encours.no_sejour = '' OR  p_factures_encours.no_sejour IS NULL);
      UPDATE activite.p_factures_encours
      SET no_sejour = p_sejours.no_sejour
      FROM activite.p_sejours
      WHERE code_origine = 'C' AND 
        split_part(p_factures_encours.no_facture,'.',1) = 'E' || p_sejours.no_sejour AND
        (p_factures_encours.no_sejour = '' OR  p_factures_encours.no_sejour IS NULL);
      UPDATE activite.p_factures_encours
      SET no_sejour = p_sejours.no_sejour
      FROM activite.p_sejours
      WHERE code_origine = 'C' AND 
        split_part(p_factures_encours.no_facture,'.',1) = p_sejours.no_sejour AND
        (p_factures_encours.no_sejour = '' OR  p_factures_encours.no_sejour IS NULL);
      UPDATE activite.p_factures_encours
      SET sejour_id = p_sejours.oid
      FROM activite.p_sejours 
      WHERE p_factures_encours.no_sejour = p_sejours.no_sejour AND
        sejour_id IS DISTINCT FROM p_sejours.oid;
      
      UPDATE activite.p_factures_encours
      SET no_sejour = split_part(p_factures_encours.no_facture,'.',1), sejour_id = 0
      WHERE p_factures_encours.no_sejour IS NULL OR p_factures_encours.no_sejour = '';
      
      UPDATE activite.p_factures_encours
      SET sejour_id = 0  
      WHERE no_sejour NOT IN (SELECT no_sejour FROM activite.p_sejours) AND
        sejour_id <> 0;
  
      
      UPDATE activite.p_factures_encours
      SET lieu_sortie_id = p_sejours.lieu_sortie_id
      FROM activite.p_sejours 
      WHERE p_sejours.no_sejour = p_factures_encours.no_sejour AND
        p_sejours.lieu_sortie_id <> p_factures_encours.lieu_sortie_id
      ;
      -- Ajout factures du mois comptabilisées en début de mois suivant (avant date cloture encours)
          
      RAISE NOTICE '%. %' , w_date_encours_YYMM, 'Ajout factures comptabilisee debut du mois suivant'; 
      IF NOT EXISTS (SELECT * FROM pg_class WHERE relnamespace = pg_my_temp_schema() AND relname = 'w_cti_encours_vente') THEN
        CREATE TEMP TABLE w_cti_encours_vente
        (
          no_sejour text,
          date_encours date,
          no_facture text,
          no_facture_encours text
        );
      END IF;
      TRUNCATE w_cti_encours_vente;
      INSERT INTO w_cti_encours_vente
      SELECT p_factures.no_sejour, 
        date(date_trunc('month', p_factures.date_fin) + interval '1 month' - interval '1 day') AS date_encours, 
        (MAX(ARRAY[p_factures.date_vente::text, p_factures.no_facture]))[2] AS no_facture,
        (MAX(ARRAY[p_factures.date_vente::text, p_factures.no_facture]))[2] || '.EV' || to_char(p_factures.date_fin,'YYMM') AS no_facture_encours
      FROM activite.p_factures
        JOIN (SELECT 
            COALESCE(
              MAX(CASE WHEN no_facture LIKE '%.EV%' THEN date(date_encours+interval '1 day') ELSE NULL END),
              MIN(date(date_trunc('month',date_encours))) 
            ) AS date_encours_debut,
            MAX(date_encours) AS date_encours_fin
          FROM activite.p_factures_encours 
          WHERE date_encours >= '20140101' AND 
          code_origine = 'C') w_periode_encours ON 1=1
        JOIN activite.t_divers ON t_divers.code = 'DATEENCOURS'
        LEFT JOIN activite.p_factures p_factures_vente ON 
          p_factures_vente.no_sejour = p_factures.no_sejour AND 
          p_factures_vente.date_vente BETWEEN date_trunc('month', p_factures.date_fin) AND date_trunc('month', p_factures.date_fin) + interval '1 month' - interval '1 day'
        LEFT JOIN activite.p_factures_encours ON 
          p_factures_encours.no_sejour = p_factures.no_sejour AND 
          code_origine = 'C' AND
          p_factures_encours.date_encours BETWEEN date_trunc('month', p_factures.date_fin) AND date_trunc('month', p_factures.date_fin) + interval '1 month' - interval '1 day'
      WHERE p_factures.date_fin BETWEEN date_encours_debut AND date_encours_fin AND
        p_factures.date_vente BETWEEN date_trunc('month', p_factures.date_fin) + interval '1 month' - interval '1 day' AND date_trunc('month', p_factures.date_fin) + interval '1 month' - interval '1 day' + (t_divers.valeur||' day')::INTERVAL AND
        p_factures.montant_facture_c > 0 AND
        p_factures.no_facture NOT LIKE '%BG' AND
        p_factures.code_vente = '1' AND
        p_factures_vente.no_facture IS NULL AND
        p_factures_encours.no_facture IS NULL
      GROUP BY 1,2,to_char(p_factures.date_fin,'YYMM')
      ORDER BY 1,2
      ;
      INSERT INTO activite.p_factures_encours(
        sejour_id,
        no_sejour,
        no_facture,
        no_facture_reference,
        date_debut,
        date_fin,
        code_origine,
        code_sorti,
        date_encours,
        tiers_payant_1_id,
        tiers_payant_2_id,
        tiers_payant_22_id,
        tiers_payant_0_id,
        ghs_id,
        ghs_bebe1_id,
        ghs_bebe2_id,
        ghs_bebe3_id,
        code_cp_demandee,
        montant_encours_c,
        montant_encours_0_c,
        montant_encours_1_c,
        montant_encours_2_c,
        montant_encours_22_c,
        montant_encours_h,
        montant_encours_0_h,
        montant_encours_1_h,
        montant_encours_2_h,
        montant_encours_22_h,
        date_entree,
        heure_entree,
        date_sortie,
        heure_sortie,
        type_sejour,
        lieu_sortie_id,
        date_groupage,
        provider_id,
        ghm_id,
        filiere_soin_principale_id
      )
      SELECT
        p_sejours.oid,
        p_sejours.no_sejour,
        w_cti_encours_vente.no_facture_encours,
        p_factures.no_facture_reference,
        p_factures.date_debut,
        p_factures.date_fin,
        'C' AS code_origine,
        '1' AS code_sorti,
        w_cti_encours_vente.date_encours AS date_encours,
        p_factures.tiers_payant_1_id,
        p_factures.tiers_payant_2_id,
        0 AS tiers_payant_22_id,
        p_factures.tiers_payant_0_id,
        p_factures.ghs_id,
        p_factures.ghs_bebe1_id,
        p_factures.ghs_bebe2_id,
        p_factures.ghs_bebe3_id,
        p_factures.code_cp_demandee,
        p_factures.montant_facture_c,
        p_factures.montant_facture_0_c,
        p_factures.montant_facture_1_c,
        p_factures.montant_facture_2_c,
        0 AS montant_encours_22_c,
        0 AS montant_encours_h,
        0 AS montant_encours_0_h,
        0 AS montant_encours_1_h,
        0 AS montant_encours_2_h,
        0 AS montant_encours_22_h,
        p_sejours.date_entree,
        p_sejours.heure_entree,
        p_sejours.date_sortie,
        p_sejours.heure_sortie,
        p_sejours.type_sejour,
        p_sejours.lieu_sortie_id,
        p_sejours.date_groupage,
        p_sejours.provider_id,
        p_sejours.ghm_id,
        p_sejours.filiere_soin_principale_id
      FROM w_cti_encours_vente
        JOIN activite.p_factures ON w_cti_encours_vente.no_facture = p_factures.no_facture
        JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
      ;
      INSERT INTO activite.p_factures_encours_lignes_c(
        facture_id,
        no_facture,
        date_debut,
        date_fin,
        nb_rubrique,
        coefficient,
        coefficient_mco,
        rubrique_facturation_id,
        prestation_id,
        prix_unitaire,
        lieu_id,
        nb_prestation,
        rubrique_comptabilisation_id,
        compte_produit_id,
        montant_encours,
        montant_encours_0,
        montant_encours_1,
        montant_encours_2,
        montant_encours_22
      )
      SELECT 
        p_factures_encours.oid AS facture_id,
        w_cti_encours_vente.no_facture_encours,
        MIN(p_factures_lignes_c.date_debut),
        MAX(p_factures_lignes_c.date_fin),
        SUM(p_factures_lignes_c.nb_rubrique),
        p_factures_lignes_c.coefficient,
        p_factures_lignes_c.coefficient_mco,
        p_factures_lignes_c.rubrique_facturation_id,
        p_factures_lignes_c.prestation_id,
        p_factures_lignes_c.prix_unitaire,
        p_factures_lignes_c.lieu_id,
        SUM(p_factures_lignes_c.nb_prestation),
        p_factures_lignes_c.rubrique_comptabilisation_id,
        p_factures_lignes_c.compte_produit_id,
        SUM(p_factures_lignes_c.montant_facture),
        SUM(p_factures_lignes_c.montant_facture_0),
        SUM(p_factures_lignes_c.montant_facture_1),
        SUM(p_factures_lignes_c.montant_facture_2),
        SUM(p_factures_lignes_c.montant_facture_22)
      FROM w_cti_encours_vente
        JOIN activite.p_factures ON w_cti_encours_vente.no_facture = p_factures.no_facture
        JOIN activite.p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
        JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
        JOIN activite.p_factures_encours ON w_cti_encours_vente.no_facture_encours = p_factures_encours.no_facture
      WHERE p_factures_lignes_c.montant_facture <> 0 AND
        p_factures_lignes_c.date_debut <= w_cti_encours_vente.date_encours AND
        p_factures_lignes_c.rubrique_facturation_id IS NOT NULL 
      GROUP BY
        p_factures_encours.oid,
        w_cti_encours_vente.no_facture_encours,
        p_factures_lignes_c.coefficient,
        p_factures_lignes_c.coefficient_mco,
        p_factures_lignes_c.rubrique_facturation_id,
        p_factures_lignes_c.prestation_id,
        p_factures_lignes_c.prix_unitaire,
        p_factures_lignes_c.lieu_id,
        p_factures_lignes_c.rubrique_comptabilisation_id,
        p_factures_lignes_c.compte_produit_id
      ;
    END IF;
    
    -- désactivation index
    RAISE NOTICE '%' , 'Finalisation. Reactivation index';  
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_2');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_4');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_5');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_6');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_7');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_8');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_9');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_10');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_11');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_2');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_3');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_4');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_5');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_6');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_7');
    PERFORM base.cti_enable_index('activite', 'i_factures_encours_lignes_c_8');
  
    -- Reconstitution LPP et UCD sur encours
    IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN	
      UPDATE activite.p_factures_encours_lignes_c
      SET lpp_id = subview.lpp_id, ucd_id = subview.ucd_id
      FROM activite.p_factures_encours,
        (
        SELECT p_factures.no_sejour, 
          prestation_id,
          ABS(montant_facture + montant_encours) AS montant, 
          COUNT(DISTINCT lpp_id::text||ucd_id::text),
          MAX(lpp_id) AS lpp_id, 
          MAX(ucd_id) AS ucd_id
        FROM activite.p_factures_lignes_c
        JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
        WHERE (montant_facture <> 0 OR montant_encours <> 0) AND
          (ucd_id <> 0 OR lpp_id <> 0)
        GROUP BY 1,2,3
        ) subview
      WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture AND
        p_factures_encours.no_sejour = subview.no_sejour AND
        p_factures_encours_lignes_c.prestation_id = subview.prestation_id AND
        p_factures_encours_lignes_c.montant_encours = subview.montant AND
        COALESCE(p_factures_encours_lignes_c.lpp_id,0) = 0 AND
        COALESCE(p_factures_encours_lignes_c.ucd_id,0) = 0
        ;
  
      UPDATE activite.p_facture_encours_ligne_valorise_c
      SET lpp_id = subview.lpp_id, ucd_id = subview.ucd_id
      FROM (
        SELECT p_factures_encours_lignes_c.no_facture,
          prestation_id,
          ABS(montant_encours) AS montant, 
          COUNT(DISTINCT lpp_id::text||ucd_id::text),
          MAX(lpp_id) AS lpp_id, 
          MAX(ucd_id) AS ucd_id
        FROM activite.p_factures_encours_lignes_c
        WHERE montant_encours <> 0 AND
          (ucd_id <> 0 OR lpp_id <> 0)
        GROUP BY 1,2,3
        ) subview
      WHERE p_facture_encours_ligne_valorise_c.no_facture = subview.no_facture AND
        p_facture_encours_ligne_valorise_c.prestation_id = subview.prestation_id AND
        p_facture_encours_ligne_valorise_c.montant_encours = subview.montant AND
        COALESCE(p_facture_encours_ligne_valorise_c.lpp_id,0) = 0 AND
        COALESCE(p_facture_encours_ligne_valorise_c.ucd_id,0) = 0
        ;
    END IF;
  
    -- Récupérer le bon compte sur les ventes (WEB100T) car quelque fois, le compte des ventes est provisoire (02020000) au moment des en cours
    IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN	
      IF (SELECT count(*) FROM activite.p_factures_encours_lignes_c JOIN activite.t_compte ON compte_produit_id = t_compte.oid WHERE t_compte.code LIKE '02%') > 0 THEN
        UPDATE activite.p_factures_encours_lignes_c
        SET compte_produit_id = subview.compte_produit_id
        FROM
        (
        SELECT p_factures_encours_lignes_c.no_facture, p_factures_encours_lignes_c.rubrique_facturation_id, p_factures_encours_lignes_c.CTID AS toCTID, MAX(subview.compte_produit_id) AS compte_produit_id
        FROM activite.p_factures_encours_lignes_c
        JOIN activite.t_compte ON compte_produit_id = t_compte.oid
        JOIN (SELECT no_facture, rubrique_facturation_id, MAX(compte_produit_id) AS compte_produit_id FROM activite.p_factures_lignes_c GROUP BY 1,2) subview ON
          subview.no_facture = split_part(p_factures_encours_lignes_c.no_facture,'.EV',1) AND
          subview.rubrique_facturation_id = p_factures_encours_lignes_c.rubrique_facturation_id
        WHERE p_factures_encours_lignes_c.no_facture LIKE '%EV%' AND
          t_compte.code LIKE '02%'
        GROUP BY 1,2,3
        ) subview
        WHERE subview.no_facture = p_factures_encours_lignes_c.no_facture AND
          subview.rubrique_facturation_id = p_factures_encours_lignes_c.rubrique_facturation_id AND
          p_factures_encours_lignes_c.CTID = toCTID
        ;
      END IF;
    END IF;
    -- Initialiser les filieres de soin anterieurs a partir de la valeur courante
    IF EXISTS (SELECT valeur FROM activite.t_divers WHERE code = 'ENCOURSACTIVE' AND valeur = '1') THEN
      UPDATE activite.p_factures_encours
      SET filiere_soin_principale_id = p_sejours.filiere_soin_principale_id
      FROM activite.p_sejours
      WHERE p_factures_encours.no_sejour = p_sejours.no_sejour AND
        p_factures_encours.filiere_soin_principale_id = 0 AND
        p_sejours.filiere_soin_principale_id <> 0
      ;
    END IF;
      RETURN 'OK' ;
  END;