return: text
lang: plpgsql
src: |
  DECLARE    
      v_montant_limitation numeric := 0;
      v_ecart_br numeric := 0;
      v_ecart_br_ht numeric := 0;
      v_ecart_remb numeric := 0;
      v_nb_src_factures numeric := 0;
      v_nb_src_autorises numeric := 0;
      v_return_string text := '';
  BEGIN
      
      DROP TABLE IF EXISTS w_imports;
      CREATE TEMP TABLE w_imports (import_id bigint, mat2a_import_id bigint, mat2a_annee numeric, mat2a_mois numeric, import_finess text);
      TRUNCATE w_imports;
      INSERT INTO w_imports 
      SELECT 
          MAX(p_imports.oid) AS import_id, 
          (MAX(Array[p_imports.oid, p_imports.mat2a_import_id]))[2] AS mat2a_import_id, 
          MAX(mat2a_annee) AS mat2a_annee, 
          MAX(mat2a_mois) AS mat2a_mois,
  	MAX(finess) AS import_finess
      FROM 
          pmsi.p_imports
          JOIN pmsi.p_mat2a_import ON p_imports.mat2a_import_id = p_mat2a_import.oid
      WHERE 1=1
          AND date_fin BETWEEN '20150101' AND '20201231'
          AND mat2a_import_id <> 0
          AND etat = 'G'
          AND p_imports.oid IN (SELECT DISTINCT import_id FROM pmsi.p_rss WHERE etat = '')
      HAVING MAX(p_imports.oid) IS NOT NULL;
  
  
      -- Est-ce qu'il y a une limitation des prestations SC/SI ?
      SELECT
          MAX(base.cti_to_number(p_mat2a_data.data_mat2a[3]))
      FROM 
          pmsi.p_mat2a_data
          JOIN w_imports ON w_imports.mat2a_import_id = p_mat2a_data.mat2a_import_id
      WHERE 1=1
          AND line_type IN ('D','F')
          AND file_code = 'T1V1SV'
          AND data_mat2a[1] LIKE '%suppression des SI/SC en cas de limitation%'
      INTO v_montant_limitation;
  
      IF v_montant_limitation > 0 THEN
          -- Récuperation des ecarts à ventiler depuis le tableau OVALIDE
          SELECT
               base.cti_to_number(p_mat2a_data.data_cti[4]) - base.cti_to_number(p_mat2a_data.data_mat2a[4])
              ,base.cti_to_number(p_mat2a_data.data_cti[5]) - base.cti_to_number(p_mat2a_data.data_mat2a[5])
              ,base.cti_to_number(p_mat2a_data.data_cti[6]) - base.cti_to_number(p_mat2a_data.data_mat2a[6])
          FROM 
              pmsi.p_mat2a_data
              JOIN w_imports ON w_imports.mat2a_import_id = p_mat2a_data.mat2a_import_id
          WHERE 1=1
              AND line_type IN ('D','F')
              AND file_code = 'T1V1RAV'
              AND data_mat2a[1] LIKE '%surveillance continue validés%'
          INTO v_ecart_br_ht, v_ecart_br, v_ecart_remb;
  
          -- Nombre de prestations SRC facturees
          SELECT
              SUM(nombre)
          FROM    
              pmsi.p_rsf_detail
              JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id
              JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
              JOIN w_imports ON w_imports.import_id = p_rss.import_id
          WHERE 1=1
              AND p_rsf_detail.est_ligne_rss = '1'
              AND p_rss.traitement_epmsi = '30'
              AND t_prestations.code = 'SRC'
          INTO v_nb_src_factures;
          
          -- Nombre de SRC autorises
          SELECT 
              sum(date_part('doy',(((mat2a_annee * 100 + mat2a_mois)::text || '01')::timestamp + interval '1 month' - interval '1 day')::date) * nb_lits)::numeric AS nb_max
          FROM 
              pmsi.t_unites_medicales
              JOIN w_imports ON w_imports.import_finess = t_unites_medicales.finess_geographique
          WHERE type_autorisation LIKE '03%'
          INTO v_nb_src_autorises;
  
          -- Si effectivement plus de SRC factures par rapport aux SRC autorises
          -- On cree une prestation fictive qui ventilera les decotes sur certains sejours
          IF v_nb_src_factures > v_nb_src_autorises THEN
          
              -- Suppression des prestations de limitation precedemment creees
              DELETE FROM pmsi.p_rsf_detail
              USING
                   pmsi.p_rss
                  ,pmsi.t_prestations
                  ,w_imports
              WHERE 1=1
                  AND p_rss.oid = p_rsf_detail.rss_id
                  AND t_prestations.oid = p_rsf_detail.prestation_id
                  AND t_prestations.code = 'LIM_SRC'
                  AND p_rss.import_id = w_imports.import_id;
              
              -- Ajout des lignes de facture
              -- Sur les sejours dont le nombre cumule (classe par date de sortie) de prestations
              -- depasse le maximun autorise
              INSERT INTO pmsi.p_rsf_detail (
                  rss_id
                  ,prestation_id
                  ,prix_unitaire
                  ,base_remboursement_sauf_transition
                  ,base_remboursement
                  ,date_debut
                  ,date_fin
                  ,finess
                  ,no_rss
                  ,sejour_facture
                  ,sejour_remboursable
                  ,taux_remboursement
                  ,coefficient_geo
                  ,coefficient_mco
                  ,coefficient_pacte_resp
                  ,coefficient
                  ,nombre
              )
              WITH w_rsf AS (
                  SELECT
                       p_rsf_detail.rss_id
                      ,p_rss.no_rss
                      ,p_rss.date_entree
                      ,p_rss.date_sortie
                      ,p_rss.finess
                      ,max(coefficient_geo) OVER() AS coefficient_geo
                      ,min(coefficient_mco) OVER() AS coefficient_mco
                      ,min(coefficient_pacte_resp) OVER() AS coefficient_pacte_resp
                      ,sum(nombre) over (PARTITION BY t_prestations.code ORDER BY p_rsf_detail.nombre DESC, p_rsf_detail.date_fin, p_rsf_detail.no_rss, p_rsf_detail.unite_medicale_id) AS cumul
                  FROM
                      temp.p_rsf_detail
                      JOIN temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                      JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                      JOIN pmsi.t_unites_medicales ON t_unites_medicales.oid = p_rsf_detail.unite_medicale_id 
                      JOIN w_imports ON w_imports.import_id = p_rss.import_id
                  WHERE 1=1
                      AND p_rsf_detail.est_ligne_rss = '1'
                      AND t_prestations.code IN ('SRC')
                      AND p_rss.traitement_epmsi = '30'
                      AND p_rsf_detail.base_remboursement > 0
              ),  w_select AS (
                  SELECT 
                       w_rsf.rss_id
                      ,w_rsf.date_entree
                      ,w_rsf.date_sortie
                      ,w_rsf.finess
                      ,w_rsf.no_rss
                      ,w_rsf.coefficient_geo
                      ,w_rsf.coefficient_mco
                      ,w_rsf.coefficient_pacte_resp
                      ,count(*) OVER() AS nb_rss
                  FROM
                      w_rsf
                  WHERE 1=1
                      AND cumul > v_nb_src_autorises
              )
              SELECT
                   w_select.rss_id
                  ,t_prestations.oid AS prestatation_id
                  ,0 - round(v_ecart_br_ht / w_select.nb_rss, 2) AS prix_unitaire
                  ,0 - round(v_ecart_br_ht / w_select.nb_rss, 2) as base_remboursement_sauf_transition
                  ,0 - round(v_ecart_br / w_select.nb_rss, 2) AS base_remboursement
                  ,w_select.date_entree AS date_debut
                  ,w_select.date_sortie AS date_fin
                  ,w_select.finess
                  ,w_select.no_rss
                  ,0 - round(v_ecart_br / w_select.nb_rss, 2) AS sejour_facture
                  ,0 - round(v_ecart_remb / w_select.nb_rss, 2) AS sejour_remboursable
                  ,100 AS taux_remboursement
                  ,w_select.coefficient_geo
                  ,w_select.coefficient_mco
                  ,w_select.coefficient_pacte_resp
                  ,1 AS coefficient
                  ,-1 AS nombre
              FROM
                  w_select, pmsi.t_prestations
              WHERE 1=1
                  AND t_prestations.code = 'LIM_SRC';
                  
              -- Mise à jour du tableau OVALIDE 1.V.1.RAV
              WITH w_update as (
                  SELECT
                      COALESCE(SUM(p_rsf_detail.base_remboursement), 0) as w_br,
                      COALESCE(SUM(p_rsf_detail.base_remboursement_sauf_transition), 0) as w_brht,
                      COALESCE(SUM(p_rsf_detail.sejour_remboursable), 0) as w_remb
                  FROM
                      pmsi.p_rsf_detail
                      JOIN temp.p_rss ON p_rss.oid = p_rsf_detail.rss_id
                      JOIN w_imports ON w_imports.import_id = p_rss.import_id
                      JOIN pmsi.t_prestations ON t_prestations.oid = p_rsf_detail.prestation_id
                  WHERE
                      t_prestations.code = 'LIM_SRC'
              )
              UPDATE pmsi.p_mat2a_data SET
                   data_cti[4] = base.cti_to_number(data_cti[4]) + w_br
                  ,data_cti[5] = base.cti_to_number(data_cti[5]) + w_brht
                  ,data_cti[6] = base.cti_to_number(data_cti[6]) + w_remb
              FROM 
                  w_imports, w_update
              WHERE 1=1
                  AND w_imports.mat2a_import_id = p_mat2a_data.mat2a_import_id
                  AND line_type IN ('D','F')
                  AND file_code = 'T1V1RAV'
                  AND (data_mat2a[1] ILIKE '%surveillance continue validés%'OR
                       data_mat2a[1] ILIKE '%Total valorisation%');
  
              v_return_string = 'OK';
          ELSE
              v_return_string = 'SRC factures inferieurs au Nombre max de SRC autorises';
          END IF;
      ELSE
          v_return_string = 'Pas de limitation detectee dans le tableau T1V1SV';
      END IF;    
      
      RETURN v_return_string;
  END;