--
--


SELECT pg_catalog.set_config('search_path', '', false);

--
-- Name: r477; Type: SCHEMA; Schema: -; Owner: developer_rep
--

CREATE SCHEMA r477;


ALTER SCHEMA r477 OWNER TO developer_rep;

--
-- Name: evnps_group_calc(bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.evnps_group_calc(p_evnsection_pid bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

DECLARE
  rec RECORD;

BEGIN
  CREATE TEMP TABLE tEvnGroup (
    rowEvn INT,
    evnsection_id BIGINT,
    diaggroup_code VARCHAR,
    diag_code VARCHAR,
    PayType_id BIGINT,
    MesOld_Num VARCHAR,
    disDate INT,
    mestariff_value FLOAT,
    evnsection_setdt TIMESTAMP WITHOUT TIME ZONE
  ) ON COMMIT DROP;

  INSERT INTO tEvnGroup (rowEvn, evnsection_id, diaggroup_code, diag_code, PayType_id, MesOld_Num, disDate, mestariff_value, evnsection_setdt)
  SELECT EvnSection_Index, evnsection_id, diaggroup_code, diag_code, PayType_id, MesOld_Num, DATE_PART('day', EvnSection_disDate - EvnSection_setDate), COALESCE(mestariff_value, 0.0), evnsection_setdt
    FROM r477.p_getevnsectiongroup(p_evnsection_pid);

  UPDATE EvnSection
     SET EvnSection_IndexNum = NULL
       , EvnSection_IsWillPaid = NULL
   WHERE Evn_pid = p_evnsection_pid;

  FOR rec IN (SELECT evnsection_id
                   , EvnSection_IndexNum
                   , mestariff_value
                   , evnsection_setdt
                   , ROW_NUMBER() OVER (PARTITION BY EvnSection_IndexNum ORDER BY mestariff_value DESC, evnsection_setdt DESC) rowPaid
                FROM (SELECT t1.evnsection_id
                           , t1.mestariff_value
                           , t1.evnsection_setdt
                           , DENSE_RANK() OVER (ORDER BY t1.diaggroup_code,
                                                         t1.PayType_id,
                                                         CASE WHEN (t2.MesOld_Num = 'st02.001' AND t2.disDate >= 6 OR t2.MesOld_Num = 'st02.001' AND t2.disDate >= 2 AND t2.diag_code IN ('O14.1', 'O34.2', 'O36.3', 'O36.4', 'O42.2')) AND t1.MesOld_Num IN ('st02.003', 'st02.004') THEN 1
                                                              WHEN (t1.MesOld_Num = 'st02.001' AND t1.disDate >= 6 OR t1.MesOld_Num = 'st02.001' AND t1.disDate >= 2 AND t1.diag_code IN ('O14.1', 'O34.2', 'O36.3', 'O36.4', 'O42.2')) AND t3.MesOld_Num IN ('st02.003', 'st02.004') THEN 2
                                                         END
                                               ) EvnSection_IndexNum
                        FROM tEvnGroup t1
                        LEFT JOIN tEvnGroup t2 ON t2.rowEvn = t1.rowEvn - 1
                        LEFT JOIN tEvnGroup t3 ON t3.rowEvn = t1.rowEvn + 1) A)
  LOOP
    UPDATE EvnSection
       SET EvnSection_IndexNum = rec.EvnSection_IndexNum
         , EvnSection_IsWillPaid = CASE WHEN rec.rowPaid = 1 THEN 2 ELSE 1 END
     WHERE Evn_id = rec.EvnSection_id;
  END LOOP;

END;
$$;


ALTER FUNCTION r477.evnps_group_calc(p_evnsection_pid bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: evnps_ksg_calc(jsonb); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.evnps_ksg_calc(p_json jsonb) RETURNS TABLE(mes_tid bigint, mes_sid bigint, mes_kid bigint, mestariff_id bigint, mesolduslugacomplex_id bigint, error_message text)
    LANGUAGE plpgsql
    AS $_$

DECLARE
  _EvnSection_id BIGINT;
  _EvnSection_pid BIGINT;
  _EvnSection_setDate TIMESTAMP;
  _EvnSection_disDate TIMESTAMP;
  _Person_id BIGINT;
  _PayType_id BIGINT;
  _Diag_id BIGINT;
  _LpuSection_id BIGINT;
  _LpuSectionProfile_id BIGINT;
  _LpuSectionBedProfile_id BIGINT;
  _LpuUnitType_id BIGINT;
  _HTMedicalCareClass_id BIGINT;
  _DiagPriem_id BIGINT;
  _RehabScale_id BIGINT;
  _CureResult_id BIGINT;
  _EvnSection_SofaScalePoints BIGINT;
  _EvnSection_IsAdultEscort BIGINT;
  _DrugTherapyScheme_ids BIGINT [];
  _MesDop_ids BIGINT [];

  rec RECORD;
  _paytype_oms_id BIGINT;
  _kd INTEGER;
  _Person_Age INTEGER;
  _Person_AgeDays BIGINT;
  _Sex_id INTEGER;
  _BirthToday INTEGER;
  _LpuSectionProfile_code VARCHAR;
  _ivl_dur INTEGER;
  _poliSoputExist INTEGER;
  _PolyTrauma_Code VARCHAR;
  _PolyTrauma_diag BIGINT;
  _totalFract INTEGER;
  _KSGFromPolyTrauma BOOLEAN;
  _mesoldNum VARCHAR;
  _hasZNOCrit INTEGER;
  _maxKSG BIGINT;
  _x BIGINT;
  _region BIGINT;
 
  _evnsection_id_arr BIGINT[];

BEGIN

  DROP TABLE IF EXISTS tDiagCrit,tGroup,tUsluga,tDiag,tKSG_polytr,tFrac,tDrug,tMesDop,tWork;
  CREATE TEMP TABLE tDiagCrit (
    diag_id BIGINT
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tGroup (
    EvnSection_id BIGINT,
    EvnSection_Index BIGINT,
    kd INTEGER
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tUsluga (
    UslugaComplex_id BIGINT,
    UslugaComplex_code VARCHAR,
    UslugaCategory_id BIGINT,
    setDt TIMESTAMP,
    disDt TIMESTAMP
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tDiag (
    diag_id BIGINT,
    Diag_Code VARCHAR,
    DiagSetClass_id INTEGER
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tKSG_polytr (
    Mes_Code VARCHAR,
    Mes_Name VARCHAR,
    MesOld_Num VARCHAR,
    Mes_id BIGINT,
    MesOldUslugaComplex_id BIGINT,
    MesTariff_Value FLOAT,
    ItogCoeff FLOAT,
    MesTariff_id BIGINT,
    MesType_id BIGINT,
    KPG FLOAT,
    Mes_kid BIGINT
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tFrac (
    UslugaComplex_id BIGINT,
    frac_count INTEGER
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tDrug (
    DrugTherapyScheme_id BIGINT
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tMesDop (
    MesDop_id BIGINT
  ) ON COMMIT DROP;

  CREATE TEMP TABLE tWork (
    MesOldUslugaComplex_id BIGINT,
    UslugaComplex_id BIGINT,
    Mes_Code VARCHAR,
    Mes_Name VARCHAR,
    MesOld_Num VARCHAR,
    Mes_id BIGINT,
    MesTariff_Value FLOAT,
    ItogCoeff FLOAT,
    MesTariff_id BIGINT,
    MesType_id BIGINT,
    Diag_nid BIGINT,
    Diag_oid BIGINT,
    KPG BIGINT,
    Mes_kid BIGINT,
    frac_count INTEGER,
    Diag_id BIGINT,
    DrugTherapyScheme_id BIGINT,
    MesOldUslugaComplex_FracFrom INTEGER,
    MesOldUslugaComplex_FracTo INTEGER,
    MesAgeGroup_id BIGINT,
    Sex_id BIGINT,
    MesOldUslugaComplex_Duration INTEGER,
    MesOldUslugaComplex_DurationTo INTEGER,
    MesOldUslugaComplex_SofaScalePoints INTEGER,
    MesOldUslugaComplex_IVLHours INTEGER,
    MesDop_id BIGINT,
    hasDopCriteria INTEGER,
    Mes_tid BIGINT,
    Mes_sid BIGINT
  ) ON COMMIT DROP;

  _region = dbo.getregion();

  _evnsection_pid := NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_pid', '""', ''), 'null'), '') :: BIGINT;
  _evnsection_id := NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_id', '""', ''), 'null'), '') :: BIGINT;
  _evnsection_setdate := NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_setdt', '""', ''), 'null'), '') :: TIMESTAMP WITHOUT TIME ZONE;
  _evnsection_disdate := COALESCE(NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_disdt', '""', ''), 'null'), '') :: TIMESTAMP WITHOUT TIME ZONE, CURRENT_TIMESTAMP);
  _person_id := NULLIF(NULLIF(REPLACE(p_json ->> 'person_id', '""', ''), 'null'), '') :: BIGINT;
  _diag_id := NULLIF(NULLIF(REPLACE(p_json ->> 'diag_id', '""', ''), 'null'), '') :: BIGINT;
  _paytype_id := NULLIF(NULLIF(REPLACE(p_json ->> 'paytype_id', '""', ''), 'null'), '') :: BIGINT;

  _lpusection_id := NULLIF(NULLIF(REPLACE(p_json ->> 'lpusection_id', '""', ''), 'null'), '') :: BIGINT;
  _lpusectionprofile_id := NULLIF(NULLIF(REPLACE(p_json ->> 'lpusectionprofile_id', '""', ''), 'null'), '') :: BIGINT;
  _lpusectionbedprofile_id := NULLIF(NULLIF(REPLACE(p_json ->> 'lpusectionbedprofile_id', '""', ''), 'null'), '') :: BIGINT;
  _LpuUnitType_id := NULLIF(NULLIF(REPLACE(p_json ->> 'lpuunittype_id', '""', ''), 'null'), '') :: BIGINT;

  _HTMedicalCareClass_id := NULLIF(NULLIF(REPLACE(p_json ->> 'htmedicalcareclass_id', '""', ''), 'null'), '') :: BIGINT;
  _DiagPriem_id := NULLIF(NULLIF(REPLACE(p_json ->> 'diagpriem_id', '""', ''), 'null'), '') :: BIGINT;
  _RehabScale_id := NULLIF(NULLIF(REPLACE(p_json ->> 'rehabscale_id', '""', ''), 'null'), '') :: BIGINT;
  _CureResult_id := NULLIF(NULLIF(REPLACE(p_json ->> 'cureresult_id', '""', ''), 'null'), '') :: BIGINT;
  _EvnSection_SofaScalePoints := NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_sofascalepoints', '""', ''), 'null'), '') :: BIGINT;
  _EvnSection_IsAdultEscort := NULLIF(NULLIF(REPLACE(p_json ->> 'evnsection_isadultescort', '""', ''), 'null'), '') :: BIGINT;

  _DrugTherapyScheme_ids = NULLIF(NULLIF(REPLACE(REPLACE(REPLACE(p_json ->> 'drugtherapyscheme_ids', '""', ''), '[', '{'), ']', '}'), 'null'), '') :: BIGINT [];
  _MesDop_ids = NULLIF(NULLIF(REPLACE(REPLACE(REPLACE(p_json ->> 'mesdop_ids', '""', ''), '[', '{'), ']', '}'), 'null'), '') :: BIGINT [];

  IF CARDINALITY(_DrugTherapyScheme_ids) > 0 THEN
    FOREACH _x IN ARRAY _DrugTherapyScheme_ids
    LOOP
      INSERT INTO tDrug (DrugTherapyScheme_id) VALUES (_x);
    END LOOP;
  END IF;

  IF CARDINALITY(_MesDop_ids) > 0 THEN
    FOREACH _x IN ARRAY _MesDop_ids
    LOOP
      INSERT INTO tMesDop (MesDop_id) VALUES (_x);
    END LOOP;
  END IF;


  -- вид оплаты ОМС
  SELECT paytype_id
    INTO _paytype_oms_id
    FROM v_paytype
   WHERE paytype_sysnick = 'oms';

  -- длительность движения
  _kd = DATE_PART('day', _evnsection_disdate - _EvnSection_setDate);
  RAISE NOTICE '_kd = %, _evnsection_disdate = %', _kd, _evnsection_disdate;


  -- данные пациента
  SELECT dbo.AgeTFOMS(PS.Person_BirthDay, _EvnSection_setDate :: DATE) Person_Age,
         datediff('day', PS.Person_BirthDay, _EvnSection_setDate :: DATE) Person_AgeDays,
         PS.Sex_id Sex_id,
         CASE WHEN DATE_PART('month', PS.Person_BirthDay) = DATE_PART('month', _EvnSection_setDate :: DATE)
               AND DATE_PART('day', PS.Person_BirthDay) = DATE_PART('day', _EvnSection_setDate :: DATE)
           THEN 1
           ELSE 0
         END BirthToday
    INTO _Person_Age,
         _Person_AgeDays,
         _Sex_id,
         _BirthToday
    FROM v_PersonState PS
   WHERE Person_id = _Person_id;


  -- если не найдено, возвращаем ошибку
  IF _Person_Age IS NULL THEN
      RETURN QUERY (SELECT
          NULL :: BIGINT,
          NULL :: BIGINT,
          NULL :: BIGINT,
          NULL :: BIGINT,
          NULL :: BIGINT,
          'Ошибка получения данных по человеку' :: TEXT);
  END IF;

  RAISE NOTICE '_Person_Age = %, days = %', _Person_Age, _Person_AgeDays;


  -- код профиля
  SELECT LpuSectionProfile_code
    INTO _LpuSectionProfile_code
    FROM v_LpuSectionProfile
   WHERE LpuSectionProfile_id = _LpuSectionProfile_id;

  -- движения подходящей группы
  IF _LpuSectionProfile_code != '158' THEN -- реабилитация
    INSERT INTO tGroup
    SELECT * FROM r477.f_getEvnSectionGroup(_EvnSection_id, _EvnSection_pid, _paytype_id, _diag_id);
  END IF;

  FOR rec IN (SELECT * FROM tGroup)
  LOOP
    RAISE NOTICE 'EvnSection_id = %, EvnSection_Index = %, kd = %', rec.EvnSection_id, rec.EvnSection_Index, rec.kd;
  END LOOP;

   _evnsection_id_arr = ARRAY(SELECT evnsection_id FROM tGroup UNION SELECT _EvnSection_id);

      -- услуги группы и этого движения
  INSERT INTO tUsluga
  SELECT uc.UslugaComplex_id,
         uc.UslugaComplex_Code,
         uc.UslugaCategory_id,
         eu.EvnUsluga_setDT,
         eu.EvnUsluga_disDT
    FROM v_evnUsluga eu
    JOIN v_UslugaComplex uc ON uc.UslugaComplex_id = eu.UslugaComplex_id
                           AND COALESCE(UslugaComplex_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                           AND COALESCE(UslugaComplex_endDT, _EvnSection_disDate) >= _EvnSection_disDate
   WHERE --(eu.EvnUsluga_pid = _EvnSection_id OR eu.EvnUsluga_pid IN (SELECT evnsection_id FROM tGroup))
     eu.evnusluga_pid = ANY(_evnsection_id_arr)
     AND eu.paytype_id = _paytype_oms_id
     AND eu.EvnUsluga_setDT IS NOT NULL
     AND LOWER(eu.EvnClass_SysNick) IN ('evnuslugacommon', 'evnuslugaoper', 'evnuslugapar', 'evnuslugastom');

  FOR rec IN (SELECT * FROM tUsluga)
  LOOP
    RAISE NOTICE 'UslugaComplex_id = %, UslugaComplex_Code = %', rec.UslugaComplex_id, rec.UslugaComplex_Code;
  END LOOP;


  -- общая длительность ИВЛ
  SELECT SUM(DATE_PART('day', tUsluga.disDT - tUsluga.setDT) * 24 + DATE_PART('hour', tUsluga.disDT - tUsluga.setDT))
    INTO _ivl_dur
    FROM tUsluga
    JOIN v_UslugaCategory ucat ON ucat.UslugaCategory_id = tUsluga.UslugaCategory_id
   WHERE tUsluga.disDT IS NOT NULL
     AND LOWER(ucat.UslugaCategory_SysNick) = 'gost2011'
     AND EXISTS (SELECT uca.UslugaComplexAttribute_id
                   FROM v_UslugaComplexAttribute uca
                  WHERE uca.UslugaComplex_id = tUsluga.UslugaComplex_id
                    AND uca.UslugaComplexAttributeType_id = 101  -- ИВЛ
                  LIMIT 1);

  -- диагнозы
  INSERT INTO tDiag
  (SELECT DISTINCT d.Diag_id,
                   d.Diag_Code,
                   edps.DiagSetClass_id
     FROM v_EvnDiagPS edps
     JOIN v_Diag d ON d.Diag_id = edps.Diag_id
                  AND COALESCE(Diag_begDate, _EvnSection_disDate) <= _EvnSection_disDate
                  AND COALESCE(Diag_endDate, _EvnSection_disDate) >= _EvnSection_disDate
    WHERE edps.DiagSetClass_id IN (2, 3)
      --AND (edps.EvnDiagPS_pid = _EvnSection_id OR edps.EvnDiagPS_pid IN (SELECT evnsection_id FROM tGroup))
      AND edps.EvnDiagPS_pid = ANY(_evnsection_id_arr)

   UNION

   SELECT d.Diag_id,
          d.Diag_Code,
          1
     FROM v_Diag d
    WHERE d.diag_id = _diag_id);

  FOR rec IN (SELECT * FROM tDiag)
  LOOP
    RAISE NOTICE 'Diag_id = %, Diag_Code = %, DiagSetClass_id = %', rec.Diag_id, rec.Diag_Code, rec.DiagSetClass_id;
  END LOOP;


  --region ПОЛИТРАВМА
  SELECT COUNT(*)
    INTO _poliSoputExist
    FROM tDiag
   WHERE DiagSetClass_id IN (2, 3)
     AND diag_code IN ('J94.2', 'J94.8', 'J94.9', 'J93', 'J93.0', 'J93.1',
                       'J93.8', 'J93.9', 'J96.0', 'N17', 'N17.0', 'N17.1',
                       'N17.2', 'N17.8', 'N17.9', 'T79.4', 'R57.1', 'R57.8');

  IF _poliSoputExist > 0
 AND _LpuUnitType_id NOT IN (6, 7, 9) THEN
    SELECT pt.PolyTrauma_Code,
           SOPUT.Diag_id
      INTO _PolyTrauma_Code,
           _PolyTrauma_diag
      FROM v_PolyTrauma pt
      JOIN tDiag d ON pt.Diag_id = d.diag_id
      LEFT JOIN LATERAL (SELECT pt2.Diag_id, tdiag.diag_code
                           FROM v_PolyTrauma pt2
                           JOIN tDiag ON pt2.Diag_id = tDiag.diag_id
                                     AND tDiag.DiagSetClass_id IN (2, 3)
                          WHERE pt2.PolyTrauma_Code <> pt.PolyTrauma_Code
                            AND COALESCE(pt2.PolyTrauma_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                            AND COALESCE(pt2.PolyTrauma_endDT, _EvnSection_disDate) >= _EvnSection_disDate
                          LIMIT 1) SOPUT ON TRUE
     WHERE COALESCE(pt.PolyTrauma_begDT, _EvnSection_disDate) <= _EvnSection_disDate
       AND COALESCE(pt.PolyTrauma_endDT, _EvnSection_disDate) >= _EvnSection_disDate
     ORDER BY CASE WHEN SOPUT.Diag_id IS NOT NULL THEN 0 ELSE 1 END,  -- в первую очередь с заполненным диагнозом
              CASE WHEN pt.PolyTrauma_Code = 7 THEN 0 ELSE 1 END, -- в первую очередь с кодом 7
              CASE WHEN SOPUT.diag_code IN ('J94.2', 'J94.8', 'J94.9', 'J93', 'J93.0', 'J93.1',
                                            'J93.8', 'J93.9', 'J96.0', 'N17', 'N17.0', 'N17.1',
                                            'N17.2', 'N17.8', 'N17.9', 'T79.4', 'R57.1', 'R57.8') THEN 0 ELSE 1 END
     LIMIT 1;

    IF _PolyTrauma_Code = '7' OR _PolyTrauma_diag > 0 THEN
      INSERT INTO tKSG_polytr
      SELECT mo.Mes_Code,
             mo.Mes_Name,
             mo.MesOld_Num,
             mo.Mes_id,
             NULL MesOldUslugaComplex_id,
             mt.MesTariff_Value,
             COALESCE(moc.MesOldCoeff_Coeff, 1) * mt.MesTariff_Value ItogCoeff,
             mt.MesTariff_id,
             mo.MesType_id,
             NULL KPG,
             NULL Mes_kid
        FROM v_MesOld mo
        LEFT JOIN v_MesTariff mt ON mt.Mes_id = mo.Mes_id -- Коэффициент КСГ
                                AND COALESCE(mt.MesTariff_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                                AND COALESCE(mt.MesTariff_endDT, _EvnSection_disDate) >= _EvnSection_disDate
        LEFT JOIN dbo.v_MesOldCoeff moc ON moc.Mes_id = mo.Mes_id -- Управленческий коэффициент
                                       AND COALESCE(moc.mesoldcoeff_begdt, _EvnSection_disDate) <= _EvnSection_disDate
                                       AND COALESCE(moc.mesoldcoeff_enddt, _EvnSection_disDate) >= _EvnSection_disDate
       WHERE mo.MesOld_Num = 'st29.007'
         AND mo.MesType_id IN (10, 14) -- для КС
         AND COALESCE(mo.Mes_begDT, _EvnSection_disDate) <= _EvnSection_disDate
         AND COALESCE(mo.Mes_endDT, _EvnSection_disDate) >= _EvnSection_disDate
       LIMIT 1;

    RETURN QUERY (SELECT tKSG_polytr.mes_id mes_tid,
                         NULL :: BIGINT mes_sid,
                         tKSG_polytr.mes_kid,
                         tKSG_polytr.MesTariff_id,
                         tKSG_polytr.MesOldUslugaComplex_id,
                         NULL :: TEXT
                    FROM tKSG_polytr);
    END IF;
  END IF;
  --endregion ПОЛИТРАВМА

  -- кол-во фракций
  INSERT INTO tFrac
  SELECT onkousl.UslugaComplex_id UslugaComplex_id,
         SUM(COALESCE(onkousl.CountFractionRT, 0)) CountFractionRT
    FROM (SELECT UslugaComplex_id,
                 EvnUslugaOnkoBeam_CountFractionRT CountFractionRT
            FROM v_EvnUslugaOnkoBeam
           WHERE --EvnUslugaOnkoBeam_pid = _EvnSection_id OR EvnUslugaOnkoBeam_pid IN (SELECT evnsection_id FROM tGroup)
            EvnUslugaOnkoBeam_pid = ANY(_evnsection_id_arr)

          UNION ALL

          SELECT UslugaComplex_id,
                 EvnUslugaOnkoGormun_CountFractionRT CountFractionRT
            FROM v_EvnUslugaOnkoGormun
           WHERE --EvnUslugaOnkoGormun_pid = _EvnSection_id OR EvnUslugaOnkoGormun_pid IN (SELECT evnsection_id FROM tGroup)
            EvnUslugaOnkoGormun_pid = ANY(_evnsection_id_arr)

          UNION ALL

          SELECT UslugaComplex_id,
                 EvnUslugaOnkoChemBeam_CountFractionRT CountFractionRT
            FROM v_EvnUslugaOnkoChemBeam
           WHERE --EvnUslugaOnkoChemBeam_pid = _EvnSection_id OR EvnUslugaOnkoChemBeam_pid IN (SELECT evnsection_id FROM tGroup)
            EvnUslugaOnkoChemBeam_pid = ANY(_evnsection_id_arr)
          ) onkousl
   GROUP BY UslugaComplex_id;

  --диагноз по доп.критериям
  INSERT INTO tDiagCrit
  SELECT diag_id
    FROM v_diag
   WHERE diag_code in ('L08.0', 'L26', 'L27.0', 'L27.2')
     AND COALESCE(diag_begdate, _EvnSection_disDate) <= _EvnSection_disDate
     AND COALESCE(diag_enddate, _EvnSection_disDate) >= _EvnSection_disDate;


  --region поиск КСГ
  IF _KSGFromPolyTrauma IS NULL THEN
    FOR rec IN
    (SELECT DISTINCT
                      mu.MesOldUslugaComplex_id,
                      mu.UslugaComplex_id,
                      mo.Mes_Code,
                      mo.Mes_Name,
                      mo.MesOld_Num,
                      mo.Mes_id,
                      mt.MesTariff_Value,
                      COALESCE(moc.MesOldCoeff_Coeff, 1) * mt.MesTariff_Value ItogCoeff,
                      mt.MesTariff_id,
                      mo.MesType_id,
                      mu.Diag_nid,
                      mu.Diag_oid,
                      NULL KPG,
                      NULL Mes_kid,
                      fr.frac_count,
                      mu.Diag_id,
                      mu.DrugTherapyScheme_id,
                      mu.MesOldUslugaComplex_FracFrom,
                      mu.MesOldUslugaComplex_FracTo,
                      mu.MesAgeGroup_id,
                      mu.Sex_id,
                      mu.MesOldUslugaComplex_Duration,
                      mu.MesOldUslugaComplex_DurationTo,
                      mu.MesOldUslugaComplex_SofaScalePoints,
                      mu.MesOldUslugaComplex_IVLHours,
                      mu.MesDop_id,
            CASE WHEN mu.RehabScale_id IS NOT NULL THEN 1
                 WHEN mu.UslugaComplex_aid IS NOT NULL AND mu.UslugaComplex_bid IS NOT NULL THEN 1
                 WHEN mu.Diag_id IN (6363, 6424, 6426, 11628) AND mu.MesAgeGroup_id = 4 THEN 1
                 WHEN mu.MesOldUslugaComplex_DurationTo = 3 THEN 1
                 WHEN _Person_AgeDays < 28 AND dc.diag_id IS NOT NULL THEN 1
                 WHEN mo.Mes_Code = '37' AND ml.Mes_sid IS NOT NULL THEN 1
                 ELSE 0 END hasDopCriteria,
            CASE WHEN mu.UslugaComplex_id IS NULL THEN mo.Mes_id END Mes_tid,
            CASE WHEN mu.UslugaComplex_id IS NOT NULL THEN mo.Mes_id END Mes_sid
                    FROM v_MesOldUslugaComplex mu
       JOIN v_MesOld mo ON mo.Mes_id = mu.Mes_id
                       AND COALESCE(mo.Mes_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                       AND COALESCE(mo.Mes_endDT, _EvnSection_disDate) >= _EvnSection_disDate
       LEFT JOIN tFrac fr ON fr.UslugaComplex_id = mu.UslugaComplex_id
       LEFT JOIN v_MesTariff mt ON mt.Mes_id = mo.Mes_id -- Коэффициент КСГ
                               AND COALESCE(mt.MesTariff_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                               AND COALESCE(mt.MesTariff_endDT, _EvnSection_disDate) >= _EvnSection_disDate
       LEFT JOIN MesOldCoeff moc ON moc.Mes_id = mo.Mes_id -- Управленческий коэффициент
                                AND (moc.region_id = _region OR moc.region_id IS NULL)
                    AND COALESCE(moc.mesoldcoeff_begdt, _EvnSection_disDate) <= _EvnSection_disDate
                    AND COALESCE(moc.mesoldcoeff_enddt, _EvnSection_disDate) >= _EvnSection_disDate
       LEFT JOIN tDiagCrit dc ON dc.diag_id = mu.diag_id
       LEFT JOIN v_MesLink ml ON ml.Mes_sid = mo.Mes_id
                             AND ml.MesLinkType_id = 1
                             AND COALESCE(ml.meslink_begdt, _EvnSection_disDate) <= _EvnSection_disDate
                             AND COALESCE(ml.meslink_enddt, _EvnSection_disDate) >= _EvnSection_disDate
      WHERE (mu.Diag_id = _Diag_id OR mu.Diag_id IS NULL)

        AND (mu.UslugaComplex_aid IS NULL OR mu.UslugaComplex_aid IN (SELECT UslugaComplex_id FROM tUsluga))
        AND (mu.UslugaComplex_bid IS NULL OR mu.UslugaComplex_bid IN (SELECT UslugaComplex_id FROM tUsluga))
        AND (mu.UslugaComplex_id IS NULL OR mu.UslugaComplex_id IN (SELECT UslugaComplex_id FROM tUsluga))

        AND (mu.Diag_nid IS NULL OR mu.Diag_nid IN (SELECT diag_id FROM tDiag WHERE DiagSetClass_id = 3))

        AND (mu.Diag_oid IS NULL OR mu.Diag_oid IN (SELECT diag_id FROM tDiag WHERE DiagSetClass_id = 2))

        AND (mu.Sex_id = _Sex_id OR mu.Sex_id IS NULL)

        AND ((_Person_Age >= 18 AND mu.MesAgeGroup_id = 1)
          OR (_Person_Age < 18 AND mu.MesAgeGroup_id = 2)
          OR (_Person_AgeDays > 28 AND mu.MesAgeGroup_id = 3)
          OR (_Person_AgeDays <= 28 AND mu.MesAgeGroup_id = 4) -- 1 от 0 до 28 дней включительно
          OR (_Person_Age < 18 AND mu.MesAgeGroup_id = 5) -- 4 от 0 дней до 18 лет НЕ включительно
          OR (_Person_Age >= 18 AND mu.MesAgeGroup_id = 6) -- 5 18 лет и старше
          OR (_Person_Age < 8 AND mu.MesAgeGroup_id = 7)
          OR (_Person_Age >= 8 AND mu.MesAgeGroup_id = 8)
          OR (_Person_AgeDays >= 29 AND _Person_AgeDays <= 90 AND mu.MesAgeGroup_id = 9) -- 2 от 29 до 90 дней включительно
          OR (_Person_AgeDays >= 91 AND _Person_Age < 1 AND mu.MesAgeGroup_id = 10) -- 3 от 91 дня до 1 года НЕ включительно
            --{$MesAgeGroup11Filter}
          OR (_Person_Age < 2 AND mu.MesAgeGroup_id = 11 AND _BirthToday = 0)
          OR (_Person_Age <= 2 AND mu.MesAgeGroup_id = 11 AND _BirthToday = 1)
          OR (mu.MesAgeGroup_id IS NULL))

        AND (mu.MesOldUslugaComplex_Duration <= _kd OR mu.MesOldUslugaComplex_Duration IS NULL)
        AND (mu.MesOldUslugaComplex_DurationTo >= _kd OR mu.MesOldUslugaComplex_DurationTo IS NULL)

        AND (mu.DrugTherapyScheme_id IN (SELECT DrugTherapyScheme_id FROM tDrug) OR mu.DrugTherapyScheme_id IS NULL)
        AND (mu.MesDop_id IN (SELECT mesdop_id FROM tMesDop) OR mu.MesDop_id IS NULL)
        AND (mu.RehabScale_id = _RehabScale_id OR mu.RehabScale_id IS NULL)
        AND (mu.MesOldUslugaComplex_SofaScalePoints <= _EvnSection_SofaScalePoints OR mu.MesOldUslugaComplex_SofaScalePoints IS NULL)
        AND (mu.mesolduslugacomplex_ivlhours NOT IN (1, 120) AND mu.MesOldUslugaComplex_IVLHours <= _ivl_dur
         OR mu.mesolduslugacomplex_ivlhours IN (1) AND _ivl_dur >= 120
         OR mu.mesolduslugacomplex_ivlhours IN (120) AND _ivl_dur < 120
         OR mu.MesOldUslugaComplex_IVLHours IS NULL)

        AND (mu.MesOldUslugaComplex_FracFrom <= fr.frac_count OR mu.MesOldUslugaComplex_FracFrom IS NULL AND fr.frac_count IS NULL)
        AND (mu.MesOldUslugaComplex_FracTo >= fr.frac_count OR mu.MesOldUslugaComplex_FracTo IS NULL AND fr.frac_count IS NULL)

                    AND COALESCE(mu.MesOldUslugaComplex_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                    AND COALESCE(mu.MesOldUslugaComplex_endDT, _EvnSection_disDate) >= _EvnSection_disDate

        AND (_LpuUnitType_id IN (6, 7, 9) AND mo.MesType_id IN (9, 13) AND COALESCE(mt.MesPayType_id, 9) = 9
          OR _LpuUnitType_id NOT IN (6, 7, 9) AND mo.MesType_id IN (10, 14) AND COALESCE(mt.MesPayType_id, 10) = 10)
      ORDER BY mu.Diag_id, mu.Diag_nid, mu.Diag_oid, mu.UslugaComplex_id
      )
      LOOP
      RAISE NOTICE 'diag = %, mes_num - %, agegr %, usl %, MesDop_id = %', rec.Diag_id, rec.MesOld_Num, rec.MesAgeGroup_id, rec.UslugaComplex_id, rec.MesDop_id;

      INSERT INTO tWork (MesOldUslugaComplex_id, UslugaComplex_id, Mes_Code, Mes_Name, MesOld_Num, Mes_id, MesTariff_Value, ItogCoeff, MesTariff_id, MesType_id
                       , Diag_nid, Diag_oid, KPG, Mes_kid, frac_count, Diag_id, DrugTherapyScheme_id, MesOldUslugaComplex_FracFrom, MesOldUslugaComplex_FracTo
                       , MesAgeGroup_id, Sex_id, MesOldUslugaComplex_Duration, MesOldUslugaComplex_DurationTo, MesOldUslugaComplex_SofaScalePoints, MesOldUslugaComplex_IVLHours
                       , MesDop_id, hasDopCriteria, Mes_tid, Mes_sid)
      VALUES (rec.MesOldUslugaComplex_id, rec.UslugaComplex_id, rec.Mes_Code, rec.Mes_Name, rec.MesOld_Num, rec.Mes_id, rec.MesTariff_Value, rec.ItogCoeff, rec.MesTariff_id, rec.MesType_id
            , rec.Diag_nid, rec.Diag_oid, rec.KPG :: BIGINT, rec.Mes_kid :: BIGINT, rec.frac_count, rec.Diag_id, rec.DrugTherapyScheme_id, rec.MesOldUslugaComplex_FracFrom, rec.MesOldUslugaComplex_FracTo
            , rec.MesAgeGroup_id, rec.Sex_id, rec.MesOldUslugaComplex_Duration, rec.MesOldUslugaComplex_DurationTo, rec.MesOldUslugaComplex_SofaScalePoints, rec.MesOldUslugaComplex_IVLHours
            , rec.MesDop_id, rec.hasDopCriteria, rec.Mes_tid, rec.Mes_sid);
      END LOOP;
  END IF;

  --регион. особенность группировки
  IF (SELECT COUNT(*) FROM tGroup) > 1 THEN
    FOR rec IN (WITH t AS (SELECT DISTINCT tWork.MesOld_Num, tWork.MesOldUslugaComplex_id, E.*, d.diag_code, d4.diag_code diaggroup_code
                             FROM tWork
                             LEFT JOIN v_diag d ON d.diag_id = tWork.diag_id
                             LEFT JOIN v_Diag d2 ON d2.Diag_id = d.Diag_pid
                             LEFT JOIN v_Diag d3 ON d3.Diag_id = d2.Diag_pid
                             LEFT JOIN v_Diag d4 ON d4.Diag_id = d3.Diag_pid
                             LEFT JOIN LATERAL (SELECT tGroup.EvnSection_Index, tGroup.kd, CASE WHEN _EvnSection_id = tGroup.evnsection_id THEN 1 END p_index
                                                  FROM tDiag
                                                  JOIN v_EvnDiagPS edps ON edps.diag_id = tDiag.diag_id
                                                  JOIN tGroup ON tGroup.evnsection_id = edps.EvnDiagPS_pid
                                                 WHERE edps.DiagSetClass_id IN (2, 3)
                                                   AND (tDiag.diag_id = tWork.diag_nid OR tDiag.diag_id = tWork.diag_oid)
                                                UNION
                                                SELECT tGroup.EvnSection_Index, tGroup.kd, 1 p_index
                                                  FROM tGroup
                                                 WHERE tGroup.evnsection_id = _EvnSection_id AND twork.diag_id = _diag_id
                                                UNION
                                                SELECT tGroup.EvnSection_Index, tGroup.kd, CASE WHEN _EvnSection_id = tGroup.evnsection_id THEN 1 END p_index
                                                  FROM tUsluga
                                                  JOIN v_evnUsluga eu ON eu.UslugaComplex_id = tUsluga.UslugaComplex_id
                                                  JOIN tGroup ON tGroup.evnsection_id = eu.EvnUsluga_pid
                                                 WHERE tUsluga.UslugaComplex_id = tWork.UslugaComplex_id
                                                ) E ON TRUE
                          )
                SELECT CASE WHEN (t2.MesOld_Num = 'st02.001' AND t2.kd >= 6 OR t2.MesOld_Num = 'st02.001' AND t2.kd >= 2 AND t2.diag_code IN ('O14.1', 'O34.2', 'O36.3', 'O36.4', 'O42.2')) AND t1.MesOld_Num IN ('st02.003', 'st02.004')
                               OR t1.diaggroup_code <> t2.diaggroup_code OR t1.diaggroup_code IS NULL OR t2.diaggroup_code IS NULL THEN t2.MesOldUslugaComplex_id END id
                     , CASE WHEN (t1.MesOld_Num = 'st02.001' AND t1.kd >= 6 OR t1.MesOld_Num = 'st02.001' AND t1.kd >= 2 AND t1.diag_code IN ('O14.1', 'O34.2', 'O36.3', 'O36.4', 'O42.2')) AND t3.MesOld_Num IN ('st02.003', 'st02.004')
                               OR t1.diaggroup_code <> t3.diaggroup_code OR t1.diaggroup_code IS NULL OR t3.diaggroup_code IS NULL THEN t3.MesOldUslugaComplex_id END id2
                     , t1.MesOld_Num
                  FROM t t1
                  LEFT JOIN t t2 ON t2.EvnSection_Index = t1.EvnSection_Index - 1
                  LEFT JOIN t t3 ON t3.EvnSection_Index = t1.EvnSection_Index + 1
                WHERE t1.p_index = 1)
    LOOP
      DELETE FROM tWork WHERE tWork.MesOldUslugaComplex_id in (rec.id, rec.id2);
      RAISE NOTICE 'MesOld_Num = %, MesOldUslugaComplex_id = %, MesOldUslugaComplex_id = %' , rec.MesOld_Num, rec.id, rec.id2;
    END LOOP;
  END IF;

--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- Особенности для Тамбова
-- ОнкоКСГ подбираются на основании справочника TERR011 (таблица r477.terr011):
-- Диагноз ЗНО учитывается в подборе КСГ если: 
-- в закрывающем ЗОГе указан один из профилей койки
-- по коду ОМС медицинской организации, коду профиля койки и типу стационара в справочнике r477.terr011 есть соответствие
  	IF EXISTS (SELECT 1
                FROM v_diag
              WHERE diag_id = _Diag_id
                AND diag_code >= 'C00'
                AND diag_code <= 'C97')
    then 	
	   	IF EXISTS (select 1	 --в закрывающем ЗОГе указан один из профилей койки  
	   				from v_LpuSectionBedProfile LSBP
	   				join (	select ve.lpusectionbedprofile_id 
	   						from tGroup 
	   						join v_evnsection ve on ve.evnsection_id =tGroup.evnsection_id
	   						order by tGroup.evnsection_index desc
	   						limit 1) lastEvnSection on lastEvnSection.lpusectionbedprofile_id=LSBP.lpusectionbedprofile_id 
	   				where LSBP.lpusectionbedprofile_code in ('20','42','43','44','45','46','47','48','49','15')
	   				)       
	   	AND EXISTS (select 1 --по коду ОМС медицинской организации, коду профиля койки и типу стационара в справочнике r477.terr011 есть соответствие
					from r477.terr011
					join v_LpuSectionBedProfile LSBP on LSBP.lpusectionbedprofile_code =terr011.bed_profile_code
					join v_lpu lpu on terr011.org_code=lpu.lpu_f003mcod
					join v_lpusection ls on ls.lpu_id = lpu.lpu_id
					where ls.lpusection_id =_LpuSection_id
					and LSBP.lpusectionbedprofile_id =_LpuSectionBedProfile_id
					and regimen_type = case when _LpuUnitType_id=1 then '1' --Круглосуточный стационар
											when _LpuUnitType_id=6 then '3' --Дневной стационар при стационаре
											when _LpuUnitType_id=9 then '5' --Дневной стационар при поликлинике
											when _LpuUnitType_id=7 then '6' --Дневной стационар на дому
										end
					and _EvnSection_disDate::date BETWEEN COALESCE(terr011.from_dt::date, '-INFINITY') AND COALESCE( terr011.to_dt::date, 'INFINITY')
	   				)
	    THEN _hasZNOCrit := 1;
	   	ELSE 
	   		DELETE FROM tWork WHERE diag_id = _Diag_id and mesold_num not IN ('st36.012', 'ds36.006');
		    RAISE NOTICE 'delete C_diag_id = %', _Diag_id;
   		END IF;
  END IF;

  RAISE NOTICE '_hasZNOCrit = %', _hasZNOCrit;
 
  -- Алгоритм 2020 года refs #189829
  -- 2. Оставляем только те, в которых есть доп. критерий (шкала реабилитации, rbs, диагноз и <28 дней), если такие есть
  -- если есть КСГ с доп.критерием, то остальные удаляем
  IF EXISTS (SELECT 1 FROM tWork WHERE hasDopCriteria = 1) THEN
    DELETE FROM tWork WHERE hasDopCriteria = 0;
    RAISE NOTICE 'delete 2';
  END IF;

  -- 3. Проверяем по полученному списку КСГ связки в MesLink и исключаем те, у которых они есть
  -- проверка на связку терап. и хир. КСГ
  FOR rec IN (SELECT m.Mes_id
                FROM v_MesLink m
                JOIN tWork ON m.Mes_id = tWork.mes_id
               WHERE m.Mes_sid IN (SELECT mes_id FROM tWork)
                 AND COALESCE(m.MesLink_begDT, _EvnSection_disDate) <= _EvnSection_disDate
                 AND COALESCE(m.MesLink_endDT, _EvnSection_disDate) >= _EvnSection_disDate
                 AND m.MesLinkType_id = 2)
  LOOP
    -- удаление терапевтической КСГ
    DELETE FROM tWork WHERE mes_id = rec.mes_id;
    RAISE NOTICE 'delete 3 mes_id = %', rec.mes_id;
  END LOOP;

              --4. если есть КСГ определенная по услуге + диагнозу и есть КСГ определенная только по услуге или только по диагнозу,
              --то исключаем КСГ определенную только по услуге или только по диагнозу
              -- услуга и диагноз  - вместе и по-отдельности
  FOR rec IN (SELECT t1.mes_id
                FROM tWork t0
                JOIN tWork t1 ON (t0.diag_id = t1.diag_id AND t1.UslugaComplex_id IS NULL OR t1.UslugaComplex_id = t0.UslugaComplex_id AND t1.diag_id IS NULL)
                WHERE t0.diag_id IS NOT NULL
                AND t0.UslugaComplex_id IS NOT NULL
                -- остальное совпадает
                AND (t0.Diag_oid = t1.Diag_oid OR t0.Diag_oid IS NULL AND t1.Diag_oid IS NULL)
                AND (t0.MesAgeGroup_id = t1.MesAgeGroup_id OR t0.MesAgeGroup_id IS NULL AND t1.MesAgeGroup_id IS NULL)
                AND (t0.Sex_id = t1.Sex_id OR t0.Sex_id IS NULL AND t1.Sex_id IS NULL)
                AND (t0.MesOldUslugaComplex_Duration = t1.MesOldUslugaComplex_Duration OR t0.MesOldUslugaComplex_Duration IS NULL AND t1.MesOldUslugaComplex_Duration IS NULL)
                AND (t0.MesOldUslugaComplex_DurationTo = t1.MesOldUslugaComplex_DurationTo OR t0.MesOldUslugaComplex_DurationTo IS NULL AND t1.MesOldUslugaComplex_DurationTo IS NULL)
                AND (t0.DrugTherapyScheme_id = t1.DrugTherapyScheme_id OR t0.DrugTherapyScheme_id IS NULL AND t1.DrugTherapyScheme_id IS NULL)
                AND (t0.MesOldUslugaComplex_SofaScalePoints = t1.MesOldUslugaComplex_SofaScalePoints OR t0.MesOldUslugaComplex_SofaScalePoints IS NULL AND t1.MesOldUslugaComplex_SofaScalePoints IS NULL)
                AND (t0.MesOldUslugaComplex_IVLHours = t1.MesOldUslugaComplex_IVLHours OR t0.MesOldUslugaComplex_IVLHours IS NULL AND t1.MesOldUslugaComplex_IVLHours IS NULL)
                AND (t0.MesDop_id = t1.MesDop_id OR t0.MesDop_id IS NULL AND t1.MesDop_id IS NULL))
              LOOP
              DELETE FROM tWork WHERE mes_id = rec.mes_id;
              RAISE NOTICE 'delete 4 mes_id = %', rec.mes_id;
              END LOOP;

  --5. если есть КСГ определенная по услуге + диагнозу + длительности и есть КСГ определенная только по услуге и диагнозу,
  --то исключаем КСГ определенную только по услуге и диагнозу
  -- услуга, диагноз, длительность  - и только услуга и диагноз
  FOR rec IN (SELECT t1.mes_id
                FROM tWork t0
                JOIN tWork t1 ON t0.diag_id = t1.diag_id
                             AND t1.UslugaComplex_id = t0.UslugaComplex_id
                             AND t1.MesOldUslugaComplex_Duration IS NULL
                             AND t1.MesOldUslugaComplex_DurationTo IS NULL
               WHERE t0.diag_id IS NOT NULL
                 AND t0.UslugaComplex_id IS NOT NULL
                 AND t0.MesOldUslugaComplex_Duration IS NOT NULL
                 AND t0.MesOldUslugaComplex_DurationTo IS NOT NULL)
  LOOP
    DELETE FROM tWork WHERE mes_id = rec.mes_id;
    RAISE NOTICE 'delete 5 mes_id = %', rec.mes_id;
  END LOOP;

  --6. если есть КСГ определенная по услуге + фракциям + схеме и есть КСГ определенная только по услуге и фракциям,
  --то исключаем КСГ определенную только по услуге и фракциям
  -- услуга, фракции, схема  - и только услуга и фракции
  FOR rec IN (SELECT t1.mes_id
                FROM tWork t0
                JOIN tWork t1 ON t1.UslugaComplex_id = t0.UslugaComplex_id
                             AND t1.MesOldUslugaComplex_FracFrom = t0.MesOldUslugaComplex_FracFrom
                             AND t1.MesOldUslugaComplex_FracTo = t0.MesOldUslugaComplex_FracTo
                             AND t1.DrugTherapyScheme_id IS NULL
               WHERE t0.UslugaComplex_id IS NOT NULL
                 AND t0.MesOldUslugaComplex_FracFrom IS NOT NULL
                 AND t0.MesOldUslugaComplex_FracTo IS NOT NULL
                 AND t0.DrugTherapyScheme_id IS NOT NULL)
  LOOP
    DELETE FROM tWork WHERE mes_id = rec.mes_id;
    RAISE NOTICE '4';
  END LOOP;
  --endregion поиск КСГ


  FOR rec IN (SELECT * FROM twork)
  LOOP
    RAISE NOTICE 'itog diag = %, mes_num - %, ItogCoeff %, usl %', rec.Diag_id, rec.MesOld_Num, rec.ItogCoeff, rec.UslugaComplex_id;
  END LOOP;

              --7. Берем из оставшихся КСГ ту у которой максимальный КЗ * упр. коэф
              -- максимальный из оставшихся
  SELECT mes_id, MesOld_Num
    INTO _maxKSG, _mesoldNum
    FROM tWork
    where diag_id is not null or UslugaComplex_id is not null or mesdop_id is not null or diag_oid is not null
   ORDER BY CASE WHEN _hasZNOCrit = 1 AND UslugaComplex_id IS NOT NULL THEN 0
                 WHEN mesold_num IN ('st36.012', 'ds36.006') THEN 3
                 ELSE 2
            end
            , ItogCoeff desc, substring(mesold_num,3, length(mesold_num)-2 ) desc
  LIMIT 1;

  RAISE NOTICE '_maxKSG = %, _mesoldNum - %', _maxKSG, _mesoldNum;

  -- возвращаем полученные данные
  IF (SELECT COUNT(*) FROM tWork) > 0 THEN
          RETURN QUERY (SELECT
              CASE WHEN tWork.mesType_id IN (9, 10) THEN mes_id END, -- as mes_tid,
              CASE WHEN tWork.mesType_id IN (13, 14) THEN mes_id END, -- as mes_sid,
              tWork.mes_kid,
              tWork.MesTariff_id,
              tWork.MesOldUslugaComplex_id,
              NULL :: TEXT
            FROM tWork
            WHERE mes_id = _maxKSG);
        ELSE
          RETURN QUERY (SELECT NULL :: BIGINT,
              NULL :: BIGINT,
              NULL :: BIGINT,
              NULL :: BIGINT,
              NULL :: BIGINT,
              'КСГ не определен' :: TEXT);
      END IF;

  END;
  $_$;


ALTER FUNCTION r477.evnps_ksg_calc(p_json jsonb) OWNER TO developer_rep;

--
-- Name: evnps_kslp_calc(bigint, character varying, character varying, double precision); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.evnps_kslp_calc(p_evnsection_id bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying, INOUT p_kslp_itog double precision DEFAULT NULL::double precision) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare
  --p_kslp_itog float = 0;
  p_TariffClass bigint;

  p_htmedicalcareclass_id BIGINT;
  p_duration INTEGER;
  p_diag BIGINT;
  p_evnsection_disDate timestamp;
  p_EvnSection_setDate TIMESTAMP;
  p_evnps bigint;
  p_evn_disdate timestamp;
  p_unittype_id bigint;
  p_person_age int;
  p_escort int;
  p_bedprofile bigint;
  p_bedprofile_code varchar(10);
  p_mestariff bigint;
  p_MesOld_Num varchar(20);
  p_mesType_id BIGINT;
  p_MesOld_Num_paid varchar(20);
  p_paytype_oms_id BIGINT;

  p_diag1 bigint;
  p_indexnum int;
  p_group_kd int; 
  p_norm_kd int = 30;
  p_kslp6 float;
  p_64_cnt int;
  p_66_cnt int;
  p_67_cnt int;
  p_sh_sh int; 
  p_sh_mt int;
  p_usl int;

  ar_code_usl float[];
  ar_code_kslp float[];
  ar_kslp_link float[];
  _code int;
  _value float;
  _cnt int := 0;
  _x int;
begin 
  RAISE NOTICE 'begin';

CREATE TEMP TABLE tUsluga (
evnusluga_id BIGINT,
UslugaComplex_id BIGINT,
UslugaComplex_code VARCHAR,
UslugaCategory_id BIGINT,
setDt TIMESTAMP,
disDt TIMESTAMP
) ON COMMIT DROP;


CREATE TEMP TABLE tAttribute (
AttributeSign_code BIGINT
) ON COMMIT DROP;

  select lu.lpuunittype_id, s.person_age, coalesce(evnsection_disDate, evnsection_setDate),DATE_PART('day', COALESCE(evnsection_disDate, CURRENT_TIMESTAMP) - evnsection_setDate),
         es.EvnSection_IsAdultEscort, es.LpuSectionBedProfile_id, es.mestariff_id, es.evnsection_indexnum,
         s.evnPS_id,es.diag_id,htmedicalcareclass_id
    into p_unittype_id, p_person_age, p_evn_disdate, p_duration,
    p_escort, p_bedprofile, p_mestariff, p_indexnum, 
    p_evnps,p_diag,p_htmedicalcareclass_id
    from 
      v_EvnSection es
      inner join v_LpuSection ls on ls.LpuSection_id = es.LpuSection_id
      inner join v_lpuunit lu on lu.LpuUnit_id = ls.LpuUnit_id
      inner join v_evnPS s on es.EvnSection_pid = s.evnPS_id
    where es.EvnSection_id = p_evnsection_id;




  select TariffClass_id 
    into p_TariffClass
    from v_TariffClass 
    where TariffClass_SysNick = 'kclp'
  LIMIT 1;

  -- КСГ на текущем движении
  select mo.mesold_num,MO.mesType_id
    into p_MesOld_Num,p_mesType_id
    from
      v_MesTariff mt 
      inner join v_MesOld mo  on mo.Mes_id = mt.Mes_id
    where
      MesTariff_id = p_MesTariff
    limit 1;  

  -- КСГ  на оплачиваемом движении группы
  select mo.MesOld_Num
    into p_MesOld_Num_paid 
    from
      v_evnsection sec
      inner join v_MesTariff mt on mt.MesTariff_id = sec.MesTariff_id
      inner join v_MesOld mo  on mo.Mes_id = mt.Mes_id
    where
      sec.evnsection_pid = p_evnps
      and sec.evnsection_indexnum = p_indexnum
      and sec.evnsection_iswillpaid = 2
  limit 1;    

  RAISE NOTICE 'p_person_age  %, p_MesOld_Num %', p_person_age, p_MesOld_Num;
 
  -- коды КСЛП в массив
  for _code, _value in 
    (
      select
          CODE.AttributeValue_ValueString as code,
          av.AttributeValue_ValueFloat as value
        from
          v_AttributeVision avis 
          inner join v_AttributeValue av  on av.AttributeVision_id = avis.AttributeVision_id
          left join lateral (
             select 
                av2.AttributeValue_ValueString
             from
                v_AttributeValue av2 
             inner join v_Attribute a2  on a2.Attribute_id = av2.Attribute_id
             where
               av2.AttributeValue_rid = av.AttributeValue_id
               and a2.Attribute_SysNick = 'KSLP_CODE'
               limit 1 
          ) CODE on true
        where
            avis.AttributeVision_TableName = 'dbo.TariffClass'
            and avis.AttributeVision_TablePKey = p_TariffClass --754
            and avis.AttributeVision_IsKeyValue = 2
            and coalesce(av.AttributeValue_begDate, p_evn_disdate) <= p_evn_disdate
            and coalesce(av.AttributeValue_endDate, p_evn_disdate) >= p_evn_disdate
             
    )
    loop
      ar_code_kslp[_code] := _value;
      RAISE NOTICE '_code  %, value %', _code, _value;
    end loop;

-- вид оплаты ОМС
SELECT
  paytype_id INTO p_paytype_oms_id
FROM v_paytype
WHERE paytype_sysnick = 'oms';

-- услуги этого движения
INSERT INTO tUsluga
  (SELECT
      evnusluga_id,
      uc.UslugaComplex_id,
      uc.UslugaComplex_Code,
      uc.UslugaCategory_id,
      eu.EvnUsluga_setDT,
      eu.EvnUsluga_disDT
    FROM v_evnUsluga eu
      INNER JOIN v_UslugaComplex uc
        ON uc.UslugaComplex_id = eu.UslugaComplex_id
    WHERE (eu.EvnUsluga_pid = p_evnsection_id
    )
    AND eu.paytype_id = p_paytype_oms_id
    AND eu.EvnUsluga_setDT IS NOT NULL
    AND eu.EvnClass_SysNick IN ('EvnUslugaCommon', 'EvnUslugaOper', 'EvnUslugaPar', 'EvnUslugaStom'));

--набор атрибутов для услуги 'A11.20.017'
INSERT INTO tAttribute
  (SELECT DISTINCT AttributeSign_code 
  FROM tUsluga u
  JOIN AttributeSignValue asv ON asv.AttributeSignValue_TablePKey=EvnUsluga_id
  JOIN AttributeSign ats ON ats.AttributeSign_id = asv.AttributeSign_id AND AttributeSign_code IN (7,8,9,10,11)
  WHERE	UslugaComplex_Code='A11.20.017')  ;

 
 -------------------------------------------------------------------------------------
    --КСЛП 4
--возраст пациента на дату поступления в первом движении в КВС входит в возрастной промежуток (в годах) [0;17].
--в движении в поле «Сопровождается взрослым» установлено значение «Да».
    if (p_person_age BETWEEN 0 AND 17 and p_escort=2)
      then
      ar_kslp_link[_cnt] := 4;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[4] - 1;
        else p_kslp_itog := ar_code_kslp[4];
      end if;  
    end if;  

    --КСЛП 6
--для основного последнего движения и КСГ st38.001 отсутствует действующая на дату выписки в движении связка в таблице dbo.MesOldUslugaComplex (в которой диагноз является основным (Diag_id));
--хотя бы одно из движений содержит сопутствующий диагноз R54;
--поле «Профиль коек» в последнем движении = «72 Геронтологические (V020: 16 - геронтологические)».
    if p_MesOld_Num <> 'st38.001' 
  AND EXISTS(select
              	EvnSection_id 
              from
              	v_EvnSection es
              	inner join v_Diag d on d.Diag_id = es.Diag_id
              	inner join v_EvnDiagPS edps on edps.EvnDiagPS_pid = es.EvnSection_id and edps.DiagSetClass_id IN (2,3)
              	inner join v_Diag ds on ds.Diag_id = edps.Diag_id
              	inner join fed.v_LpuSectionBedProfileLink lsp on lsp.LpuSectionBedProfile_id = es.LpuSectionBedProfile_id AND lsp.LpuSectionBedProfile_fedid=16
              where
              	LEFT(ds.Diag_Code, 3) = 'R54'
              	and LEFT(d.Diag_Code, 3) <> 'R54'
              	and ES.EvnSection_rid = p_evnps
              limit 1)
      then
      ar_kslp_link[_cnt] := 6;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[6] - 1;
        else p_kslp_itog := ar_code_kslp[6];
      end if;  
    end if;  

     --КСЛП 8
--движение содержит услугу с кодом A11.20.017;
--для услуги A11.20.017 добавлен один из следующих наборов атрибутов:
--1 этап ЭКО (Стимуляция суперовуляции);
--1этап ЭКО (Стимуляция суперовуляции), 2 этап ЭКО (Получение яйцеклетки);
--1этап ЭКО (Стимуляция суперовуляции), 2 этап ЭКО (Получение яйцеклетки), 3 этап ЭКО (Экстракорпоральное оплодотворение и культивирование эмбрионов).
   
 -- нужно дописать про атрибуты
   
   
   if EXISTS(SELECT UslugaComplex_Code FROM tUsluga where	UslugaComplex_Code='A11.20.017' limit 1)
       AND EXISTS(SELECT * FROM tAttribute
                  JOIN (SELECT COUNT(*)kol FROM tAttribute) kol ON 1=1
                WHERE AttributeSign_code=7 AND kol=1 
                OR AttributeSign_code IN (7,8)AND kol=2 AND  AttributeSign_code NOT IN (9,10,11)
                OR AttributeSign_code IN (7,8,9)AND kol=3  AND  AttributeSign_code NOT IN (10,11)
                  LIMIT 1)
      then
      ar_kslp_link[_cnt] := 8;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[8] - 1;
        else p_kslp_itog := ar_code_kslp[8];
      end if;  
    end if;  
        


  -- КСЛП 9
--  движение содержит услугу с кодом A11.20.017;
--для услуги A11.20.017 добавлен следующий наборов атрибутов:
--1 этап ЭКО (Стимуляция суперовуляции);
--2 этап ЭКО (Получение яйцеклетки);
--3 этап ЭКО (Экстракорпоральное оплодотворение и культивирование эмбрионов);
--4 этап ЭКО (Внутриматочное введение (перенос) эмбрионов);
--Криоконсервация.
 
  -- нужно дописать про атрибуты
  
    
       if EXISTS(SELECT UslugaComplex_Code FROM tUsluga where	UslugaComplex_Code='A11.20.017' limit 1)
       AND EXISTS(SELECT * FROM tAttribute
                  JOIN (SELECT COUNT(*)kol FROM tAttribute) kol ON 1=1
                WHERE  AttributeSign_code IN (7,8,9,10,11)AND kol=5
                  LIMIT 1)
      then
      ar_kslp_link[_cnt] := 9;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[9] - 1;
        else p_kslp_itog := ar_code_kslp[9];
      end if;  
    end if; 


 -- КСЛП 1
--движение содержит услугу с кодом A11.20.017;
--для услуги A11.20.017 добавлен следующий наборов атрибутов:
--4 этап ЭКО (Внутриматочное введение (перенос) эмбрионов).

  -- нужно дописать про атрибуты

       if EXISTS(SELECT UslugaComplex_Code FROM tUsluga where	UslugaComplex_Code='A11.20.017' limit 1)
       AND EXISTS(SELECT * FROM tAttribute
                  JOIN (SELECT COUNT(*)kol FROM tAttribute) kol ON 1=1
                WHERE AttributeSign_code=10 AND kol=1
                  LIMIT 1)
      then
      ar_kslp_link[_cnt] := 1;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[1] - 1;
        else p_kslp_itog := ar_code_kslp[1];
      end if;  
    end if; 


 -- КСЛП 3
--движение содержит услугу с кодом A11.20.017;
--для услуги A11.20.017 добавлен следующий наборов атрибутов:
--1 этап ЭКО (Стимуляция суперовуляции);
--2 этап ЭКО (Получение яйцеклетки);
--3 этап ЭКО (Экстракорпоральное оплодотворение и культивирование эмбрионов);
--Криоконсервация.

  -- нужно дописать про атрибуты

       if EXISTS(SELECT UslugaComplex_Code FROM tUsluga where	UslugaComplex_Code='A11.20.017' limit 1)
       AND EXISTS(SELECT * FROM tAttribute
                  JOIN (SELECT COUNT(*)kol FROM tAttribute) kol ON 1=1
                WHERE  AttributeSign_code IN (7,8,9,11)AND kol=4  AND  AttributeSign_code NOT IN (10)
                  LIMIT 1)
      then
      ar_kslp_link[_cnt] := 3;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[3] - 1;
        else p_kslp_itog := ar_code_kslp[3];
      end if;  
    end if; 



 -- КСЛП 5
--движение содержит услугу с кодом A11.20.017;
--для услуги A11.20.017 добавлен следующий наборов атрибутов:
--1этап ЭКО (Стимуляция суперовуляции);
--2 этап ЭКО (Получение яйцеклетки);
--3 этап ЭКО (Экстракорпоральное оплодотворение и культивирование эмбрионов);
--4 этап ЭКО (Внутриматочное введение (перенос) эмбрионов).

  -- нужно дописать про атрибуты

      if EXISTS(SELECT UslugaComplex_Code FROM tUsluga where	UslugaComplex_Code='A11.20.017' limit 1)
       AND EXISTS(SELECT * FROM tAttribute
                  JOIN (SELECT COUNT(*)kol FROM tAttribute) kol ON 1=1
                WHERE  AttributeSign_code IN (7,8,9,10)AND kol=4  AND  AttributeSign_code NOT IN (11)
                  LIMIT 1)
      then
      ar_kslp_link[_cnt] := 5;
      _cnt := _cnt + 1;
      if p_kslp_itog > 0 
        then p_kslp_itog := p_kslp_itog + ar_code_kslp[5] - 1;
        else p_kslp_itog := ar_code_kslp[5];
      end if;  
    end if; 




--------------------------------------------------------------------------------------------  
  if p_kslp_itog > 1.8 then p_kslp_itog := 1.8; end if;
  IF p_htmedicalcareclass_id IS NOT null THEN p_kslp_itog :=0; END IF;



  -- вставка в таблицы
  --if p_ins = 2 THEN
    BEGIN

    update evnsection 
      set EvnSection_CoeffCTP = p_kslp_itog
      where evn_id = p_evnsection_id;
    
-- сначала удалить если есть
      delete from  dbo.evnsectionkslplink
        where  evnsection_id = p_evnsection_id;

 -- добавить новые
      if cardinality(ar_kslp_link) > 0 then
    FOREACH _x IN ARRAY ar_kslp_link
    LOOP
--      RAISE NOTICE '--- % +++ % ', _x, ar_code_kslp[_x];
      INSERT INTO dbo.evnsectionkslplink
        (evnsection_id, evnsectionkslplink_code, evnsectionkslplink_value, pmuser_insid, pmuser_updid, evnsectionkslplink_insdt, evnsectionkslplink_upddt, evnsectionksg_id, evnsectionkslplink_rowversion, evnsectionkslplink_deleted, evnsectionkslplink_deldt, pmuser_delid)
        VALUES(p_evnsection_id, _x::text, ar_code_kslp[_x], 1, 1, now(), now(), null, null, null, null, null);
       
       
    END LOOP;    
    
  end if;
  
      EXCEPTION
      when others then error_code:=SQLSTATE; error_message:=SQLERRM;
    END;
  --return p_kslp_itog;
    
end;    
$$;


ALTER FUNCTION r477.evnps_kslp_calc(p_evnsection_id bigint, INOUT error_code character varying, INOUT error_message character varying, INOUT p_kslp_itog double precision) OWNER TO developer_rep;

--
-- Name: p_getevnsectiongroup(bigint, bigint, bigint, bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_getevnsectiongroup(p_evnsection_pid bigint, p_evnsection_id bigint DEFAULT NULL::bigint, p_paytype_id bigint DEFAULT NULL::bigint, p_diag_id bigint DEFAULT NULL::bigint) RETURNS TABLE(evnsection_id bigint, diaggroup_code character varying, person_age integer, evnsection_setdt timestamp without time zone, evnsection_setdate timestamp without time zone, evnsection_disdate timestamp without time zone, lpuunittype_id bigint, lpusectionprofile_code character varying, lpusectionprofile_id bigint, mes_tid bigint, mes_sid bigint, mestariff_id bigint, diag_code character varying, evnsection_indexrep integer, evnsection_indexrepinreg integer, evnsection_ispaid bigint, lpu_id bigint, evnsection_ispriem bigint, evnsection_sofascalepoints integer, rehabscale_id bigint, drugtherapyscheme_id bigint, person_id bigint, diag_id bigint, paytype_id bigint, evnsection_pid bigint, evnsection_barthelidx integer, evnsection_indexnum bigint, evnsection_index bigint, evnsection_ismanualidxnum bigint, mes_kid bigint, mesolduslugacomplex_id bigint, evnsection_totalfract bigint, mestariff_value numeric, mes_id bigint, mes_code character varying, mesold_num character varying, evnsection_ismultiksg bigint, paytype_sysnick character varying, evnsectionksg_id bigint)
    LANGUAGE plpgsql
    AS $$

DECLARE
  p_diagclass BIGINT;
  p_EvnSection_IndexNum BIGINT;
BEGIN

  IF EvnSection_id IS NOT NULL
    THEN
      SELECT
        EvnSection_IndexNum INTO p_EvnSection_IndexNum
      FROM v_EvnSection
      WHERE EvnSection_id = p_EvnSection_id;
    ELSE
      p_EvnSection_IndexNum := NULL;
  END IF;

  -- класс диагноза из параметра
  IF p_diag_id IS NOT NULL
    THEN
      SELECT
        COALESCE(d4.Diag_id, d3.Diag_id) AS diag_id INTO p_diagclass
      FROM v_Diag d
        LEFT JOIN v_Diag d2
          ON d2.Diag_id = d.Diag_pid
        LEFT JOIN v_Diag d3
          ON d3.Diag_id = d2.Diag_pid
        LEFT JOIN v_Diag d4
          ON d4.Diag_id = d3.Diag_pid
      WHERE d.Diag_id = p_diag_id;
    ELSE
      p_diagclass := NULL;
  END IF;


  RETURN QUERY (SELECT
      es.EvnSection_id AS EvnSection_id,
      d.Diag_Code AS DiagGroup_Code,
      dbo.AgeTFOMS(PS.Person_BirthDay, es.EvnSection_setDate) AS Person_Age,
      es.EvnSection_setDT AS EvnSection_setDT,
      es.EvnSection_setDate AS EvnSection_setDate,
      COALESCE(es.EvnSection_disDate, es.EvnSection_setDate) :: DATE :: TIMESTAMP WITHOUT TIME ZONE AS EvnSection_disDate,
      lu.LpuUnitType_id AS LpuUnitType_id,
      ls.LpuSectionProfile_Code AS LpuSectionProfile_Code,
      ls.LpuSectionProfile_id AS LpuSectionProfile_id,
      es.Mes_tid AS Mes_tid,
      es.Mes_sid AS Mes_sid,
      es.MesTariff_id AS MesTariff_id,
      d.es_diag AS Diag_Code,
      es.EvnSection_IndexRep AS EvnSection_IndexRep,
      es.EvnSection_IndexRepInReg AS EvnSection_IndexRepInReg,
      es.EvnSection_IsPaid AS EvnSection_IsPaid,
      es.Lpu_id AS Lpu_id,
      es.EvnSection_IsPriem AS EvnSection_IsPriem,
      es.EvnSection_SofaScalePoints AS EvnSection_SofaScalePoints,
      es.RehabScale_id AS RehabScale_id,
      ESDTS.DrugTherapyScheme_id AS DrugTherapyScheme_id,
      es.Person_id AS Person_id,
      es.Diag_id AS Diag_id,
      es.PayType_id AS PayType_id,
      es.EvnSection_pid AS EvnSection_pid,
      es.EvnSection_BarthelIdx AS EvnSection_BarthelIdx,
      es.EvnSection_IndexNum AS EvnSection_IndexNum,
      es.EvnSection_Index AS EvnSection_Index,
      es.EvnSection_IsManualIdxNum AS EvnSection_IsManualIdxNum,
      es.Mes_kid AS Mes_kid,
      es.MesOldUslugaComplex_id AS MesOldUslugaComplex_id,
      es.EvnSection_TotalFract AS EvnSection_TotalFract,
      mo.MesTariff_Value AS MesTariff_Value,
      mo.Mes_id AS Mes_id,
      mo.Mes_Code AS Mes_Code,
      mo.MesOld_Num AS MesOld_Num,
      ES.EvnSection_IsMultiKSG AS EvnSection_IsMultiKSG,
      pt.PayType_SysNick AS PayType_SysNick,
      ESKS.EvnSectionKSG_id AS EvnSectionKSG_id
    FROM v_EvnSection es
      INNER JOIN v_LpuSection ls
        ON ls.LpuSection_id = es.LpuSection_id
      INNER JOIN v_LpuUnit lu
        ON lu.LpuUnit_id = ls.LpuUnit_id
      LEFT JOIN v_LpuSectionProfile lsp
        ON lsp.LpuSectionProfile_id = ls.LpuSectionProfile_id
      LEFT JOIN fed.v_LpuSectionProfile flsp
        ON flsp.LpuSectionProfile_id = lsp.LpuSectionProfile_fedid
      LEFT JOIN v_PersonState ps
        ON ps.Person_id = es.Person_id
      LEFT JOIN LATERAL (SELECT
          COALESCE(d4.Diag_Code, d3.Diag_Code) AS Diag_Code,
          d3.Diag_id AS d3_Diag_id,
          d4.Diag_id AS d4_Diag_id,
          d.diag_code AS es_diag
        FROM v_Diag d
          INNER JOIN v_Diag d2
            ON d2.Diag_id = d.Diag_pid
          INNER JOIN v_Diag d3
            ON d3.Diag_id = d2.Diag_pid
          LEFT JOIN v_Diag d4
            ON d4.Diag_id = d3.Diag_pid
        WHERE d.Diag_id = es.Diag_id LIMIT 1)
      d
        ON TRUE
      LEFT JOIN LATERAL (SELECT
          mo.Mes_id,
          mo.Mes_Code,
          mo.MesOld_Num,
          mt.MesTariff_Value
        FROM v_MesTariff mt
          INNER JOIN v_MesOld mo
            ON mo.Mes_id = mt.Mes_id
        WHERE mt.MesTariff_id = es.MesTariff_id LIMIT 1)
      mo
        ON TRUE
      LEFT JOIN v_PayType pt
        ON pt.PayType_id = es.PayType_id
      LEFT JOIN LATERAL (SELECT
          ESDTS.DrugTherapyScheme_id
        FROM v_EvnSectionDrugTherapyScheme ESDTS
        WHERE ESDTS.EvnSection_id = ES.EvnSection_id LIMIT 1)
      ESDTS
        ON TRUE
      LEFT JOIN LATERAL (SELECT
          esks.EvnSectionKSG_id
        FROM v_EvnSectionKSG esks
        WHERE esks.EvnSection_id = es.EvnSection_id
        AND esks.EvnSectionKSG_IsSingle = 2 LIMIT 1)
      ESKS
        ON TRUE
    WHERE es.EvnSection_pid = p_EvnSection_pid
    --and lu.LpuUnitType_id = 1
    AND (COALESCE(flsp.LpuSectionProfile_Code, '1') <> '158'
    OR COALESCE(es.EvnSection_disDate, es.EvnSection_setDate) >= '2016-01-01')
    AND pt.paytype_sysnick IN ('oms', 'mbudtrans', 'bud', 'fbud', 'mbudtrans_mbud')
    AND COALESCE(es.EvnSection_IsPriem, 1) = 1
    AND es.HTMedicalCareClass_id IS NULL
    AND (COALESCE(es.EvnSection_IsPaid, 1) = 1
    OR COALESCE(es.EvnSection_disDate, es.EvnSection_setDate) >= '2015-01-01') -- оплаченные движения с датой окончания до 2015 года не участвуют в группировке
    AND (es.EvnSection_IndexNum = p_EvnSection_IndexNum
    OR p_EvnSection_IndexNum IS NULL)
    AND (COALESCE(d.d4_Diag_id, d.d3_Diag_id) = p_diagclass
    OR p_diagclass IS NULL)
    AND (es.PayType_id = p_PayType_id
    OR p_PayType_id IS NULL));
END;
$$;


ALTER FUNCTION r477.p_getevnsectiongroup(p_evnsection_pid bigint, p_evnsection_id bigint, p_paytype_id bigint, p_diag_id bigint) OWNER TO developer_rep;

--
-- Name: p_identity_exp_pac(bigint, timestamp without time zone, timestamp without time zone); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_identity_exp_pac(p_lpu_id bigint, p_begdate timestamp without time zone, p_enddate timestamp without time zone) RETURNS TABLE("ID_PAC" bigint, "FAM" text, "IM" text, "OT" text, "W" integer, "DR" text, "FAM_P" text, "IM_P" text, "OT_P" text, "W_P" integer, "DR_P" text, "MR" text, "DOCTYPE" text, "DOCSER" text, "DOCNUM" text, "SNILS" text, "OKATOG" text, "OKATOP" text, "COMENTP" text)
    LANGUAGE plpgsql
    AS $_$
DECLARE
	_paytype_id bigint = (select paytype_id from v_paytype where paytype_sysnick = 'oms' and paytype_enddate is null limit 1);
BEGIN
 
 --первичный отбор
  create temp table tmp_ident_pac on commit drop as   
  select 
      EvnVizit.server_id,
      EvnVizit.personevn_id,
      EvnPL.evnpl_setdate as evn_setdate,
      EvnPl.evnpl_disdate as evn_disdate
  from v_evnpl EvnPL 
   join v_EvnVizitPL as EvnVizit on EvnVizit.EvnVizitPL_pid = EvnPL.EvnPL_id and EvnVizit.EvnVizitPL_Index = EvnVizit.EvnVizitPL_Count - 1  
  where 
      EvnPL.lpu_id = p_lpu_id 
      and coalesce(EvnPL.evnpl_disdate,EvnPL.evnpl_setdate) between p_begdate and p_enddate
      --and EvnPL.evnpl_isfinish = 2 
      and EvnVizit.paytype_id = _paytype_id 
      
  union all         
      
  select 
      EvnUsluga.server_id,
      EvnUsluga.personevn_id,
      EvnUsluga.evnuslugapar_setdate::date as evn_setdate,
      EvnUsluga.evnuslugapar_disdate::date as evn_disdate    
  from v_EvnUslugaPar EvnUsluga  
  where 
      EvnUsluga.lpu_id = p_lpu_id
      and coalesce(EvnUsluga.evnuslugapar_disdate,EvnUsluga.evnuslugapar_setdate) between p_begdate and p_enddate
      and EvnUsluga.paytype_id = _paytype_id 

  union all 

  select 
      EvnPLDisp.server_id,
      EvnPLDisp.personevn_id,
      EvnPLDisp.evnpldisp_setdate::date as evn_setdate,
      EvnPLDisp.evnpldisp_disdate::date as evn_disdate    
  from v_EvnPLDisp EvnPLDisp  
  where 
      EvnPLDisp.lpu_id = p_lpu_id
      and coalesce(EvnPLDisp.evnpldisp_disdate,EvnPLDisp.evnpldisp_setdate) between p_begdate and p_enddate
      --and EvnPLDisp.evnpldisp_isfinish = 2 
      and EvnPLDisp.paytype_id = _paytype_id   
      
  union all 

  select 
  	  EvnSection.server_id,
      EvnSection.personevn_id,
      EvnPS.evnps_setdate::date as evn_setdate,
      EvnPS.evnps_disdate::date as evn_disdate
  from v_EvnPS EvnPS 
   join v_EvnSection as EvnSection on EvnSection.EvnSection_pid = EvnPS.EvnPS_id and EvnPS.Lpu_id = EvnSection.Lpu_id                                        
   join v_EvnLeaveBase as EvnLeaveBase on EvnLeaveBase.EvnLeaveBase_pid = EvnSection.EvnSection_id and EvnLeaveBase_index = EvnLeaveBase_count - 1
  where 
      EvnPS.lpu_id = p_lpu_id
      and coalesce(EvnPS.evnps_disdate,EvnPS.evnps_setdate) between p_begdate and p_enddate
      --and EvnSection.LeaveType_id is not null 
      and EvnSection.EvnSection_IsPriem is null
      and EvnSection.paytype_id = _paytype_id 
  ;
  
  return query (
  
  	select distinct 
    
      	  t.ID_PAC,
          t.FAM,
          t.IM,
          t.OT,
          t.W,
          t.DR, 
          t.FAM_P,
          t.IM_P,
          t.OT_P,
          t.W_P,
          t.DR_P,
          t.MR,
          t.DOCTYPE,
          t.DOCSER,
          t.DOCNUM,
          t.SNILS,
          t.OKATOG,
          t.OKATOP,
          t.COMENTP
    
    from (
    
        select  
          PersonAll.person_id as ID_PAC,
          case when Patron.person_pid is null then upper(PersonAll.person_surname) else 'НЕТ' end as FAM,
          case when Patron.person_pid is null then upper(PersonAll.Person_Firname) else 'НЕТ' end as IM,
          case when Patron.person_pid is null then upper(PersonAll.Person_Secname) else 'НЕТ' end as OT,
          PersonAll.sex_id::integer as W,
          to_char(PersonAll.person_birthday,'YYYY-MM-DD') as DR, 
          case when Patron.person_pid is not null then upper(Patron.Person_Surname) end as FAM_P,
          case when Patron.person_pid is not null then upper(Patron.Person_Firname) end as IM_P,
          case when Patron.person_pid is not null then upper(Patron.Person_Secname) end as OT_P,
          case when Patron.person_pid is not null then Patron.sex_id::integer end as W_P,
          case when Patron.person_pid is not null then to_char(Patron.person_birthday,'YYYY-MM-DD') end as DR_P,
          left(Address.address_address,100) as MR,
          doct.documenttype_code::text AS DOCTYPE,
          case 
              when nullif(trim(doc.document_ser),'') is not null then 
                  case doct.documenttype_code
                      when '14' then regexp_replace(trim(doc.document_ser), '(^[0-9]{2})([0-9]{2}$)', '\1-\2')
                      when '3' then regexp_replace(trim(doc.document_ser), '(^[IVXLCDM]{1,3})([А-Я]{2}$)', '\1-\2')
                      else trim(doc.document_ser) 
                  end 
              else null 
          end as DOCSER,
          nullif(trim(doc.document_num),'') as DOCNUM,
          regexp_replace(
              coalesce(Patron.person_snils,PersonAll.person_snils),
              '(...)(...)(...)(..)','\1-\2-\3 \4'
          ) as SNILS,
          kladrU.kladr_ocatd as OKATOG,
          kladrP.kladr_ocatd as OKATOP,
          null::text as COMENTP,
          case when Patron.person_pid is null then case when Polis.PolisType_id = 4 then PersonAll.Person_EdNum else Polis.Polis_Num end else Patron.Polis_Num end::text as NPOLIS
      from tmp_ident_pac t 
       join v_Person_BDZ PersonAll on t.server_id = PersonAll.server_id and t.personevn_id = PersonAll.personevn_id
       left join v_Polis Polis  on Polis.Polis_id = PersonAll.Polis_id
         
       left join lateral (
           select
              PD.Person_pid,
              Pers.Person_BirthDay,
              Pers.Sex_id,
              Pers.Document_id,
              Pers.PAddress_id,
              Pers.UAddress_id,
              Pers.person_surname,
              Pers.person_firname,
              Pers.person_secname,
              Pers.person_snils,
              case when PolisPD.PolisType_id = 4 then Pers.Person_EdNum else PolisPD.Polis_Num end as Polis_Num
          FROM
              PersonDeputy PD
              join lateral (
                select 
                  Person_BirthDay,Document_id,UAddress_id,PAddress_id,Sex_id,Person_SurName,Person_FirName, Person_SecName, Person_EdNum, Person_Snils, Polis_id
                from v_Person_bdz PersonState
                where 
                  Person_id = PD.Person_pid and PersonEvn_insDT <= t.evn_setdate
                order by PersonEvn_insDT desc
                limit 1
              ) Pers on true
              left join v_Polis PolisPD on PolisPD.Polis_id =Pers.Polis_id
              where
               PD.Person_id = PersonAll.person_id and Polis.Polis_id is null
               and age(coalesce(t.evn_disdate,t.evn_setdate),PersonAll.Person_BirthDay) < '2 months'::interval 
               and t.evn_setdate::date >= coalesce(PD.persondeputy_begdt::date,p_begdate::date)
              limit 1
        ) Patron on true
          
        left join lateral (
              select pb.address_id from PersonBirthPlace pb 
              where pb.person_id = coalesce(Patron.person_pid,PersonAll.person_id) 
              limit 1
        ) as pb on true 
        left join Address on pb.address_id = Address.address_id
          
        left join dbo.Document doc on doc.document_id = coalesce(Patron.document_id,PersonAll.document_id)
        left join DocumentType doct on doc.documenttype_id = doct.documenttype_id 
          
        left join v_address_kladr kladrU on kladrU.address_id = coalesce(Patron.uaddress_id,PersonAll.uaddress_id)
        left join v_address_kladr kladrP on kladrP.address_id = coalesce(Patron.paddress_id,PersonAll.paddress_id)  
        
    )t
    WHERE 
    	nullif(t.NPOLIS,'') is not null
  
  );  

END;
$_$;


ALTER FUNCTION r477.p_identity_exp_pac(p_lpu_id bigint, p_begdate timestamp without time zone, p_enddate timestamp without time zone) OWNER TO developer_rep;

--
-- Name: p_identity_exp_zap(bigint, timestamp without time zone, timestamp without time zone); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_identity_exp_zap(p_lpu_id bigint, p_begdate timestamp without time zone, p_enddate timestamp without time zone) RETURNS TABLE("N_ZAP" bigint, "ID_PAC" bigint, "VPOLIS" text, "SPOLIS" text, "NPOLIS" text, "ST_OKATO" text, "SMO" text, "SMO_OGRN" text, "SMO_OK" text, "SMO_NAM" text, "IDCASE" bigint, "USL_OK" text, "VIDPOM" text, "DATE_1" text, "DATE_2" text, "CODE_MES1" text, "ED_COL" numeric, "COMENTSL" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_paytype_id bigint = (select paytype_id from v_paytype where paytype_sysnick = 'oms' and paytype_enddate is null limit 1);    
BEGIN
 
--первичный отбор 
create temp table tmp_ident_data on commit drop as  
select 
	EvnVizit.evnvizitpl_id as evn_id,
    EvnClass.evnclass_sysnick,
    EvnVizit.server_id,
    EvnVizit.personevn_id,
    EvnPL.evnpl_setdate as evn_setdate,
    EvnPl.evnpl_disdate as evn_disdate,
    null::bigint as lpuunittype_id
from v_evnpl EvnPL 
 join v_EvnVizitPL as EvnVizit on EvnVizit.EvnVizitPL_pid = EvnPL.EvnPL_id and EvnVizit.EvnVizitPL_Index = EvnVizit.EvnVizitPL_Count - 1 
 join EvnClass on EvnVizit.evnclass_id = EvnClass.evnclass_id
where 
	EvnPL.lpu_id = p_lpu_id 
    and coalesce(EvnPL.evnpl_disdate,EvnPL.evnpl_setdate) between p_begdate and p_enddate
    --and EvnPL.evnpl_isfinish = 2 
    and EvnVizit.paytype_id = _paytype_id 
    
union all         
    
select 
	EvnUsluga.evnuslugapar_id as evn_id,
    EvnClass.evnclass_sysnick,
    EvnUsluga.server_id,
    EvnUsluga.personevn_id,
    EvnUsluga.evnuslugapar_setdate::date as evn_setdate,
    EvnUsluga.evnuslugapar_disdate::date as evn_disdate,
    null::bigint as lpuunittype_id  
from v_EvnUslugaPar EvnUsluga 
 join EvnClass on EvnUsluga.evnclass_id = EvnClass.evnclass_id
where 
	EvnUsluga.lpu_id = p_lpu_id
    and coalesce(EvnUsluga.evnuslugapar_disdate,EvnUsluga.evnuslugapar_setdate) between p_begdate and p_enddate
    and EvnUsluga.paytype_id = _paytype_id 

union all 

select 
	EvnPLDisp.evnpldisp_id as evn_id,
    EvnClass.evnclass_sysnick,
    EvnPLDisp.server_id,
    EvnPLDisp.personevn_id,
    EvnPLDisp.evnpldisp_setdate::date as evn_setdate,
    EvnPLDisp.evnpldisp_disdate::date as evn_disdate,
    null::bigint as lpuunittype_id
from v_EvnPLDisp EvnPLDisp 
 join EvnClass on EvnPLDisp.evnclass_id = EvnClass.evnclass_id
where 
	EvnPLDisp.lpu_id = p_lpu_id
    and coalesce(EvnPLDisp.evnpldisp_disdate,EvnPLDisp.evnpldisp_setdate) between p_begdate and p_enddate
    --and EvnPLDisp.evnpldisp_isfinish = 2 
    and EvnPLDisp.paytype_id = _paytype_id   
    
union all 

select 
	EvnSection.evnsection_id,
    EvnClass.evnclass_sysnick,
    EvnSection.server_id,
    EvnSection.personevn_id,
    EvnPS.evnps_setdate::date as evn_setdate,
    EvnPS.evnps_disdate::date as evn_disdate,
    LpuUnit.lpuunittype_id 
from v_EvnPS EvnPS 
 join v_EvnSection as EvnSection on EvnSection.EvnSection_pid = EvnPS.EvnPS_id and EvnPS.Lpu_id = EvnSection.Lpu_id                                        
 join v_EvnLeaveBase as EvnLeaveBase on EvnLeaveBase.EvnLeaveBase_pid = EvnSection.EvnSection_id and EvnLeaveBase_index = EvnLeaveBase_count - 1
 join EvnClass on EvnSection.evnclass_id = EvnClass.evnclass_id
 join LpuSection on LpuSection.LpuSection_id = EvnSection.LpuSection_id
 join LpuUnit on LpuUnit.LpuUnit_id = LpuSection.LpuUnit_id
where 
	EvnPS.lpu_id = p_lpu_id
    and coalesce(EvnPS.evnps_disdate,EvnPS.evnps_setdate) between p_begdate and p_enddate
	--and EvnSection.LeaveType_id is not null 
    and EvnSection.EvnSection_IsPriem is null
    and EvnSection.paytype_id = _paytype_id 
;


return query (
	
    select 
    
    	t.N_ZAP,
        t.ID_PAC,
        t.VPOLIS,
        t.SPOLIS,
        t.NPOLIS,
        t.ST_OKATO,
        t.SMO,
        t.SMO_OGRN,
        t.SMO_OK,
        t.SMO_NAM,
        t.IDCASE,
        t.USL_OK,
        t.VIDPOM,
        t.DATE_1,  
        t.DATE_2,
        t.CODE_MES1,
        t.ED_COL,
        t.COMENTSL 
    
    from (
        select 
            row_number() over(order by t.evn_id) as N_ZAP,
            PersonAll.person_id as ID_PAC,
            PolisType.polistype_codef008::text as VPOLIS,
            case when Patron.person_pid is null then Polis.Polis_Ser else Patron.Polis_Ser end::text as SPOLIS,
            case when Patron.person_pid is null then case when Polis.PolisType_id = 4 then PersonAll.Person_EdNum else Polis.Polis_Num end else Patron.Polis_Num end::text as NPOLIS,
            coalesce(KLArea.kladr_ocatd::text,nullif(OmsSprTerr.omssprterr_okato,'')) as ST_OKATO,
            null::text as SMO,
            null::text as SMO_OGRN,
            null::text as SMO_OK,
            null::text as SMO_NAM,
            --t.evn_id as IDCASE,
            row_number() over(order by t.evn_id) as IDCASE,
            case 
                when t.evnclass_sysnick = 'EvnSection' then 
                    case when t.lpuunittype_id = 1 then '1' else '2' end 
                else '3'  
            end as USL_OK,
            null::text as VIDPOM,
            to_char(t.evn_setdate,'YYYY-MM-DD') as DATE_1,  
            to_char(t.evn_disdate,'YYYY-MM-DD') as DATE_2,
            null::text as CODE_MES1,
            null::numeric as ED_COL,
            null::text as COMENTSL   
        from tmp_ident_data t 
         join v_Person_BDZ PersonAll on t.server_id = PersonAll.server_id and t.personevn_id = PersonAll.personevn_id
         
         left join v_Polis Polis  on Polis.Polis_id = PersonAll.Polis_id
         
         left join lateral (
             select
                PD.Person_pid,
                PolisPD.Polis_id,
                PolisPD.PolisType_id,
                PolisPD.Polis_Ser,
                case when PolisPD.PolisType_id = 4 then Pers.Person_EdNum else PolisPD.Polis_Num end as Polis_Num,
                OmsSprTerr.OMSSprTerr_id,
                PolisPD.orgsmo_id               
            FROM
                PersonDeputy PD
                join lateral (
                  select Polis_id,Person_EdNum from v_Person_bdz PersonState
                  where 
                    Person_id = PD.Person_pid and PersonEvn_insDT <= t.evn_setdate
                  order by PersonEvn_insDT desc
                  limit 1
                ) Pers on true
                left join v_Polis PolisPD on PolisPD.Polis_id =Pers.Polis_id
                left join v_OmsSprTerr OmsSprTerr on OmsSprTerr.OmsSprTerr_id = PolisPD.OmsSprTerr_id
                where
                 PD.Person_id = PersonAll.person_id and Polis.Polis_id is null
                 and dbo.AgeYMD (PersonAll.Person_BirthDay,t.evn_setdate, 3) <= 28	--возраст меньше 28 дней 
                 and t.evn_setdate::date >= coalesce(PD.persondeputy_begdt::date,current_date)
                limit 1
          ) Patron on true
          
          left join PolisType on PolisType.polistype_id = coalesce(Patron.PolisType_id,Polis.PolisType_id)
          left join v_OmsSprTerr OmsSprTerr on OmsSprTerr.OmsSprTerr_id = coalesce(Polis.OmsSprTerr_id,Patron.OMSSprTerr_id)
          left join OrgSmo on OrgSmo.orgsmo_id = coalesce(Patron.orgsmo_id,Polis.orgsmo_id)
          left join KLArea on OrgSmo.klrgn_id = KLArea.klarea_id 
    
    )t
    WHERE 
    	nullif(t.NPOLIS,'') is not null
    

);

END;
$$;


ALTER FUNCTION r477.p_identity_exp_zap(p_lpu_id bigint, p_begdate timestamp without time zone, p_enddate timestamp without time zone) OWNER TO developer_rep;

--
-- Name: p_militarycategory_del(bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: r477_role
--

CREATE FUNCTION r477.p_militarycategory_del(militarycategory_id bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
begin

--autogen
--project promed
--delete from r477.militarycategory
delete from r477.militarycategory
where militarycategory.militarycategory_id = p_militarycategory_del.militarycategory_id;

exception
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


end; $$;


ALTER FUNCTION r477.p_militarycategory_del(militarycategory_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO r477_role;

--
-- Name: p_militarycategory_ins(bigint, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: r477_role
--

CREATE FUNCTION r477.p_militarycategory_ins(INOUT militarycategory_id bigint DEFAULT NULL::bigint, militarycategory_code character varying DEFAULT NULL::character varying, militarycategory_name character varying DEFAULT NULL::character varying, militarycategory_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, militarycategory_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare
	datetime timestamp = localtimestamp;

begin

--AUTOGEN
--project ProMed
--insert into r477.militarycategory
if pmuser_id = 0
	then pmuser_id := null; end if;

if coalesce(militarycategory_id, 0) = 0
then 
	insert into r477.militarycategory(militarycategory_code, militarycategory_name, militarycategory_begdate, militarycategory_enddate, pmuser_insid, pmuser_updid, militarycategory_insdt, militarycategory_upddt)
	values ( militarycategory_code, militarycategory_name, militarycategory_begdate, militarycategory_enddate, pmuser_id, pmuser_id, datetime, datetime)
	returning militarycategory.militarycategory_id into p_militarycategory_ins.militarycategory_id;
else
	insert into r477.militarycategory(militarycategory_id, militarycategory_code, militarycategory_name, militarycategory_begdate, militarycategory_enddate, pmuser_insid, pmuser_updid, militarycategory_insdt, militarycategory_upddt)
	values (militarycategory_id, militarycategory_code, militarycategory_name, militarycategory_begdate, militarycategory_enddate, pmuser_id, pmuser_id, datetime, datetime);
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_militarycategory_ins(INOUT militarycategory_id bigint, militarycategory_code character varying, militarycategory_name character varying, militarycategory_begdate timestamp without time zone, militarycategory_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO r477_role;

--
-- Name: p_militarycategory_upd(bigint, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: r477_role
--

CREATE FUNCTION r477.p_militarycategory_upd(INOUT militarycategory_id bigint DEFAULT NULL::bigint, militarycategory_code character varying DEFAULT NULL::character varying, militarycategory_name character varying DEFAULT NULL::character varying, militarycategory_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, militarycategory_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare
	datetime timestamp = localtimestamp;

begin

--AUTOGEN
--project ProMed
--update r477.militarycategory
if pmuser_id = 0
	then pmuser_id := null; end if;

update r477.militarycategory
set militarycategory_code = p_militarycategory_upd.militarycategory_code,
militarycategory_name = p_militarycategory_upd.militarycategory_name,
militarycategory_begdate = p_militarycategory_upd.militarycategory_begdate,
militarycategory_enddate = p_militarycategory_upd.militarycategory_enddate,
pmuser_updid = pmuser_id,
militarycategory_upddt = datetime
where militarycategory.militarycategory_id = p_militarycategory_upd.militarycategory_id;

EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_militarycategory_upd(INOUT militarycategory_id bigint, militarycategory_code character varying, militarycategory_name character varying, militarycategory_begdate timestamp without time zone, militarycategory_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO r477_role;

--
-- Name: p_orgmilitarytype_del(bigint, bigint, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytype_del(orgmilitarytype_id bigint, pmuser_id bigint DEFAULT NULL::bigint, isremove bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--autogen
--project promed
--delete from r477.orgmilitarytype
if (coalesce(isremove,1)=2) then
	delete from r477.orgmilitarytype
	where orgmilitarytype.orgmilitarytype_id = p_orgmilitarytype_del.orgmilitarytype_id;
else
	update r477.orgmilitarytype
	set 
	pmuser_delid=pmuser_id,
	orgmilitarytype_deldt=dbo.tzGetDate(),
	orgmilitarytype_deleted=2
	where orgmilitarytype.orgmilitarytype_id = p_orgmilitarytype_del.orgmilitarytype_id;
end if;

exception
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


end; $$;


ALTER FUNCTION r477.p_orgmilitarytype_del(orgmilitarytype_id bigint, pmuser_id bigint, isremove bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_orgmilitarytype_ins(bigint, character varying, character varying, bigint, timestamp without time zone, timestamp without time zone, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytype_ins(INOUT orgmilitarytype_id bigint DEFAULT NULL::bigint, orgmilitarytype_code character varying DEFAULT NULL::character varying, orgmilitarytype_name character varying DEFAULT NULL::character varying, klcountry_id bigint DEFAULT NULL::bigint, orgmilitarytype_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgmilitarytype_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare datetime timestamp = dbo.tzgetdate();

begin

--AUTOGEN
--project ProMed
--insert into r477.orgmilitarytype
if pmuser_id = 0
	then pmuser_id := null; end if;

if coalesce(orgmilitarytype_id, 0) = 0
then 
	insert into r477.orgmilitarytype(orgmilitarytype_code, orgmilitarytype_name, klcountry_id, orgmilitarytype_begdate, orgmilitarytype_enddate, pmuser_insid, pmuser_updid, orgmilitarytype_insdt, orgmilitarytype_upddt)
	values ( orgmilitarytype_code, orgmilitarytype_name, klcountry_id, orgmilitarytype_begdate, orgmilitarytype_enddate, pmuser_id, pmuser_id, datetime, datetime)
	returning orgmilitarytype.orgmilitarytype_id into p_orgmilitarytype_ins.orgmilitarytype_id;
else
	insert into r477.orgmilitarytype(orgmilitarytype_id, orgmilitarytype_code, orgmilitarytype_name, klcountry_id, orgmilitarytype_begdate, orgmilitarytype_enddate, pmuser_insid, pmuser_updid, orgmilitarytype_insdt, orgmilitarytype_upddt)
	values (orgmilitarytype_id, orgmilitarytype_code, orgmilitarytype_name, klcountry_id, orgmilitarytype_begdate, orgmilitarytype_enddate, pmuser_id, pmuser_id, datetime, datetime);
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_orgmilitarytype_ins(INOUT orgmilitarytype_id bigint, orgmilitarytype_code character varying, orgmilitarytype_name character varying, klcountry_id bigint, orgmilitarytype_begdate timestamp without time zone, orgmilitarytype_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_orgmilitarytype_upd(bigint, character varying, character varying, bigint, timestamp without time zone, timestamp without time zone, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytype_upd(INOUT orgmilitarytype_id bigint DEFAULT NULL::bigint, orgmilitarytype_code character varying DEFAULT NULL::character varying, orgmilitarytype_name character varying DEFAULT NULL::character varying, klcountry_id bigint DEFAULT NULL::bigint, orgmilitarytype_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgmilitarytype_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare datetime timestamp = dbo.tzgetdate();

begin

--AUTOGEN
--project ProMed
--update r477.orgmilitarytype
if pmuser_id = 0
	then pmuser_id := null; end if;

update r477.orgmilitarytype
set orgmilitarytype_code = p_orgmilitarytype_upd.orgmilitarytype_code,
orgmilitarytype_name = p_orgmilitarytype_upd.orgmilitarytype_name,
klcountry_id = p_orgmilitarytype_upd.klcountry_id,
orgmilitarytype_begdate = p_orgmilitarytype_upd.orgmilitarytype_begdate,
orgmilitarytype_enddate = p_orgmilitarytype_upd.orgmilitarytype_enddate,
pmuser_updid = pmuser_id,
orgmilitarytype_upddt = datetime

where orgmilitarytype.orgmilitarytype_id = p_orgmilitarytype_upd.orgmilitarytype_id;

EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_orgmilitarytype_upd(INOUT orgmilitarytype_id bigint, orgmilitarytype_code character varying, orgmilitarytype_name character varying, klcountry_id bigint, orgmilitarytype_begdate timestamp without time zone, orgmilitarytype_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_orgmilitarytypelink_del(bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytypelink_del(orgmilitarytypelink_id bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--autogen
--project promed
--delete from r477.orgmilitarytypelink
delete from r477.orgmilitarytypelink
where orgmilitarytypelink.orgmilitarytypelink_id = p_orgmilitarytypelink_del.orgmilitarytypelink_id;

exception
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


end; $$;


ALTER FUNCTION r477.p_orgmilitarytypelink_del(orgmilitarytypelink_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_orgmilitarytypelink_ins(bigint, bigint, bigint, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytypelink_ins(INOUT orgmilitarytypelink_id bigint DEFAULT NULL::bigint, orgmilitarytype_id bigint DEFAULT NULL::bigint, org_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare datetime timestamp = dbo.tzgetdate();

begin

--AUTOGEN
--project ProMed
--insert into r477.orgmilitarytypelink
if pmuser_id = 0
	then pmuser_id := null; end if;

if coalesce(orgmilitarytypelink_id, 0) = 0
then 
	insert into r477.orgmilitarytypelink(orgmilitarytype_id, org_id, pmuser_insid, pmuser_updid, orgmilitarytypelink_insdt, orgmilitarytypelink_upddt)
	values ( orgmilitarytype_id, org_id, pmuser_id, pmuser_id, datetime, datetime)
	returning orgmilitarytypelink.orgmilitarytypelink_id into p_orgmilitarytypelink_ins.orgmilitarytypelink_id;
else
	insert into r477.orgmilitarytypelink(orgmilitarytypelink_id, orgmilitarytype_id, org_id, pmuser_insid, pmuser_updid, orgmilitarytypelink_insdt, orgmilitarytypelink_upddt)
	values (orgmilitarytypelink_id, orgmilitarytype_id, org_id, pmuser_id, pmuser_id, datetime, datetime);
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_orgmilitarytypelink_ins(INOUT orgmilitarytypelink_id bigint, orgmilitarytype_id bigint, org_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_orgmilitarytypelink_upd(bigint, bigint, bigint, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_orgmilitarytypelink_upd(INOUT orgmilitarytypelink_id bigint DEFAULT NULL::bigint, orgmilitarytype_id bigint DEFAULT NULL::bigint, org_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

declare datetime timestamp = dbo.tzgetdate();

begin

--AUTOGEN
--project ProMed
--update r477.orgmilitarytypelink
if pmuser_id = 0
	then pmuser_id := null; end if;

update r477.orgmilitarytypelink
set orgmilitarytype_id = p_orgmilitarytypelink_upd.orgmilitarytype_id,
org_id = p_orgmilitarytypelink_upd.org_id,
pmuser_updid = pmuser_id,
orgmilitarytypelink_upddt = datetime

where orgmilitarytypelink.orgmilitarytypelink_id = p_orgmilitarytypelink_upd.orgmilitarytypelink_id;

EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_orgmilitarytypelink_upd(INOUT orgmilitarytypelink_id bigint, orgmilitarytype_id bigint, org_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_registry_del(bigint, bigint, integer, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_del(p_registry_id bigint, p_pmuser_delid bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare 

--p_Registry_IsZNO int := (select Registry_IsZNO from r477.Registry where Registry_id = p_Registry_id)  ;
_registry_type_code text = r477.p_registry_get_registry_type_code(p_registry_id);

begin


if exists (select 1 from r477.v_RegistryQueue where Registry_id = p_Registry_id) then

 RAISE EXCEPTION 'Нельзя удалить реестра %', p_registry_id;

end if;


update r477.Registry 
set 
	Registry_deleted = 2,
	pmUser_delID = p_pmUser_delID, 
	Registry_delDT = current_date
where 
	Registry_id = p_Registry_id
;


if _registry_type_code in ('omspol','emergency','resemdent', 'pol_bug_palliativ', 'parakl_budg','parusl' ) then 

    update EvnVizit 
    set 
        EvnVizit_IsInReg = 1
    where 
        Evn_id in (select Evn_id from r477.RegistryData where Registry_id = p_Registry_id)
        and EvnVizit_IsInReg = 2
    ;

    if _registry_type_code in ('resemdent', 'parakl_budg','parusl') then 
            
        --параклинические услуги 
        update EvnUslugaPar 
        set 
            evnusluga_isinreg = 1	
        where 
            Evn_id in (select Evn_id from r477.RegistryData where Registry_id = p_Registry_id)
            and evnusluga_isinreg = 2 
        ;
            
    end if;


elsif _registry_type_code in ('omsstac','htm','omsks','0901','omsds', '0901_1','0901_2') then

	update Evnsection 
    set 	
    	EvnSection_IsInReg = 1
	where 
    	Evn_id in (select Evn_id from r477.RegistryData where Registry_id = p_Registry_id)
        and EvnSection_IsInReg = 2 
    ;
    
elsif _registry_type_code in ('medexam') then 

	update EvnPLDisp 
	set 
    	EvnPLDisp_IsInReg = 1
	where
		Evn_id in (select Evn_id from r477.RegistryData where Registry_id = p_Registry_id)
    	and EvnPLDisp_IsInReg = 2 
	;	

end if;


exception
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;

end;
$$;


ALTER FUNCTION r477.p_registry_del(p_registry_id bigint, p_pmuser_delid bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_registry_evnpl_get_item_type(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpl_get_item_type(p_evnpl_id bigint) RETURNS text
    LANGUAGE plpgsql
    AS $$
DECLARE
	_item_type TEXT; 
	_is_neotl BOOLEAN;
	_r RECORD;
	_attr_arr TEXT[];
	_kmu_code_arr TEXT[];
	_isvizitcode BOOLEAN; -- Признак поля "Код посещения"
	_vizitcode TEXT; -- Код услуги из поля "Код посещения"
	_per_capita_other_code_arr TEXT[] := ARRAY[
		'1', '2', '41', '42', '60', '61', '708', '709', '714', '742', '743', '748', '788', '905', '926', '938', 
		'939', '963', '964', '970', '971', '972', '973', '974', '975', '976', '977'
		]::TEXT[]; -- Тарифные профили для Поликлиника (вне подушевого) - per_capita_other 
	_evnplstom_class_id INTEGER := (SELECT evnclass_id FROM evnclass WHERE evnclass_sysnick = 'EvnPLStom' LIMIT 1); -- Лечение в стоматологии
BEGIN

	--определяем по последнему посещению
	SELECT 
		pl.evnpl_setdate::date AS open_date,
		pl.evnpl_disdate::date AS close_date,
		COALESCE(t.treatmentclass_code,'') = '1.1' AS is_neotl,
		pl.evnpl_vizitcount AS vizit_count,
		lsp.lpusectionprofile_code::text as lpusectionprofile_code,
		COALESCE(vt.vizittype_sysnick, '') = 'dial' AS is_dial,
		pl.evnclass_id = _evnplstom_class_id AS is_stom,
		v.evnvizitpl_id AS last_id,
		lpu.lpu_f003mcod as lpu_f003mcod
	INTO _r 	
	FROM v_evnpl pl 
	JOIN v_evnvizitpl v ON v.EvnVizitPL_pid = pl.EvnPL_id and v.EvnVizitPL_Index = v.EvnVizitPL_Count - 1
	join v_lpu lpu on pl.lpu_id =lpu.lpu_id 
	LEFT JOIN v_vizittype AS vt ON v.vizittype_id = vt.vizittype_id
	LEFT JOIN treatmentclass t ON v.treatmentclass_id = t.treatmentclass_id 
	LEFT JOIN LpuSection ls ON ls.LpuSection_id = v.LpuSection_id
	LEFT JOIN LpuSectionProfile lsp ON lsp.LpuSectionProfile_id = COALESCE(v.lpusectionprofile_id,ls.LpuSectionProfile_id)
	WHERE pl.evnpl_id = p_evnpl_id; 

--получаем атрибуты услуг случая
_attr_arr = ARRAY(
    SELECT DISTINCT t.uslugacomplexattributetype_sysnick FROM v_evnusluga u 
     JOIN v_uslugacomplex cx on u.uslugacomplex_id = cx.uslugacomplex_id
     JOIN v_uslugacomplexattribute a ON u.uslugacomplex_id = a.uslugacomplex_id
     JOIN v_uslugacomplexattributetype t ON a.uslugacomplexattributetype_id = t.uslugacomplexattributetype_id 
    WHERE 
        u.evnusluga_rid = p_evnpl_id
        and _r.close_date between coalesce(a.uslugacomplexattribute_begdate::date,'-infinity'::date) and coalesce(a.uslugacomplexattribute_enddate::date,'infinity'::Date)
				-- пока закоментировано поскольку является частью Адыгейского кода и возможно не требуется на Тамбове

)
;
	-- хотя бы в одном посещении случая заполнено поле Код посещения;
	_isvizitcode = EXISTS (SELECT 1 FROM v_evnusluga AS u WHERE u.evnusluga_rid = p_evnpl_id AND u.evnusluga_isvizitcode = 2);

	--raise notice '_attr_arr = %',_attr_arr;
	--raise notice '_r.lpusectionprofile_code = %',_r.lpusectionprofile_code;

	--определяем код услуги из поля "Код посещения"
	IF _isvizitcode THEN 
		_vizitcode = ( 
			SELECT cx.uslugacomplex_code 
			FROM v_evnusluga AS u 
			JOIN v_uslugacomplex AS cx on u.uslugacomplex_id = cx.uslugacomplex_id 
			WHERE u.evnusluga_rid = p_evnpl_id AND u.evnusluga_isvizitcode = 2
			ORDER BY u.evnusluga_pid = _r.last_id DESC 
			LIMIT 1
			);          
	END IF;



	_item_type =
		CASE
			WHEN _r.is_dial THEN 'dializ'
			WHEN _r.is_stom AND 'stom' = ANY(_attr_arr) THEN 
				CASE 
					WHEN _r.is_neotl THEN 'stomat_neotl' 
					ELSE 'stomat' 
				END
			when _isvizitcode and _vizitcode in ('bPALL_A','bPALL_P') then 'pall_budg'
			WHEN 'priem' <> ALL(_attr_arr) AND NOT _isvizitcode AND ARRAY['lab', 'xray', 'parusl', 'mrt', 'kt', 'func'] && _attr_arr THEN 
				CASE
					WHEN 'lab' = ANY(_attr_arr) THEN 'isl_lab'
					WHEN 'xray' = ANY(_attr_arr) THEN 'isl_xray'
					WHEN 'parusl' = ANY(_attr_arr) THEN 'isl_parusl'
					WHEN 'mrt' = ANY(_attr_arr) THEN 'isl_mrt'
					WHEN 'kt' = ANY(_attr_arr) THEN 'isl_kt'
					WHEN 'func' = ANY(_attr_arr) THEN 'isl_func'
				END
			WHEN 'priem' = ANY(_attr_arr) OR _isvizitcode THEN 
				concat(
					CASE 
						WHEN _r.vizit_count >= 2 AND _r.close_date - _r.open_date + 1 > 3 THEN 'priem_obr' 
						ELSE 'priem_prof' 
					END, --обращение/посещение
					'.' || 
					CASE 
						WHEN _isvizitcode THEN 
							CASE 
							-- Для МО из списка в реестр "Поликлиника (вне подушевого)" отбираются все тарифные профили.
								WHEN _vizitcode = ANY(_per_capita_other_code_arr) or _r.lpu_f003mcod in ('680090', '680092', '680094', '680095', '680097', '680098', '680099', '680101') THEN 'other' 
								ELSE 'ownalien' 
							END 
						ELSE 'no' -- если тарифного профиля нет, то куда попадет случай будет зависеть от того, где он застрахован
					END -- помечаем случаи по Тарифному профилю
					)
			ELSE 'undefined' -- не удалось определить тип случая
		END;


 
RETURN _item_type;

EXCEPTION 
	when others then 
    	raise notice 'Error function r477.p_registry_evnpl_get_item_type EvnPL.evn_id = %',p_evnpl_id; 
        raise;

END;
$$;


ALTER FUNCTION r477.p_registry_evnpl_get_item_type(p_evnpl_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_evnpl_get_tariff(text, text, integer, date, jsonb); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpl_get_tariff(p_item_type text, p_code_usl text, p_person_age integer, p_on_date date, p_params jsonb, OUT tariff numeric, OUT tariff_code text) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE
	_tariff_code TEXT;    
	_tariff_one_day_code TEXT; 
	_fname TEXT;
	_tariff NUMERIC;
	_spec_code TEXT;
	_pay_type_code TEXT := p_params ->> 'pay_type_code';
BEGIN

	IF _pay_type_code = 'regional' THEN
		SELECT NULL::TEXT, 
		r477.tambov_fin_get_value_dev(
			jsonb_build_object(
				'object_code', case when p_item_type='pall_budg' then 'ambulatory_palliative_budget' 	-- Поликлиника паллиативная помощь (бюджет региональный)
									when p_item_type='parakl_budg' then 'br_paraclinic' 				-- Параклиника (бюджет региональный)		
									else 'ambulatory_budget' end, 										-- Поликлиника (бюджет региональный)
				'object_type', 'dbo.TariffClass', 
				'p_date', p_on_date,
				'lpu_id', p_params ->> 'lpu_id', 
				'lpusectionprofile_id', p_params ->> 'lpusectionprofile_id',
				'uslugacomplex_id', p_params ->> 'uslugacomplex_id'
				)
			)
		INTO _tariff_code, _tariff;
	ELSE
		IF p_item_type ~ '^stomat' THEN
			SELECT CASE WHEN (p_params ->> 'is_vizitcode')::BOOLEAN THEN UPPER(TRIM(p_code_usl)) ELSE NULL END,
			r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', 'БСУЕТ', 'object_type', 'dbo.TariffClass', 'p_date', p_on_date)) 
			INTO _tariff_code, _tariff;
		ELSIF p_item_type ~ 'dializ' THEN
			SELECT CASE WHEN (p_params ->> 'is_vizitcode')::BOOLEAN THEN UPPER(TRIM(p_code_usl)) ELSE NULL END,
			r477.getevnuslugaprice((p_params ->> 'evnusluga_id')::BIGINT) 
			INTO _tariff_code, _tariff;
		ELSE
			SELECT division, sl INTO _tariff_code, _tariff
			FROM r477.terr007 AS t
			WHERE UPPER(TRIM(t.division)) = UPPER(TRIM(p_code_usl))
			AND TRIM(t.org_id) = TRIM(COALESCE(p_params ->> 'org_id', ''))
			AND t.idsp = (p_params ->> 'idsp')::INTEGER
			AND p_on_date >= to_date(concat(t.year_per, t.month_per), 'YYYYMM')
			ORDER BY to_date(concat(t.year_per, t.month_per), 'YYYYMM') DESC 
			LIMIT 1;
			
			IF p_item_type ~ '^isl' AND COALESCE(_tariff, 0) = 0 THEN
				SELECT UPPER(TRIM(p_code_usl)), r477.getevnuslugaprice((p_params ->> 'evnusluga_id')::BIGINT) INTO _tariff_code, _tariff;
			END IF;
		END IF;
	END IF;

    
    
    tariff_code = _tariff_code;
    tariff 		= COALESCE(_tariff,0);

END;
$$;


ALTER FUNCTION r477.p_registry_evnpl_get_tariff(p_item_type text, p_code_usl text, p_person_age integer, p_on_date date, p_params jsonb, OUT tariff numeric, OUT tariff_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_ds2_n(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_ds2_n(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(evn_id bigint, diag_id bigint, "DS2" text, "DS2_PR" integer, "PR_DS2_N" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _disp_code_arr 		text[];
BEGIN

  if p_disp_code is not null then 
	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
  end if;	
    
  return query (
	
    select distinct
        rd.evn_id,
        DiagSop.Diag_id as diag_id,
        case when length(DiagSop.diag_code) = 4 then left(DiagSop.Diag_Code,3) else DiagSop.Diag_Code  end::text as DS2,
        case when EvnDiagDopDisp.deseasedisptype_id = 2 then 1 else null end as DS2_PR,
        coalesce(PersonDisp.pr_d_n,3) as PR_DS2_N
    from 
        r477.registrydata rd 
         join v_EvnDiagDopDisp EvnDiagDopDisp on EvnDiagDopDisp.evndiagdopdisp_rid = rd.evn_id
         join Diag DiagSop on DiagSop.Diag_id = EvnDiagDopDisp.Diag_id
         
         left join lateral (
            select 
                case when PD.persondisp_begdate < rd.evn_setdate then 1 else 2 end as pr_d_n 	
            from v_PersonDisp PD 
             join Diag pd_diag on PD.diag_id = rd.diag_id
            where 
                PD.PErson_id = rd.Person_id and left(DiagSop.diag_code,3) = left(pd_diag.diag_code,3)
                and PD.persondisp_begdate <= rd.evn_disdate 
            order by PersonDisp_begDate desc
            limit 1
         ) PersonDisp on true
    where 
      rd.registry_id = any(_registry_id_arr) 
      and EvnDiagDopDisp.diagsetclass_id = 3 --сопутствующий диагноз 
      and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end
      and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
                 	
  );  

END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_ds2_n(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_naz(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_naz(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(evn_id bigint, "NAZ_N" integer, "NAZ_R" integer, "NAZ_SP" integer, "NAZ_V" integer, "NAZ_USL" text, "NAPR_DATE" text, "NAPR_MO" text, "NAZ_PMP" integer, "NAZ_PK" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _disp_code_arr 		text[];
BEGIN

  if p_disp_code is not null then 
	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
  end if;	
    
  return query (
	
    select distinct 
          rd.evn_id,
          (row_number() over(partition by rd.evn_id order by DispAppoint.dispappoint_id))::integer as NAZ_N,
          DispAppointtype.dispappointtype_code::integer as NAZ_R,
          case when DispAppointtype.dispappointtype_code in ('1','2') then msc.MedSpecClass_code::integer end as NAZ_SP,
          case when DispAppointtype.dispappointtype_code = '3' then ExaminationType.ExaminationType_Code::integer end as NAZ_V,
          case when DispAppointtype.dispappointtype_code = '3' and rd.region_data ->> 'ds_onk' = '1' then ED_ter_usl.uslugacomplex_code::text end as NAZ_USL, 
          case 
              when DispAppointtype.dispappointtype_code = '3' and rd.region_data ->> 'ds_onk' = '1' then 
                  to_char(ed_ter_usl.evndirection_setdate,'YYYY-MM-DD')
              when DispAppointtype.dispappointtype_code = '2' and rd.region_data ->> 'ds_onk' = '1' then 
                  to_char(ed_ter_spec.evndirection_setdate,'YYYY-MM-DD')
          end as NAPR_DATE,
          case 
              when DispAppointtype.dispappointtype_code = '3' and rd.region_data ->> 'ds_onk' = '1' then ed_ter_usl.lpu_f003mcod
              when DispAppointtype.dispappointtype_code = '2' and rd.region_data ->> 'ds_onk' = '1' then ed_ter_spec.lpu_f003mcod
          end::text as NAPR_MO,
          case when DispAppointtype.dispappointtype_code in ('4','5') then LSP.LpuSectionProfile_Code::integer end as NAZ_PMP,
          case when DispAppointtype.dispappointtype_code = '6' then LSBP.LpuSectionBedProfile_Code::integer end as NAZ_PK
      from 
          r477.registrydata rd 
           join v_DispAppoint DispAppoint on rd.evn_id = DispAppoint.evnpldisp_id 
           join DispAppointtype on DispAppointtype.dispappointtype_id = DispAppoint.dispappointtype_id
           left join v_MedSpecOms mso on DispAppoint.MedSpecOms_id = mso.MedSpecOms_id
           left join fed.MedSpecClass msc on mso.MedSpecClass_id = msc.MedSpecClass_id
           left join ExaminationType on DispAppoint.ExaminationType_id = ExaminationType.ExaminationType_id
           left join fed.LpuSectionProfile LSP on DispAppoint.LpuSectionProfile_id = LSP.LpuSectionProfile_id
           left join fed.LpuSectionBedProfile LSBP on DispAppoint.LpuSectionBedProfile_id = LSBP.LpuSectionBedProfile_id
           
           left join lateral (
              select 
                  u.UslugaComplex_Code, ED_ter.EvnDirection_setDate,lpu.Lpu_f003mcod
              from v_EvnDirection ED_ter 
               join UslugaComplex u on u.uslugacomplex_id = ED_ter.UslugaComplex_did          
               left join v_Lpu Lpu  on Lpu.lpu_id = ED_ter.lpu_did
              where 
                ED_ter.evndirection_rid = rd.evn_id
                and ED_ter.DirType_id = 10 --направление на исследование 
                and ED_ter.DirFailType_id is null
                and exists (
                    select 1 from UslugaComplexAttribute uca 
                     join v_UslugaComplexAttributeType uct on uca.uslugacomplexattributetype_id = uct.uslugacomplexattributetype_id
                    where 
                        uca.uslugacomplex_id = u.uslugacomplex_id 
                        and rd.evn_disdate::date <@ daterange(uca.uslugacomplexattribute_begdate::date,uca.uslugacomplexattribute_enddate::date,'[]') 
                        and case ExaminationType.ExaminationType_Code 
                                when '4' then uct.uslugacomplexattributetype_sysnick in ('kt','mrt')
                                when '3' then uct.uslugacomplexattributetype_sysnick = 'ray'
                                when '2' then uct.uslugacomplexattributetype_sysnick in ('func','diagisl')
                                when '1' then uct.uslugacomplexattributetype_sysnick = 'lab' 
                            end 
                )
              order by 
                  ED_ter.evndirection_pid = (rd.region_data ->> 'last_vizit_id')::bigint desc, --приоритет направление от терапевта или педиатра 
                  ED_ter.EvnDirection_insDT
              limit 1
          ) ED_ter_usl on true
          
          left join lateral (
              select 
                  ED_ter.EvnDirection_setDate,lpu.Lpu_f003mcod
              from v_EvnDirection ED_ter 
               left join v_Lpu Lpu  on Lpu.lpu_id = ED_ter.lpu_did
                where 
                  ED_ter.evndirection_rid = rd.evn_id
                  and ED_ter.DirType_id in (3,16) --на консультацию/поликлинический прием 
                  and ED_ter.DirFailType_id is null
                  and ED_ter.lpu_did != ED_ter.lpu_id
              order by 
                  ED_ter.evndirection_pid = (rd.region_data ->> 'last_vizit_id')::bigint desc, --приоритет направление от терапевта или педиатра 
                  ED_ter.EvnDirection_insDT
              limit 1
          ) ED_ter_spec on true
      where 
          rd.registry_id = any(_registry_id_arr) 
          and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end
          and not coalesce(rd.region_data ->> 'rslt_d','') in ('1','2')	--кроме 1 и 2 группы здоровья
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
                 	
  );  

END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_naz(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_pac(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_pac(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(person_id bigint, "ID_PAC" text, "FAM" text, "IM" text, "OT" text, "W" text, "DR" text, "TEL" text, "FAM_P" text, "IM_P" text, "OT_P" text, "W_P" text, "DR_P" text, "MR" text, "DOCTYPE" text, "DOCSER" text, "DOCNUM" text, "DOCDATE" text, "DOCORG" text, "SNILS" text, "OKATOG" text, "OKATOP" text, "COMENTP" text)
    LANGUAGE plpgsql
    AS $_$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
        _disp_code_arr 		text[];
    BEGIN
    
if p_disp_code is not null then 
  _disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
end if;
    
return query (
	
    select distinct 
    	t.person_id,
        t.ID_PAC,    
        t.FAM,
        t.IM,
        t.OT,
        t.W,
        t.DR,
        t.TEL,
        t.FAM_P,
        t.IM_P,
        t.OT_P,
        t.W_P,
        t.DR_P,
        t.MR,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCTYPE
        end as DOCTYPE,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCSER
        end as DOCSER,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCNUM
        end as DOCNUM,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCDATE
        end as DOCDATE,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCORG
        end as DOCORG,
        t.SNILS,
        t.OKATOG,
        t.OKATOP,
        t.COMENTP
    from (
        select 
            rd.person_id,
            rd.person_id::text as ID_PAC,    
            case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'surname' else null end as FAM,
            case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'firname' else null end as IM,
            case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'secname' else null end as OT,
            coalesce(rd.region_data -> 'person' ->> 'sex_id','1')::text as W,
            to_char((rd.region_data -> 'person' ->> 'birthday')::date,'YYYY-MM-DD') as DR,
            null::text as TEL,
            rd.region_data -> 'deputy' ->> 'surname' as FAM_P,
            rd.region_data -> 'deputy' ->> 'firname' as IM_P,
            rd.region_data -> 'deputy' ->> 'secname' as OT_P,
            case when rd.region_data -> 'deputy' is not null then coalesce(rd.region_data -> 'deputy' ->> 'sex_id','1') else null end as W_P,
            to_char((rd.region_data -> 'deputy' ->> 'birthday')::date,'YYYY-MM-DD') as DR_P,
            left(Address.address_address,100) as MR,
            doct.documenttype_code::text AS DOCTYPE,
            case 
                when nullif(trim(doc.document_ser),'') is not null then 
                    case doct.documenttype_code
                        when '14' then regexp_replace(trim(doc.document_ser), '(^[0-9]{2})([0-9]{2}$)', '\1 \2')
                        when '3' then regexp_replace(trim(doc.document_ser), '(^[IVXLCDM]{1,3})([А-Я]{2}$)', '\1-\2')
                        else trim(doc.document_ser) 
                    end 
                else null 
            end as DOCSER,
            nullif(trim(doc.document_num),'') as DOCNUM,
            to_char(doc.document_begdate,'YYYY-MM-DD') as DOCDATE,
            nullif(trim(org.org_nick),'') as DOCORG,
            regexp_replace(
                coalesce(rd.region_data -> 'deputy' ->> 'snils',rd.region_data -> 'person' ->> 'snils'),
                '(...)(...)(...)(..)','\1-\2-\3 \4'
            ) as SNILS,
            kladrU.kladr_ocatd as OKATOG,
            kladrP.kladr_ocatd as OKATOP,
            null::text as COMENTP,
            rd.region_data -> 'polis' ->> 'vpolis' as vpolis
        from r477.registry r 
         join r477.registrydata rd on rd.registry_id = r.registry_id
           
         left join lateral (
            select pb.address_id from PersonBirthPlace pb 
            where pb.person_id = coalesce((rd.region_data -> 'deputy' ->> 'person_id')::bigint,rd.person_id) 
            limit 1
         ) as pb on true 
         left join Address on pb.address_id = Address.address_id
           
         left join dbo.Document doc on doc.document_id = coalesce(rd.region_data -> 'deputy' ->> 'document_id',rd.region_data -> 'person' ->> 'document_id')::bigint  
         left join DocumentType doct on doc.documenttype_id = doct.documenttype_id 
         left join OrgDep on OrgDep.orgdep_id = doc.orgdep_id 
         left join Org on Org.org_id = OrgDep.org_id
           
         left join v_address_kladr kladrU on kladrU.address_id = coalesce(rd.region_data -> 'deputy' ->> 'uaddress_id',rd.region_data -> 'person' ->> 'uaddress_id')::bigint 
         left join v_address_kladr kladrP on kladrP.address_id = coalesce(rd.region_data -> 'deputy' ->> 'paddress_id',rd.region_data -> 'person' ->> 'paddress_id')::bigint  
           
        where 
            r.registry_id = any(_registry_id_arr)
            and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end
            and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
    )t
    
);
	END;
$_$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_pac(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_pac_zglv(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_pac_zglv(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(registry_id bigint, "VERSION" text, "DATA" text, "FILENAME" text, "FILENAME1" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	
BEGIN



return query (
 
 select
    p_registry_id as registry_id,
    '3.2'::text as VERSION,
    to_char(current_date,'YYYY-MM-DD') as DATA,
    'L'||t.filename as FILENAME,
    'D'||t.filename as FILENAME1
 from (
    select 
    	concat(
          'M',Lpu.lpu_f003mcod,
          case when KatNasel.katnasel_sysnick = 'oblast' then 'S' else 'T' end,
          case when KatNasel.katnasel_sysnick = 'oblast' then OrgSMO.orgsmo_f002smocod else '68000' end,
          '_',to_char(r.registry_enddate,'YY'),to_char(r.registry_enddate,'MM')
    	) as filename
    from r477.Registry r  
     join Lpu on Lpu.Lpu_id = r.Lpu_id
     left join OrgSMO on OrgSMO.OrgSMO_id = r.OrgSmo_id
     left join KatNasel on r.katnasel_id = KatNasel.katnasel_id  
    where 
        r.Registry_id = p_Registry_id
 )t
 
);
END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_pac_zglv(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_sl(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_sl(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(registry_id bigint, evn_id bigint, maxevn_id bigint, person_id bigint, "SL_ID" bigint, "LPU_1" text, "PODR" text, "PROFIL" text, "DET" integer, "P_CEL" text, "NHISTORY" text, "DISP" text, "DATE_1" text, "DATE_2" text, "DS1" text, "DS1_PR" integer, "DS_ONK" integer, "C_ZAB" integer, "PR_D_N" integer, "CODE_MES1" text, "PRVS" integer, "VERS_SPEC" text, "IDDOKT" text, "ED_COL" numeric, "TARIF" numeric, "SUM_M" numeric, "COMENTSL" text)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
        _lpu_code 			text;
        _disp_code_arr 		text[];
	BEGIN
    
	if p_disp_code is not null then 
    	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
    end if;
    
    _lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);      
   	    
    return query (
	
		select 
            rd.registry_id,
            rd.evn_id,
            rd.evn_id as maxevn_id,
            rd.person_id,    
            rd.evn_id as SL_ID,
            null as LPU_1,
            uc_podr.uslugacomplex_code::text as PODR,
            lsp.lpusectionprofile_code::text as PROFIL,
            case when lsp.lpusectionprofile_code in ('17','18','19','20','21','55','68','83','86') 
              or (rd.region_data -> 'person' ->> 'age')::integer < 18 then 1 else 0 end as DET,
            case when cast(rd.region_data -> 'dispclass' as integer) in (5,6,9,10,11,12) then '2.1' else '2.2' end as P_CEL,
            rd.numcard::text AS NHISTORY,
            rd.region_data ->> 'disp' as DISP,
            to_char(rd.evn_setdate::date,'YYYY-MM-DD') as DATE_1,
            to_char(rd.evn_disdate::date,'YYYY-MM-DD') as DATE_2,
            Diag.diag_scode::text as DS1,
            case 
            	when  EvnVizitDispOrp.dopdispdiagtype_id = 2 then 1 
                when EvnVizitDispDop.dopdispdiagtype_id = 2 then 1 
                else 0  
            end::integer as ds1_pr,
            coalesce(rd.region_data ->> 'ds_onk','0')::integer  as DS_ONK,
            case when left(Diag.diag_code,1) != 'Z' then
            	case 
            		when EvnVizitDispOrp.dopdispdiagtype_id = 2 then 2 
                	when EvnVizitDispDop.dopdispdiagtype_id = 2 then 2 
                	else 3 
            end end::integer as C_ZAB,
            coalesce(PersonDisp.pr_d_n,3) as PR_D_N,
            rd.region_data ->> 'tariff_code' as CODE_MES1,   
            ms.medspecclass_code::integer as PRVS,
            'V021' as VERS_SPEC,
            rd.medpersonal_fio::text as IDDOKT,
            (rd.region_data ->> 'ed_col')::numeric  as ED_COL,
           coalesce(rd.registrydata_tariff,0)::numeric(15,2) as TARIF,
            coalesce(rd.registrydata_itogsum,0)::numeric(15,2) as SUM_M,
            null::text as COMENTSL
        from 
            r477.registrydata rd 
             left join LpuSection on LpuSection.lpusection_id = rd.lpusection_id
             left join LpuUnit on LpuSection.lpuunit_id = LpuUnit.lpuunit_id
             left join LpuBuilding on LpuUnit.lpubuilding_id = LpuBuilding.lpubuilding_id
             left join Diag on Diag.diag_id = rd.diag_id
             left join fed.MedSpecClass ms on rd.medspec_id = ms.medspecclass_id
             left join LpuSectionProfile on LpuSection.lpusectionprofile_id = LpuSectionProfile.lpusectionprofile_id
             left join fed.LpuSectionProfile lsp on lsp.lpusectionprofile_id = LpuSectionProfile.LpuSectionProfile_fedid
             left join v_uslugacomplex uc_podr on (rd.region_data ->> 'podr_id')::bigint = uc_podr.uslugacomplex_id
             
             left join EvnVizitDispDop on (rd.region_data ->> 'last_vizit_id')::bigint = EvnVizitDispDop.evn_id
             left join EvnVizitDispOrp on (rd.region_data ->> 'last_vizit_id')::bigint = EvnVizitDispOrp.evn_id
             
             left join lateral (
                select 
                    case when PD.persondisp_begdate < rd.evn_setdate then 1 else 2 end as pr_d_n 	
                from v_PersonDisp PD 
                 join Diag pd_diag on PD.diag_id = rd.diag_id
                where 
                    PD.PErson_id = rd.Person_id and left(Diag.diag_code,3) = left(pd_diag.diag_code,3)
                    and PD.persondisp_begdate <= rd.evn_disdate 
                order by PersonDisp_begDate desc
                limit 1
             ) PersonDisp on true

             
        where 
            rd.registry_id = any(_registry_id_arr)
            and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end 
            and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
       
	);
    
	END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_sl(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_usl(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_usl(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(evn_id bigint, "IDSERV" text, "LPU_USL" text, "LPU_1_USL" text, "PODR_USL" text, "PROFIL_USL" text, "DET_USL" integer, "DATE_IN" text, "DATE_OUT" text, "DS" text, "P_OTK_USL" integer, "CODE_USL" text, "KOL_USL" integer, "TARIF_USL" numeric, "SUMV_USL" numeric, "PRVS_USL" integer, "CODE_MD" text, "COMENTU" text)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
        _lpu_code 			text; 
        _disp_code_arr 		text[];
	BEGIN
    
if p_disp_code is not null then 
	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
end if;

_lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);      
    
return query (
	
	select 
        ru.evn_id,
        ru.evnusluga_id::text as IDSERV,
        _lpu_code as LPU_USL,
        coalesce(nullif(rd.lpusection_code,''),nullif(LpuBuilding.lpubuilding_code,''),_lpu_code) as LPU_1_USL,
        uc_podr.uslugacomplex_code::text as PODR_USL,
        lsp.lpusectionprofile_code::text as PROFIL_USL,
        case when lsp.lpusectionprofile_code in ('17','18','19','20','21','55','68','83','86') 
          or (rd.region_data -> 'person' ->> 'age')::integer < 18 then 1 else 0 end as DET_USL,
        to_char(ru.registryusluga_setdate,'YYYY-MM-DD') as DATE_IN,
        to_char(ru.registryusluga_setdate,'YYYY-MM-DD') as DATE_OUT,
        Diag.diag_code::text as DS,
        case when ru.region_data ->> 'disp_service_os_sluch' = 'OS-0' then 1 else 0 end as P_OTK_USL,        
        ru.registryusluga_codeusl::text as CODE_USL,
        1 as KOL_USL,
        coalesce(rd.registrydata_tariff,0)::numeric(15,2) as TARIF_USL,
        case 
            when 
            	ru.region_data ->> 'disp_service_os_sluch' is null 
                and rd.region_data ->> 'disp' in ('ДВ2','ДВ4','ОПВ')	--тариф по услугам выводим только для взрослых
            then coalesce(ru.registryusluga_sum,0)
            else 0
        end::numeric(15,2) as SUMV_USL,
        ms.medspecclass_code::integer as PRVS_USL,           
        MedPersonal.person_fio as CODE_MD,
        null as COMENTU
    from r477.registrydata rd 
     join r477.registryusluga ru on rd.registry_id = ru.registry_id and rd.evn_id = ru.evn_id
     join v_Evn evn on rd.evn_id = Evn.evn_id
     left join LpuSection on LpuSection.lpusection_id = rd.lpusection_id
     left join LpuUnit on LpuSection.lpuunit_id = LpuUnit.lpuunit_id
     left join LpuBuilding on LpuUnit.lpubuilding_id = LpuBuilding.lpubuilding_id
     left join Diag on Diag.diag_id = coalesce(ru.diag_id,rd.diag_id)
     left join v_MedStaffFact msf on msf.MedStaffFact_id = ru.medstafffact_id
     left join v_MedPersonal MedPersonal on MedPersonal.MedPersonal_id = case when rd.Evn_id=ru.evnusluga_id then rd.medpersonal_id else  msf.MedPersonal_id end and MedPersonal.lpu_id = evn.lpu_id
     left join MedSpecOms on MedSpecOms.MedSpecOms_id = msf.MedSpecOms_id 
     left join fed.MedSpecClass mcs on MedSpecOms.MedSpecClass_id = mcs.MedSpecClass_id
     left join fed.MedSpecClass ms on rd.medspec_id = ms.medspecclass_id
     left join LpuSectionProfile on LpuSection.lpusectionprofile_id = LpuSectionProfile.lpusectionprofile_id
     left join fed.LpuSectionProfile lsp on lsp.lpusectionprofile_id = LpuSectionProfile.LpuSectionProfile_fedid
     left join v_uslugacomplex uc_podr on (rd.region_data ->> 'podr_id')::bigint = uc_podr.uslugacomplex_id

    where 
        rd.registry_id = any(_registry_id_arr)
        and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
    
);
	END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_usl(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_z_sl(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_z_sl(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(evn_id bigint, maxevn_id bigint, person_id bigint, "N_ZAP" integer, "PR_NOV" integer, "VPOLIS" integer, "SPOLIS" text, "NPOLIS" text, "ST_OKATO" text, "SMO" text, "SMO_OGRN" text, "SMO_OK" text, "SMO_NAM" text, "NOVOR" text, "VNOV_D" integer, "VNOV_M" integer, "IDCASE" bigint, "USL_OK" integer, "VIDPOM" integer, "FOR_POM" integer, "LPU" text, "VBR" integer, "DATE_Z_1" text, "DATE_Z_2" text, "P_OTK" integer, "RSLT_D" integer, "ISHOD" integer, "IDSP" integer, "SUMV" numeric, "OPLATA" integer, "SUMP" numeric, "SANK_IT" numeric)
    LANGUAGE plpgsql
    AS $_$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
        _lpu_code 			text; 
        _disp_code_arr 		text[];        
	BEGIN
    
	if p_disp_code is not null then 
    	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
    end if;
    
    _lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);      
    
    return query (
	
		select 
          rd.evn_id,
          rd.evn_id as maxevn_id,
          rd.person_id,
          --rd.registrydata_rownum::integer as N_ZAP,
          (row_number() over(order by rd.evn_id))::integer as N_ZAP,
          case when r.registry_isrepeated = 2 then 1 else 0 end as PR_NOV,
          --rd.person_id::text as ID_PAC,
          (rd.region_data -> 'polis' ->> 'vpolis')::integer as VPOLIS,
          nullif(rd.region_data -> 'polis' ->> 'spolis','') as SPOLIS,
          nullif(rd.region_data -> 'polis' ->> 'npolis','') as NPOLIS,
          case when rd.region_data -> 'polis' ->> 'vpolis' = '1' then nullif(OmsSprTerr.omssprterr_okato,'') else null end as ST_OKATO,
          nullif(OrgSmo.orgsmo_f002smocod,'') AS SMO,
          nullif(Org.org_ogrn,'') AS SMO_OGRN,
          left(coalesce(nullif(Org.org_okato,''),nullif(KLArea.kladr_ocatd,'')),5) as SMO_OK, 
          nullif(Org.org_nick,'') as SMO_NAM,
          case 
              when rd.region_data -> 'deputy' is null then '0' 
              else concat(
                  rd.region_data -> 'person' ->> 'sex_id',
                  to_char((rd.region_data -> 'person' ->> 'birthday')::date,'DD'),
                  to_char((rd.region_data -> 'person' ->> 'birthday')::date,'MM'),
                  to_char((rd.region_data -> 'person' ->> 'birthday')::date,'YY'),'1'
                  )
          end::text as NOVOR,
          case when rd.region_data -> 'deputy' is null then pcw.PersonWeight_Weight::integer else null::integer end as VNOV_D,
          case when rd.region_data -> 'deputy' is not null then pcw.PersonWeight_Weight::integer else null::integer end as VNOV_M,
          --rd.evn_id as IDCASE,
          --rd.registrydata_rownum::bigint as IDCASE,
          (row_number() over(order by rd.evn_id))::bigint as IDCASE,
          3 as USL_OK, 
          (rd.region_data ->> 'vidpom')::integer as VIDPOM,
          3 as FOR_POM,
          _lpu_code as LPU,
          case 
              --when exists (select 1 from r477.registryusluga ru where ru.registry_id = rd.registry_id and ru.evn_id = rd.evn_id and ru.registryusluga_codeusl ~ '^[AB]\d+\.\d+\.\d+\.008$') then 1
              when rd.region_data ->> 'ismobile' = '2' then 1
              else 0 
          end as VBR,
          to_char(rd.evn_setdate::date,'YYYY-MM-DD') as DATE_Z_1,
          to_char(rd.evn_disdate::date,'YYYY-MM-DD') as DATE_Z_2,   
          0 as P_OTK,
          (rd.region_data ->> 'rslt_d')::integer as RSLT_D,   

          306 as ISHOD,
          29 as IDSP,  
          coalesce(rd.registrydata_itogsum,0)::numeric as SUMV,
          null::integer as OPLATA,
          null::numeric as SUMP,
          null::numeric as SANK_IT          
      from 
          r477.registrydata rd 
           join r477.registry r on rd.registry_id = r.registry_id
           left join OmsSprTerr on rd.omssprterr_id = OmsSprTerr.omssprterr_id
           left join OrgSmo on rd.orgsmo_id = OrgSmo.orgsmo_id 
           left join Org on Org.org_id = OrgSmo.org_id
           left join lateral (select ost.klrgn_id from v_OrgServiceTerr ost where ost.org_id = OrgSmo.org_id order by ost.orgserviceterr_id limit 1) as ost on true --окато по территории обслуживания
           left join KLArea on KLArea.klarea_id = coalesce(OrgSmo.klrgn_id,ost.klrgn_id) 
             
           left join lateral (
              select 
                  case when PersonWeight.Okei_id = 37 then PersonWeight_Weight * 1000 else PersonWeight_Weight end as PersonWeight_Weight
              from v_PersonNewborn PChild 
               join PersonWeight on PersonWeight.Person_id = PChild.person_id and PersonWeight.WeightMeasureType_id = 1  --select*From WeightMeasureType
              where 
                  PChild.Person_id = rd.person_id
                  and (
                      (
                          datediff('day',(rd.region_data -> 'person' ->> 'birthday')::date,rd.Evn_setDate) <= 28 
                          and case when PersonWeight.Okei_id = 37 then PersonWeight_Weight * 1000 else PersonWeight_Weight end < 3000
                      ) 
                      or ChildTermType_id=2
                  )
              order by WeightMeasureType_id,PersonWeight_setDT
              limit 1
           ) pcw on true     
           
      where 
          rd.registry_id = any(_registry_id_arr)
          and case when p_disp_code is not null then rd.region_data ->> 'disp' = any(_disp_code_arr) else true end 
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
      order by rd.evn_id
      
	);

END;
$_$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_z_sl(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_exp_zglv(bigint, text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_exp_zglv(p_registry_id bigint, p_disp_code text DEFAULT NULL::text) RETURNS TABLE(registry_id bigint, "VERSION" text, "DATA" text, "FILENAME" text, "SD_Z" bigint, "CODE" bigint, "CODE_MO" text, "YEAR" integer, "MONTH" integer, "NSCHET" character varying, "DSCHET" text, "PLAT" text, "SUMMAV" text, "COMENTS" text, "SUMMAP" text, "SUMMAP_R" text, "SUMMAP_F" text, "SANK_MEK" text, "SANK_MEE" text, "SANK_EKMP" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _disp_code_arr 		text[];
    _reg_prfx 			text 	 = concat(getregion(),'0101');  
BEGIN

	if p_disp_code is not null then 
    	_disp_code_arr = r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code);	
    end if;

return query (
 select
    p_registry_id as registry_id,
    '3.1'::text as VERSION,
    to_char(current_date,'YYYY-MM-DD') as DATA,
    concat(
    	'D','M',Lpu.lpu_f003mcod,
        case when KatNasel.katnasel_sysnick = 'oblast' then 'S' else 'T' end,
        case when KatNasel.katnasel_sysnick = 'oblast' then OrgSMO.orgsmo_f002smocod else '68000' end,
        '_',to_char(r.registry_enddate,'YY'),to_char(r.registry_enddate,'MM')
    ) as FILENAME,
    coalesce(rd.sd_z,0) as SD_Z,
    r.Registry_id as CODE,
    --regexp_replace(regexp_replace(r.registry_id::text,'^\d{1,2}0101',''),'^0+','')::bigint as CODE,
    Lpu.Lpu_f003mcod::text as CODE_MO,
    date_part('YEAR', r.Registry_endDate)::integer as YEAR,
    date_part('MONTH', r.Registry_endDate)::integer as MONTH,
    r.Registry_Num as NSCHET,
    to_char(r.Registry_accDate::date,'YYYY-MM-DD') as DSCHET,
    case when KatNasel.katnasel_sysnick = 'oblast' then orgSMO.orgsmo_f002smocod else '68000' end::text as PLAT,
    coalesce(rd.summav,0)::numeric(15,2)::text as SUMMAV,
    '6' as COMENTS,
    null as SUMMAP,
    null as SUMMAP_R,
    null as SUMMAP_F,
    null as SANK_MEK,
    null as SANK_MEE,
    null as SANK_EKMP
from r477.Registry r  
 join Lpu on Lpu.Lpu_id = r.Lpu_id
 left join OrgSMO on OrgSMO.OrgSMO_id = r.OrgSmo_id
 left join KatNasel on r.katnasel_id = KatNasel.katnasel_id 
 left join lateral (
 	select sum(d.registrydata_itogsum) as summav,count(*) as sd_z from r477.registrydata d 
    where 
    	d.registry_id = any(_registry_id_arr) 
        --and case when p_disp_code is not null then d.region_data ->> 'disp' = any(_disp_code_arr) else true end  
        and d.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
 ) rd on true 
 where 
	r.Registry_id = p_Registry_id
);
END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_exp_zglv(p_registry_id bigint, p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnpldisp_get_dispcode_arr(text); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code text) RETURNS text[]
    LANGUAGE plpgsql
    AS $$
DECLARE
  
BEGIN
  
	p_disp_code = upper(p_disp_code);
    if not coalesce(p_disp_code,'DP') in ('DP','DV','DO','DS','DU','DF') then 
        raise exception 'r477.p_registry_evnpldisp_get_dispcode_arr(text) invalid parameter value!';
    end if;

    return 
        case p_disp_code
            when 'DP' then '{ДВ4}'
            when 'DV' then '{ДВ2}'
            when 'DO' then '{ОПВ}'
            when 'DS' then '{ДС1,ДС3}'
            when 'DU' then '{ДС2,ДС4}'
            when 'DF' then '{ПН1,ПН2}'
        end::text[]
    ; 

END;
$$;


ALTER FUNCTION r477.p_registry_evnpldisp_get_dispcode_arr(p_disp_code text) OWNER TO developer_rep;

--
-- Name: p_registry_evnps_get_tariff(text, bigint, bigint, text, bigint, bigint, bigint, numeric, date, jsonb); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnps_get_tariff(p_vidpom text, p_lpuunittype_id bigint, p_lpusection_id bigint, p_lpusectionprofile_code text, p_leavetype_id bigint, p_kd_pay bigint, p_mes_id bigint, p_coeffctp numeric, p_ondate date, p_param jsonb, OUT tariff numeric, OUT tariff_code text, OUT price numeric, OUT podr text, OUT lvl text, OUT is_interrupt boolean) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE
	_lpu_code_oms	text 	= p_param ->> 'lpu_code_oms';
    _trf_gr 		integer	= (p_param ->> 'trf_gr')::integer; 
    _metod_hmp		text 	= p_param ->> 'metod_hmp';   
    
    _csg_code 		text;
    _csg_tariff 	record;
    _tariff_code 	text;
    _podr 			text;
    _lvl			text;
    _is_interrupt 	boolean = false;
    _rslt_code 		text;
    _int_coeff		numeric = 1.0;
    _tariff			numeric;
    _price			numeric;
BEGIN
 
IF p_vidpom in ('31','12','13') THEN --специализированная помощь + ДС, расчет тарифа по КСГ  

	_csg_code  = (select mesold_num from mesold where mes_id = p_mes_id);
    _rslt_code = (select flt.leavetype_code from dbo.LeaveType lt 
                   join fed.LeaveType flt on lt.leavetype_fedid = flt.leavetype_id
                  where lt.leavetype_id = p_leavetype_id
    			 )
    ;   
    

    
    
    IF p_lpuunittype_id = 1 THEN 	
    	
    	--------------------РАСЧЕТ КРУГЛОСУТОЧНОГО СТАЦИОНАРА-----------------
    	
    	--podr и lvl 
        select 
            av1.attributevalue_valuestring as podr,av2.attributevalue_valuestring as lvl 
        into _podr, _lvl
        from AttributeSignValue asv 
         join v_AttributeSign ats on asv.attributesign_id = ats.attributesign_id
         join dbo.AttributeValue av1 on asv.attributesignvalue_id = av1.attributesignvalue_id 
         join dbo.Attribute at1 on av1.attribute_id = at1.attribute_id and at1.attribute_sysnick = 'StacCode' 
         join dbo.AttributeValue av2 on asv.attributesignvalue_id = av2.attributesignvalue_id 
         join dbo.Attribute at2 on av2.attribute_id = at2.attribute_id and at2.attribute_sysnick = 'StacLevel'
        where 
            ats.attributesign_code = 21 
            and asv.attributesignvalue_tablepkey = p_lpusection_id
            and p_ondate <@ daterange(asv.attributesignvalue_begdate::date,asv.attributesignvalue_enddate::date,'[]')

        order by 
            av2.attributevalue_valuestring desc, asv.attributesignvalue_id
        limit 1
        ; 
        
        --определяем прерванный случай
        if 
        	p_kd_pay <= 3 
            and not exists (select 1 from r477.adyg_csg_ex ex where ex.csg_code1 = _csg_code and ex_code = 'full_payment' and p_ondate <@ daterange(from_dt,to_dt,'[]'))
            or _rslt_code in ('102', '105', '106', '107', '108', '110') 
        then 
        	_is_interrupt = true;
        end if;
        
        
        if _is_interrupt then 
        
        	--для прерванных случаев определяем значение понижающего коэффициента            
            if exists (select 1 from r477.adyg_csg_ex
                       where ex_code = 'surgery' and csg_code1 = _csg_code and p_ondate <@ daterange(from_dt,to_dt,'[]')
                       )
            then 
            	--если КСГ среди хирургических      
                _int_coeff = case when p_kd_pay <= 3 then 0.8 else 0.9 end;                         
            else                        
                _int_coeff = case when p_kd_pay <= 3 then 0.3 else 0.5 end;                          
            end if;
        
        end if;
        
        --получаем тариф 
        --для третьего уровня пытаемся взять из поля dsi (если там не ноль)
        _tariff = 0 --case when left(coalesce(_lvl,''),1) = '3' then coalesce(nullif(_csg_tariff.dsi,0),_csg_tariff.s) ELSE _csg_tariff.s END
        ;
        
        --получаем стоимость 
        _price = round(_tariff * _int_coeff * coalesce(nullif(p_coeffctp,0),1), 2);
    
    ELSE 
    
    	--------------------РАСЧЕТ ДНЕВНОГО СТАЦИОНАРА-----------------
    
    	--podr и lvl 
        select 
            t002.otd_kod, t002.lvl
        into _podr, _lvl
        from r477.adyg_t002 t002 
        where 
            t002.f_mcod = _lpu_code_oms
            and t002.prof = p_lpusectionprofile_code	--уровень определяем по профилю 
            and p_ondate <@ daterange(t002.datebeg,t002.dateend,'[]')
            and t002.usl_ok = 2 
        order by t002.otd_kod
        limit 1
        ;
        
        --определяем прерванный случай 
        if _rslt_code in ('202', '203', '204', '205', '206', '207', '208') then 
        	_is_interrupt = true;
        end if;        
        
        if _is_interrupt then 
        
        	--для прерванных случаев определяем значение понижающего коэффициента            
            if exists (select 1 from r477.adyg_csg_ex
                       where ex_code = 'surgery' and csg_code1 = _csg_code and p_ondate <@ daterange(from_dt,to_dt,'[]')
                       )
            then 
            	--если КСГ среди хирургических      
                _int_coeff = case when p_kd_pay <= 3 then 0.8 else 0.9 end;                         
            else                        
                _int_coeff = case when p_kd_pay <= 3 then 0.3 else 0.5 end;                          
            end if;
        
        end if;
        
        --получаем тариф 
        _tariff = _csg_tariff.s;
        
        --получаем стоимость 
        _price = round(_tariff * _int_coeff * coalesce(nullif(p_coeffctp,0),1), 2);        
    
    END IF;
    
    _tariff_code = _csg_tariff.tariff_code;

ELSIF p_vidpom = '32' THEN --ВМП 

	--podr и lvl 
    select 
        av1.attributevalue_valuestring as podr,av2.attributevalue_valuestring as lvl 
    into _podr, _lvl
    from AttributeSignValue asv 
     join v_AttributeSign ats on asv.attributesign_id = ats.attributesign_id
     join dbo.AttributeValue av1 on asv.attributesignvalue_id = av1.attributesignvalue_id 
     join dbo.Attribute at1 on av1.attribute_id = at1.attribute_id and at1.attribute_sysnick = 'StacCode' 
     join dbo.AttributeValue av2 on asv.attributesignvalue_id = av2.attributesignvalue_id 
     join dbo.Attribute at2 on av2.attribute_id = at2.attribute_id and at2.attribute_sysnick = 'StacLevel'
    where 
        ats.attributesign_code = 21 
        and asv.attributesignvalue_tablepkey = p_lpusection_id
        and p_ondate <@ daterange(asv.attributesignvalue_begdate::date,asv.attributesignvalue_enddate::date,'[]')        
    order by 
        av2.attributevalue_valuestring desc, asv.attributesignvalue_id
    limit 1
    ; 
    
    --находим код тарифа, соответствующий методу вмп 
    _tariff_code = (select avt.tarif_code from r477.adyg_vmp_method_price_type avt 
                    where 
                   	 avt.vmp_method_code = _metod_hmp 	
                     and p_ondate <@ daterange(avt.from_dt,avt.to_dt,'[]')
                    order by avt.id desc 
                    limit 1
                    )
    ;
    
    --находим тариф 
    _tariff = (select t.s from r477.adyg_tariflpu t 
               where 
              	t.kmu = _tariff_code 
                and p_ondate <@ daterange(t.datebeg,t.dateend,'[]')
               limit 1       
    		  )
    ;
    
    _price = _tariff;

END IF;	


tariff_code  = _tariff_code;
podr		 = _podr;
lvl			 = _lvl; 	
tariff		 = _tariff;
price 		 = _price;
is_interrupt = _is_interrupt;  

END;
$$;


ALTER FUNCTION r477.p_registry_evnps_get_tariff(p_vidpom text, p_lpuunittype_id bigint, p_lpusection_id bigint, p_lpusectionprofile_code text, p_leavetype_id bigint, p_kd_pay bigint, p_mes_id bigint, p_coeffctp numeric, p_ondate date, p_param jsonb, OUT tariff numeric, OUT tariff_code text, OUT price numeric, OUT podr text, OUT lvl text, OUT is_interrupt boolean) OWNER TO developer_rep;

--
-- Name: p_registry_evnps_get_tariff_dev(jsonb); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_evnps_get_tariff_dev(p_params jsonb) RETURNS jsonb
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id BIGINT := (p_params ->> 'registry_id')::BIGINT;
	_item_type TEXT := p_params ->> 'item_type';
	_group_hmp TEXT := p_params ->> 'group_hmp'; 
	_org_id TEXT := TRIM(COALESCE(p_params ->> 'org_id', ''));
	_idsp INTEGER := (p_params ->> 'idsp')::INTEGER;
	_lpuunittype_id BIGINT := (p_params ->> 'lpuunittype_id')::BIGINT;
	_unit_type TEXT := (SELECT lpuunittype_sysnick FROM dbo.v_lpuunittype WHERE lpuunittype_id = _lpuunittype_id);
	_stac_type TEXT := (SELECT CASE WHEN _unit_type = 'stac' THEN 'ks' ELSE 'ds' END);
	_regimen_type TEXT;
	_on_date DATE := COALESCE((p_params ->> 'evn_disdate')::DATE, CURRENT_DATE);
	_ver_ksg TEXT := DATE_PART('year', _on_date);
	_mesold_code TEXT := p_params ->> 'n_ksg';
	_mesold_id BIGINT := (p_params ->> 'mesitog_id')::BIGINT;
	_leavetype_id BIGINT := (p_params ->> 'leavetype_id')::BIGINT;
	_kd_pay BIGINT := (p_params ->> 'registrydata_kdpay')::BIGINT;
	_coeffctp NUMERIC := (p_params ->> 'registrydata_coeffctp')::NUMERIC;
	_mesolduslugacomplex_id BIGINT := (p_params ->> 'mesolduslugacomplex_id')::BIGINT;
	_lpusectionbedprofilelink_id BIGINT := (p_params ->> 'lpusectionbedprofilelink_id')::BIGINT;
	_lpusectionprofile_id BIGINT := (p_params ->> 'lpusectionprofile_id')::BIGINT;
	_lpusectionprofile_code TEXT;
	_lpusectionbedprofile_code TEXT;
	_person_age INTEGER := (p_params ->> 'person_age')::INTEGER;
	_evn_id BIGINT := (p_params ->> 'evn_id')::BIGINT;
	_drugtherapyscheme_id BIGINT;
	_days_in_tarif INTEGER;
	_fd_inj INTEGER;
	_lpu_id TEXT := p_params ->> 'lpu_id';
	_bztsz_code TEXT := (SELECT CASE WHEN _stac_type = 'ks' THEN 'БСКС' ELSE 'БСДС' END);
	_koef_u_code TEXT := (SELECT CASE WHEN _stac_type = 'ks' THEN 'КУСКС' ELSE 'КУСДС' END);
	--Если в КВС по типу стационара, коду профиля койки и коду организации по ОМС подбирается один из следующих PODR_ID по справочнику TERR011:
	_podr_for_kuscaop TEXT[] := ARRAY['02054201','06754201','07554601','08154201','08454601','08754601']::TEXT; 
	_koef_caop_code TEXT := 'КУСЦАОП';
	_rslt_code TEXT;
	_podr TEXT;
	_lpu_1 TEXT;
	_podr_code TEXT;
	_podr_code_id_arr INTEGER[];
	_tariff_code TEXT;
	_tariff_name TEXT;
	_tariff NUMERIC;
	_price NUMERIC;
	_koef_u NUMERIC(5,2);
	_koef_up NUMERIC(5,2);
	_koef_z NUMERIC(5,2) := (p_params ->> 'mestariff_value')::NUMERIC(5,2);
	_koef_d NUMERIC = 1;
	_bztsz NUMERIC(8,2);
	_short_koef NUMERIC(5,2) = 1;
	_koef_proc_pay NUMERIC(5,2) = 1;
	_kslp_code_arr TEXT;
	_sl_k INTEGER;
	_it_sl NUMERIC;
	_is_interrupt BOOLEAN := FALSE;
	_is_short_by_lek_tr BOOLEAN := FALSE;
	_is_without_koef_u BOOLEAN;
	_is_full_payment BOOLEAN;
	_is_surgery BOOLEAN;
	_is_csg_lek_tr NUMERIC(5,4);
	_csg_ex_flag BOOLEAN := FALSE; -- Переключить с внутренней таблицы (r477.csg_ex) на Тарифы/Объемы
	_csg_ex_arr TEXT[] := ARRAY['']::TEXT[]; -- признаки по КСГ (r477.csg_ex)
	_without_koef_u_code TEXT:= CASE WHEN _csg_ex_flag THEN 'no_cus_koef' ELSE 'КСГбезКУС' END;
	_full_payment_code TEXT := CASE WHEN _csg_ex_flag THEN 'full_payment' ELSE 'КСГ_100' END;
	_surgery_code TEXT := CASE WHEN _csg_ex_flag THEN 'surgery' ELSE 'КСГ_Хир' END;
--	_csg_lek_tr_code TEXT := CASE WHEN _csg_ex_flag THEN 'csg_lek_tr' ELSE 'КСГ_ЛекТер' END;
	_csg_lek_tr_code TEXT := 'ДЗП';
	_kslp_tarif_code TEXT := '780';
	_kslp_short_code_fed TEXT := '2';
	_kslp_short_code_fed_type TEXT := 'KSLP_CODE';
	_kslp_short_code_reg TEXT;
	_kslp_short_code_reg_type TEXT := 'KSLP_CODE_REG';
	_kslp_short_csg_code TEXT := 'st12.013.2';
	_ttc TEXT := 'dbo.TariffClass';
	_tvt TEXT := 'dbo.VolumeType';
	_csg_i jsonb;
BEGIN
 
	SELECT COALESCE(flsp.lpusectionprofile_code, lsp.lpusectionprofile_code::INTEGER) INTO _lpusectionprofile_code
	FROM dbo.lpusectionprofile AS lsp 
	LEFT JOIN fed.lpusectionprofile AS flsp ON lsp.lpusectionprofile_fedid = flsp.lpusectionprofile_id
	WHERE lsp.lpusectionprofile_id = _lpusectionprofile_id;

	SELECT lsbp.lpusectionbedprofile_code INTO _lpusectionbedprofile_code
	FROM fed.lpusectionbedprofilelink AS lsbpl
	LEFT JOIN fed.LpuSectionBedProfile AS lsbp on lsbp.LpuSectionBedProfile_id = lsbpl.lpusectionbedprofile_fedid
	WHERE lsbpl.lpusectionbedprofilelink_id = _lpusectionbedprofilelink_id;

	_regimen_type = 
		CASE
			WHEN _item_type = 'htm' THEN '1'
			WHEN _unit_type = 'stac' THEN '1'
			WHEN _unit_type = 'dstac' THEN '3'
			WHEN _unit_type = 'pstac' THEN '5'
			WHEN _unit_type = 'hstac' THEN '6'
		END;
---- поиск _podr_code = PODR_ID по справочнику TERR011
	SELECT ARRAY_AGG(DISTINCT t.id) INTO _podr_code_id_arr
	FROM r477.terr011 AS t 
	WHERE t.regimen_type = _regimen_type
	AND t.org_code = '680' || _org_id
	AND t.bed_profile_code = _lpusectionbedprofile_code
	AND _on_date BETWEEN COALESCE(t.from_dt, '-INFINITY') AND COALESCE( t.to_dt, 'INFINITY');

	IF array_length(_podr_code_id_arr, 1) > 1 THEN 
		--п.5
		IF '680094' = '680' || _org_id THEN 
			IF _lpusectionbedprofile_code = '41' AND EXISTS (
				SELECT 1
				FROM r477.registryusluga AS u  
				WHERE u.registry_id = _registry_id AND u.evn_id = _evn_id AND (u.region_data ->> 'is_dializ')::BOOLEAN
				) 
			THEN 
				SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
				FROM r477.terr011 
				WHERE id = ANY(_podr_code_id_arr) AND dializ;
			ELSEIF _lpusectionbedprofile_code = '41' AND NOT EXISTS (
				SELECT 1
				FROM r477.registryusluga AS u  
				WHERE u.registry_id = _registry_id AND u.evn_id = _evn_id AND (u.region_data ->> 'is_dializ')::BOOLEAN
				) 
			THEN 
				SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
				FROM r477.terr011 
				WHERE id = ANY(_podr_code_id_arr) AND NOT dializ;
			END IF;
		END IF;
	
		IF _item_type = 'htm' OR _stac_type = 'ks' THEN 
			--п.7
			IF '680081' = '680' || _org_id THEN 
				IF _lpusectionbedprofile_code IN ('6', '34', '80') AND FALSE THEN -- реанимация
					SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
					FROM r477.terr011 
					WHERE id = ANY(_podr_code_id_arr) AND reanim;
				ELSEIF _lpusectionbedprofile_code IN ('6', '34', '80') AND FALSE THEN -- реанимация  
					SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
					FROM r477.terr011 
					WHERE id = ANY(_podr_code_id_arr) AND NOT reanim;
				END IF;
			END IF;
			--п.4
			IF array_length(_podr_code_id_arr, 1) > 1 THEN
				IF _person_age < 18 THEN 
					SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
					FROM r477.terr011 
					WHERE id = ANY(_podr_code_id_arr) AND det;
				ELSE
					SELECT ARRAY_AGG(id) INTO _podr_code_id_arr
					FROM r477.terr011 
					WHERE id = ANY(_podr_code_id_arr) AND NOT det;
				END IF;
			END IF;
			--п.8
			IF '680083' = '680' || _org_id THEN
				IF _lpusectionbedprofile_code = '71' AND FALSE THEN _podr_code := '08317101'; END IF; -- dep_id = 382
				IF _lpusectionbedprofile_code = '71' AND FALSE THEN _podr_code := '08317102'; END IF; -- dep_id = 383
			END IF;
			--п.9
			IF '680097' = '680' || _org_id THEN
				IF _lpusectionbedprofile_code = '42' AND FALSE THEN _podr_code := '09714202'; END IF; -- dep_id = 13831
				IF _lpusectionbedprofile_code = '42' AND FALSE THEN _podr_code := '09714201'; END IF; -- dep_id <> 13831
			END IF;
		END IF;	
	
		--п.9	
		IF _stac_type = 'ds' THEN 
			IF '680097' = '680' || _org_id THEN
				IF _lpusectionbedprofile_code = '42' AND _kd_pay = 1 THEN _podr_code = '09734202'; END IF;
				IF _lpusectionbedprofile_code = '42' AND _kd_pay > 1 THEN _podr_code = '09734201'; END IF;
			END IF;
		END IF;

		--п.9
		IF '680095' = '680' || _org_id THEN
			IF FALSE THEN _podr_code = '09513902'; END IF; -- dep_id = 15871
		END IF;
	ELSE 
		_podr_code := (SELECT podr_code FROM r477.terr011 WHERE id = _podr_code_id_arr[1]);
	END IF;

	IF _podr_code IS NULL THEN
		_podr_code := (SELECT podr_code FROM r477.terr011 WHERE id = _podr_code_id_arr[1]);
	END IF;
---- конец поиска _podr_code = PODR_ID по справочнику TERR011
	_lpu_1 = _podr_code;	
		
	IF _item_type = 'stac' THEN  

		SELECT flt.leavetype_code INTO _rslt_code
		FROM dbo.leavetype AS lt 
		JOIN fed.leavetype AS flt ON lt.leavetype_fedid = flt.leavetype_id
		WHERE lt.leavetype_id = _leavetype_id;

		SELECT r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', _bztsz_code, 'object_type', _ttc, 'p_date', _on_date))::NUMERIC INTO _bztsz;
		
		IF _csg_ex_flag THEN 

			-- Собираем все признаки КСГ
			_csg_ex_arr = COALESCE
				(
					(
						SELECT ARRAY_AGG(ex_code)::TEXT[] 
						FROM r477.csg_ex 
						WHERE csg_code1 = _mesold_code AND care_regimen_code = CASE WHEN _stac_type = 'ks' THEN 'KS_CSG' ELSE 'DS_CSG' END AND _on_date <@ daterange(from_dt, to_dt, '[]') 
					), 
					_csg_ex_arr
				);

			_is_without_koef_u = (_without_koef_u_code = ANY(_csg_ex_arr));
			_is_full_payment = (_full_payment_code = ANY(_csg_ex_arr));
			_is_surgery = (_surgery_code = ANY(_csg_ex_arr));
			--_is_csg_lek_tr = (_csg_lek_tr_code = ANY(_csg_ex_arr));

		ELSE 
			SELECT r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', _without_koef_u_code, 'object_type', _tvt, 'p_date', _on_date, 'mesold_id', _mesold_id))::BOOLEAN INTO _is_without_koef_u;
			SELECT r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', _full_payment_code, 'object_type', _tvt, 'p_date', _on_date, 'mesold_id', _mesold_id))::BOOLEAN INTO _is_full_payment;
			SELECT r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', _surgery_code, 'object_type', _tvt, 'p_date', _on_date, 'mesold_id', _mesold_id))::BOOLEAN INTO _is_surgery;
			SELECT r477.tambov_fin_get_value_dev(jsonb_build_object('object_code', _csg_lek_tr_code, 'object_type', _tvt, 'p_date', _on_date, 'mesold_id', _mesold_id))::NUMERIC(5,4)  INTO _is_csg_lek_tr;
		END IF;

		_is_without_koef_u = COALESCE(_is_without_koef_u, FALSE);
		_is_full_payment = COALESCE(_is_full_payment, FALSE);
		_is_surgery = COALESCE(_is_surgery, FALSE);
		--_is_csg_lek_tr = COALESCE(_is_csg_lek_tr, FALSE);

		SELECT r477.tambov_fin_get_value_dev(jsonb_build_object(
															'object_code', case when _podr_code=any(_podr_for_kuscaop) then _koef_caop_code else _koef_u_code end,
															'object_type', _ttc, 
															'p_date', _on_date, 
															'lpu_id', _lpu_id
															)
											)::NUMERIC INTO _koef_u;

		_koef_u = (SELECT CASE WHEN _is_without_koef_u or (_koef_u<1 and _mesold_code ~ '^(st19|ds19)') THEN 1 ELSE _koef_u END);

		

		IF (_rslt_code IN ('102', '105', '107', '108', '110', '202', '205', '206', '207', '208') AND NOT _is_full_payment) OR (NOT _is_full_payment AND _kd_pay <= 3)  THEN 
			_is_interrupt := TRUE;
		END IF;	

		IF _is_interrupt THEN	

			IF _mesold_code = _kslp_short_csg_code AND _kd_pay <= 10 THEN 
				_kslp_short_code_reg = 
					CASE 
						WHEN _kd_pay BETWEEN 0 AND 3 THEN 'kskp18'
						WHEN _kd_pay BETWEEN 4 AND 6 THEN 'kskp19'
						WHEN _kd_pay BETWEEN 7 AND 10 THEN 'kskp20'
					END;
			ELSIF _is_surgery THEN _kslp_short_code_reg = 'kskp6';
			ELSIF _kd_pay > 3 THEN _kslp_short_code_reg = 'kskp21';
			ELSE _kslp_short_code_reg = 'kskp7';
			END IF;

			SELECT r477.tambov_fin_get_value_dev(
				jsonb_build_object(
					'object_code', _kslp_tarif_code, 
					'object_type', _ttc, 
					'p_date', _on_date, 
					_kslp_short_code_fed_type, _kslp_short_code_fed, 
					_kslp_short_code_reg_type, _kslp_short_code_reg
					)
				)::NUMERIC INTO _short_koef;

		END IF;

		SELECT mesoldcoeff_coeff INTO _koef_up
		FROM v_mesoldcoeff 
		WHERE mes_id = _mesold_id 
		AND _on_date BETWEEN COALESCE(mesoldcoeff_begdt::DATE, '-INFINITY') AND COALESCE(mesoldcoeff_enddt::DATE, 'INFINITY');

		_tariff = _bztsz;
	
		_tariff_code = 
			CASE
				WHEN _unit_type = 'stac' THEN '14'
				WHEN _unit_type = 'dstac' THEN '16'
				WHEN _unit_type = 'pstac' THEN '15'
				WHEN _unit_type = 'hstac' THEN '17'
			END;
		
		_podr = '0';
		
		--_coeffctp = COALESCE(NULLIF(_coeffctp, 0), 1) + _short_koef - 1;

		--IF _coeffctp > 1.8 THEN _coeffctp = 1.8; END IF;
		
		_coeffctp = round(COALESCE(NULLIF(_coeffctp, 0), 1) * _short_koef, 2);
	
		_sl_k = (_coeffctp <> 1)::INTEGER;
	
		_it_sl = COALESCE(NULLIF(_coeffctp, 1), 1);
		
		--_it_sl = _coeffctp;
		IF COALESCE(_is_csg_lek_tr, 0)=0 then _price = round(_tariff * _koef_z * _koef_up * _koef_u * _koef_d * _coeffctp, 2);
		else _price = round(_tariff * _koef_z *((1-_is_csg_lek_tr)+_is_csg_lek_tr * _koef_u * _koef_d * _coeffctp)*_koef_proc_pay, 2);
		END IF;
	
		SELECT string_agg(('K' || (l.evnsectionkslplink_code)::TEXT || ':' || (l.evnsectionkslplink_value)::TEXT), ',') INTO _kslp_code_arr
		FROM dbo.v_evnsectionkslplink AS l
		WHERE l.evnsection_id = _evn_id;

		_kslp_code_arr = CONCAT_WS(',', _kslp_code_arr, CASE WHEN _is_interrupt THEN 'K' || _kslp_short_code_fed || ':' || _short_koef ELSE NULL END);
		
		_csg_i = jsonb_build_object(
			'csg_info', jsonb_build_object(
				'n_ksg', _mesold_code,
				'ver_ksg', _ver_ksg,
				'ksg_pg', 0,
				'n_kpg', NULL,
				'bztsz', _bztsz, 
				'koef_z', _koef_z,
				'koef_up', _koef_up,
				'koef_u', _koef_u, 
				'koef_d', _koef_d, 
				'sl_k', _sl_k,
				'it_sl', _it_sl,
				'short_koef', _short_koef, 
				'kslp_code_arr', _kslp_code_arr,
				'is_interrupt', _is_interrupt,
				'is_short_by_lek_tr', _is_short_by_lek_tr,
				'is_without_koef_u', _is_without_koef_u,
				'is_full_payment', _is_full_payment,
				'is_surgery', _is_surgery,
				'is_csg_lek_tr', _is_csg_lek_tr,
				'bztsz_code', _bztsz_code,
				'koef_u_code', _koef_u_code,
				'rslt_code', _rslt_code,
				'kd_pay', _kd_pay
				)
			);

	ELSIF _item_type = 'htm' THEN 

		SELECT division, sl INTO _tariff_code, _tariff
		FROM r477.terr007 AS t
		WHERE UPPER(TRIM(t.division)) = '23' || lpad(_group_hmp, 2, '0')
		AND TRIM(t.org_id) = _org_id
		AND t.idsp = _idsp
		AND _on_date >= to_date(concat(t.year_per, t.month_per), 'YYYYMM')
		ORDER BY to_date(concat(t.year_per, t.month_per), 'YYYYMM') DESC 
		LIMIT 1;
	
		--RAISE NOTICE '_group_hmp %', lpad(_group_hmp, 2, '0');
		--RAISE NOTICE '_org_id %', _org_id;
		--RAISE NOTICE '_idsp %', _idsp;
		--RAISE NOTICE '_on_date %', _on_date;


		SELECT DISTINCT t.name INTO _tariff_name 
		FROM r477.terr001 AS t 
		WHERE t.cod = _tariff_code
		AND _on_date BETWEEN COALESCE(t.date_ins, '-INFINITY') AND COALESCE( t.date_del, 'INFINITY');

		_price = _tariff;
		_podr = _tariff_code;
	
	END IF;



	RETURN jsonb_build_object(
		'tariff_info', jsonb_build_object(
			'tariff_code', _tariff_code, 
			'tariff_name', _tariff_name, 
			'tariff', _tariff, 
			'price', _price,
			'podr', _podr,
			'lpu_1', _lpu_1
			)
		) || COALESCE(_csg_i, '{}');
 

END;
$$;


ALTER FUNCTION r477.p_registry_evnps_get_tariff_dev(p_params jsonb) OWNER TO developer_rep;

--
-- Name: p_registry_exp_bdiag(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_bdiag(p_registry_id bigint) RETURNS TABLE(evn_id bigint, "DIAG_DATE" text, "DIAG_TIP" integer, "DIAG_CODE" integer, "DIAG_RSLT" integer, "REC_RSLT" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN
    
  return query (
	
    select distinct 
        mov.evn_id,
        to_char(mov.MorbusOnkoLink_takeDT::date,'YYYY-MM-DD')::text as DIAG_DATE,
        DiagAttribType.DiagAttribType_Code::integer as DIAG_TIP,
        DiagAttribDict.DiagAttribDict_code::integer as DIAG_CODE,
        DiagResult.DiagResult_Code::integer as DIAG_RSLT,
        1::integer as REC_RSLT
    from (
        
    	--поликлиника ТАП
        select 
              rd.evn_id,MorbusOnkoLeave.diag_id,MorbusOnkoLink.diagresult_id,
              MorbusOnkoLink.DiagAttribType_id,MorbusOnkoLink.DiagAttribDict_id,
              MorbusOnkoLink.MorbusOnkoLink_takeDT 
        from r477.registrydata rd 
         join v_EvnVizitPL ev on ev.EvnVizitPL_pid = rd.evn_rid
         join v_MorbusOnkoVizitPLDop MorbusOnkoLeave on ev.EvnVizitPL_id = MorbusOnkoLeave.EvnVizit_id               
         join v_MorbusOnkoLink MorbusOnkoLink on MorbusOnkoLink.MorbusOnkoVizitPLDop_id=MorbusOnkoLeave.MorbusOnkoVizitPLDop_id
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
         rd.registry_id = any(_registry_id_arr) 
         and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
         and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPL'
         and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
         and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
             
        union all 

        --стоматология ТАП 
        select 
            rd.evn_id,MorbusOnkoLeave.diag_id,MorbusOnkoLink.diagresult_id,
            MorbusOnkoLink.DiagAttribType_id,MorbusOnkoLink.DiagAttribDict_id,
            MorbusOnkoLink.MorbusOnkoLink_takeDT
        from r477.registrydata rd 
         join v_EvnDiagPLStom EvnDiagPLStom on EvnDiagPLStom.EvnDiagPLStom_rid = rd.evn_rid
         join v_MorbusOnkoDiagPLStom MorbusOnkoLeave on EvnDiagPLStom.EvnDiagPLStom_id = MorbusOnkoLeave.EvnDiagPLStom_id
         join v_MorbusOnkoLink MorbusOnkoLink on MorbusOnkoLink.MorbusOnkoDiagPLStom_id = MorbusOnkoLeave.MorbusOnkoDiagPLStom_id
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
         rd.registry_id = any(_registry_id_arr) 
         and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
         and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPLStom'
         and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
         and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
         
         union all
         
         --стационары 
         select 
            rd.evn_id,MorbusOnkoLeave.diag_id,MorbusOnkoLink.diagresult_id,
            MorbusOnkoLink.DiagAttribType_id,MorbusOnkoLink.DiagAttribDict_id,
            MorbusOnkoLink.MorbusOnkoLink_takeDT
        from r477.registrydata rd 
         join v_EvnSection EvnSection on EvnSection.evnsection_id = rd.evn_id -- EvnSection.evnsection_rid = rd.evn_rid --#PROMEDWEB-21529 Исправил соединение
         join v_MorbusOnkoLeave MorbusOnkoLeave on EvnSection.evnsection_id = MorbusOnkoLeave.evnsection_id
         join v_MorbusOnkoLink MorbusOnkoLink on MorbusOnkoLink.morbusonkoleave_id = MorbusOnkoLeave.morbusonkoleave_id
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
         rd.registry_id = any(_registry_id_arr) 
         and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
         and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection'
         and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
         and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
         
    ) mov
     join lateral (
        select DR.DiagResult_Code from DiagResult DR
         join v_DiagnosisResultDiagLink DiagnosisResultDiagLink on DiagnosisResultDiagLink.DiagResult_id = DR.DiagResult_id     			
        where DR.DiagResult_id = mov.diagresult_id and DiagnosisResultDiagLink.Diag_id = mov.diag_id
      ) DiagResult on true
                    
      left join v_DiagAttribType DiagAttribType on DiagAttribType.DiagAttribType_id = mov.DiagAttribType_id
      left join DiagAttribDict DiagAttribDict on DiagAttribDict.DiagAttribDict_id = mov.DiagAttribDict_id  
      
  );  
    
    

END;
$$;


ALTER FUNCTION r477.p_registry_exp_bdiag(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_bprot(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_bprot(p_registry_id bigint) RETURNS TABLE(evn_id bigint, "D_PROT" text, "PROT" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 		bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);    
BEGIN

    return query (
	
      --поликлиника ТАП 
      select  
          rd.evn_id,
          to_char(mr.MorbusOnkoRefusal_setDT::date,'YYYY-MM-DD')::text as D_PROT,
          mrt.MorbusOnkoRefusalType_code::integer as PROT	
      from 
          r477.registrydata rd 
           join v_EvnVizitPL EL on EL.EvnVizitPL_pid = rd.evn_rid
           join v_MorbusOnkoVizitPLDop  OnkoVizit on OnkoVizit.EvnVizit_id = EL.EvnVizitPL_id
           join MorbusOnkoRefusal mr on mr.MorbusOnkoVizitPLDop_id = OnkoVizit.MorbusOnkoVizitPLDop_id
           join MorbusOnkoRefusalType mrt on mrt.MorbusOnkoRefusalType_id = mr.MorbusOnkoRefusalType_id
           left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
          rd.registry_id = any(_registry_id_arr) 
          and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
          and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPL'
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
          
      union 
      
      select  
          rd.evn_id,
          to_char(OnkoVizit.MorbusOnkoVizitPLDop_histDT::date,'YYYY-MM-DD')::text as D_PROT,
          hrt.histologicreasontype_code::integer as PROT	
      from 
          r477.registrydata rd 
           join v_EvnVizitPL EL on EL.EvnVizitPL_pid = rd.evn_rid
           join v_MorbusOnkoVizitPLDop  OnkoVizit on OnkoVizit.EvnVizit_id = EL.EvnVizitPL_id
           join HistologicReasonType hrt on OnkoVizit.histologicreasontype_id = hrt.histologicreasontype_id
           left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
          rd.registry_id = any(_registry_id_arr) 
          and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
          and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPL'
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
            
      union 
	  
      --стоматология ТАП 	
      select 
          rd.evn_id,
          to_char(mr.MorbusOnkoRefusal_setDT::date,'YYYY-MM-DD')::text as D_PROT,
          mrt.MorbusOnkoRefusalType_code::integer as PROT
      from r477.registrydata rd 
       join v_EvnDiagPLStom EvnDiagPLStom on EvnDiagPLStom.EvnDiagPLStom_rid = rd.evn_rid
       join v_MorbusOnkoDiagPLStom MorbusOnkoLeave on EvnDiagPLStom.EvnDiagPLStom_id = MorbusOnkoLeave.EvnDiagPLStom_id
       join MorbusOnkoRefusal mr on mr.morbusonkodiagplstom_id = MorbusOnkoLeave.morbusonkodiagplstom_id
       join MorbusOnkoRefusalType mrt on mrt.MorbusOnkoRefusalType_id = mr.MorbusOnkoRefusalType_id
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
       rd.registry_id = any(_registry_id_arr) 
       and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
       and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPLStom'
       and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
       and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
       
      union
      
      select 
          rd.evn_id,
          to_char(MorbusOnkoLeave.morbusonkodiagplstom_histdt::date,'YYYY-MM-DD')::text as D_PROT,
          hrt.histologicreasontype_code::integer as PROT
      from r477.registrydata rd 
       join v_EvnDiagPLStom EvnDiagPLStom on EvnDiagPLStom.EvnDiagPLStom_rid = rd.evn_rid
       join v_MorbusOnkoDiagPLStom MorbusOnkoLeave on EvnDiagPLStom.EvnDiagPLStom_id = MorbusOnkoLeave.EvnDiagPLStom_id
       join HistologicReasonType hrt on MorbusOnkoLeave.histologicreasontype_id = hrt.histologicreasontype_id
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
       rd.registry_id = any(_registry_id_arr) 
       and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
       and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPLStom'
       and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
       and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
       
      union 
      
      --стационар 
      select 
          rd.evn_id,
          to_char(mr.MorbusOnkoRefusal_setDT::date,'YYYY-MM-DD')::text as D_PROT,
          mrt.MorbusOnkoRefusalType_code::integer as PROT
      from r477.registrydata rd 
       join v_EvnSection EvnSection on EvnSection.evnsection_rid = rd.evn_rid
       join v_MorbusOnkoLeave MorbusOnkoLeave on EvnSection.evnsection_id = MorbusOnkoLeave.evnsection_id
       join MorbusOnkoRefusal mr on mr.morbusonkoleave_id = MorbusOnkoLeave.morbusonkoleave_id
       join MorbusOnkoRefusalType mrt on mrt.MorbusOnkoRefusalType_id = mr.MorbusOnkoRefusalType_id
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
       rd.registry_id = any(_registry_id_arr) 
       and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
       and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' 
       and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
       and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335      
       
       union 
       
       select 
          rd.evn_id,
          to_char(MorbusOnkoLeave.morbusonkoleave_histdt::date,'YYYY-MM-DD')::text as D_PROT,
          hrt.histologicreasontype_code::integer as PROT
      from r477.registrydata rd 
       join v_EvnSection EvnSection on EvnSection.evnsection_rid = rd.evn_rid
       join v_MorbusOnkoLeave MorbusOnkoLeave on EvnSection.evnsection_id = MorbusOnkoLeave.evnsection_id
       join HistologicReasonType hrt on MorbusOnkoLeave.histologicreasontype_id = hrt.histologicreasontype_id
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
       rd.registry_id = any(_registry_id_arr) 
       and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
       and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection'   
       and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
       and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
      
    ); 
    
    
END;
$$;


ALTER FUNCTION r477.p_registry_exp_bprot(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_cons(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_cons(p_registry_id bigint) RETURNS TABLE(evn_id bigint, "PR_CONS" integer, "DT_CONS" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN

	
  create temp table t_cons (evn_id bigint, pr_cons integer, dt_cons date) on commit drop;
  
  insert into t_cons (evn_id,pr_cons,dt_cons) 
  --поликлиника тап
  select  
    rd.evn_id,
    OnkoConsultResult.OnkoConsultResult_Code,
    OnkoConsult.OnkoConsult_consDate
  from 
    r477.registrydata rd      
     join v_EvnVizitPL EV on EV.EvnVizitPL_pid = rd.Evn_rid
     join v_MorbusOnkoVizitPLDop MorbusOnkoVizitPLDop on MorbusOnkoVizitPLDop.EvnVizit_id = EV.EvnVizitPL_id 
     join v_OnkoConsult OnkoConsult on OnkoConsult.MorbusOnkoVizitPLDop_id = MorbusOnkoVizitPLDop.MorbusOnkoVizitPLDop_id  
     join OnkoConsultResult OnkoConsultResult on OnkoConsult.OnkoConsultResult_id = OnkoConsultResult.OnkoConsultResult_id
     left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
  where 
    rd.registry_id = any(_registry_id_arr) 
    and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
    and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPL'
    and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
    and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 

  union all
                
  --стоматология тап 
  select  
      rd.evn_id,
      OnkoConsultResult.OnkoConsultResult_Code,
      OnkoConsult.OnkoConsult_consDate
  from r477.registrydata rd 
   join v_EvnDiagPLStom EvnDiagPLStom on EvnDiagPLStom.evndiagplstom_rid = rd.evn_rid 
   join v_MorbusOnkoDiagPLStom MorbusOnkoDiagPLStom on MorbusOnkoDiagPLStom.evndiagplstom_id = EvnDiagPLStom.evndiagplstom_id
   join v_OnkoConsult OnkoConsult on OnkoConsult.MorbusOnkoDiagPLStom_id = MorbusOnkoDiagPLStom.MorbusOnkoDiagPLStom_id
   join OnkoConsultResult OnkoConsultResult on OnkoConsult.OnkoConsultResult_id = OnkoConsultResult.OnkoConsultResult_id
   left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
  where 
      rd.registry_id = any(_registry_id_arr) 
      and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
      and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPLStom'
      and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
      and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
            
  union all 
        
  --стационары 
  select  
      rd.evn_id,
      OnkoConsultResult.OnkoConsultResult_Code,
      OnkoConsult.OnkoConsult_consDate
  from r477.registrydata rd 
   join v_EvnSection EvnSection on rd.Evn_id = EvnSection.EvnSection_id 
   join v_MorbusOnkoLeave MorbusOnkoLeave on MorbusOnkoLeave.evnsection_id = EvnSection.evnsection_id
   join v_OnkoConsult OnkoConsult on MorbusOnkoLeave.MorbusOnkoLeave_id = OnkoConsult.MorbusOnkoLeave_id
   join OnkoConsultResult OnkoConsultResult on OnkoConsult.OnkoConsultResult_id = OnkoConsultResult.OnkoConsultResult_id
   left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
  where 
      rd.registry_id = any(_registry_id_arr) 
      and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
      and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' 	
      and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
      and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
  ;
  
  create index on t_cons (evn_id);
  analyze t_cons;
  
  


  return query (
	
    select  
    	rd.evn_id,
        0::integer as PR_CONS,
        null::text as DT_CONS  
    from 
    	r477.registrydata rd
    	left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
    	rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and not exists (select 1 from t_cons t where rd.evn_id = t.evn_id)
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
        
    union 
    
    select 
    	t.evn_id,
        t.pr_cons as PR_CONS,
        to_char(t.dt_cons,'YYYY-MM-DD') as DT_CONS 
    from t_cons t
      
  ); 
    
   
END;
$$;


ALTER FUNCTION r477.p_registry_exp_cons(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_crit(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_crit(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, "CRIT" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN

	
      return query (
	
		select 
            t.evn_id,unnest(t.crit)::text as CRIT   
        from ( 
            select  
                rd.evn_id,
                case 
                    when moc.mesolduslugacomplex_ivlhours >= 480 then array['it2','it4']
                    when moc.mesolduslugacomplex_sofascalepoints >= 5 or (moc.mesagegroup_id = 5 and moc.mesolduslugacomplex_sofascalepoints >= 4) and moc.mesolduslugacomplex_ivlhours >= 72 then array['it1']
                    when moc.mesolduslugacomplex_ivlhours between 0 and 120 then array['it3']
                    when moc.UslugaComplex_aid is not null and moc.UslugaComplex_bid is not null then array['rbs']
                    when moc.MesOldUslugaComplex_FracFrom is not null then array['fr' || right('0'||rtrim(cast(moc.MesOldUslugaComplex_FracFrom as varchar)),2)||'-'||right('0'|| coalesce(rtrim(cast(moc.MesOldUslugaComplex_Fracto as varchar)),'99'),2)]
                    when rs.rehabscale_code = '2' then array['rb2']
                    when rs.rehabscale_code = '3' then array['rb3']
                    when rs.rehabscale_code = '4' then array['rb4']
                    when rs.rehabscale_code = '5' then array['rb5']
                    when rs.rehabscale_code = '6' then array['rb6']            
                    else case when md.mesdop_code is not null then array[md.mesdop_code] else null end 
                end as crit
            from 
                r477.registrydata rd  
                 join MesOldUslugaComplex moc on rd.mesolduslugacomplex_id = moc.mesolduslugacomplex_id     
                 left join RehabScale rs on moc.rehabscale_id = rs.rehabscale_id
                 left join MesDop md on moc.mesdop_id = md.mesdop_id
            where 
                rd.registry_id = any(_registry_id_arr)  
                and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
                and rd.region_data ->> 'item_type' = 'stac'
                and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
        )t 
        where t.crit is not null 

        union all 

        select 
            rd.evn_id,
            dts.drugtherapyscheme_code::text as CRIT  
        from 
            r477.registrydata rd 
             join EvnSectionDrugTherapyScheme esdts on esdts.evnsection_id = rd.evn_id
             join DrugTherapyScheme dts on esdts.drugtherapyscheme_id = dts.drugtherapyscheme_id 
        where 
            rd.registry_id = any(_registry_id_arr)   
            and rd.registrydata_iszno = 1
            and rd.region_data ->> 'item_type' = 'stac'
            and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
		
	  );  
    
   


END;
$$;


ALTER FUNCTION r477.p_registry_exp_crit(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_date_inj(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_date_inj(p_registry_id bigint) RETURNS TABLE(evn_id bigint, evnusluga_id bigint, morbusonkodrug_id bigint, "DATE_INJ" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN
  
return query (

      select  
          rd.evn_id,
          ru.evnusluga_id,
          MorbusOnkoDrug.morbusonkodrug_id,
          to_char(inj_dat.day,'YYYY-MM-DD') as DATE_INJ
      from r477.registrydata rd 
       join r477.registryusluga ru on rd.registry_id = ru.registry_id and ru.evn_id = ru.evn_id 
       join v_MorbusOnkoDrug MorbusOnkoDrug on MorbusOnkoDrug.evn_id = ru.evnusluga_id
       
       left join lateral (
          -- каждый день заданного периода
          select generate_series(
            MorbusOnkoDrug.MorbusOnkoDrug_begDT,
            coalesce(MorbusOnkoDrug.MorbusOnkoDrug_endDT,MorbusOnkoDrug.MorbusOnkoDrug_begDT),
            '1 day') as day 
        ) inj_dat on true
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
      where 
         rd.registry_id = any(_registry_id_arr) 
         and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
         and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' 
         and ru.region_data ->> 'evnclass_sysnick' in ('EvnUslugaOnkoGormun','EvnUslugaOnkoChem')

         and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
         and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335

);

END;
$$;


ALTER FUNCTION r477.p_registry_exp_date_inj(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_dost(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_dost(p_registry_id bigint) RETURNS TABLE(person_id bigint, "DOST" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
BEGIN

  return query (
	
      select distinct
          rd.person_id,
          unnest(
              string_to_array(
                  concat_ws(',',
                      case when nullif(rd.region_data -> 'person' ->> 'surname','') is null then '2' end,
                      case when nullif(rd.region_data -> 'person' ->> 'firname','') is null then '3' end,
                      case when nullif(nullif(upper(rd.region_data -> 'person' ->> 'secname'),''),'НЕТ') is null then '1' end
                  )
              ,',')
          )::integer as DOST  
      from 
          r477.registrydata rd    
          left join lateral ( select re.evn_id
									from r477.registryerror re
									where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
									limit 1
									) r_err on true	
      where 
          rd.registry_id = any(_registry_id_arr) 
          --and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
          and rd.region_data -> 'deputy' is null 
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
            
    );  

END;
$$;


ALTER FUNCTION r477.p_registry_exp_dost(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_dost_p(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_dost_p(p_registry_id bigint) RETURNS TABLE(person_id bigint, "DOST_P" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
BEGIN

  return query (
	
      select distinct
          rd.person_id,
          unnest(
              string_to_array(
                  concat_ws(',',
                      case when nullif(rd.region_data -> 'deputy' ->> 'surname','') is null then '2' end,
                      case when nullif(rd.region_data -> 'deputy' ->> 'firname','') is null then '3' end,
                      case when nullif(nullif(upper(rd.region_data -> 'deputy' ->> 'secname'),''),'НЕТ') is null then '1' end
                  )
              ,',')
          )::integer as DOST  
      from 
          r477.registrydata rd    
          left join lateral ( select re.evn_id
									from r477.registryerror re
									where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
									limit 1
									) r_err on true	
      where 
          rd.registry_id = any(_registry_id_arr) 
          --and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
          and rd.region_data -> 'deputy' is not null 
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
            
    );  

END;
$$;


ALTER FUNCTION r477.p_registry_exp_dost_p(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_ds2(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_ds2(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, diag_id bigint, "DS2" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN
	
      return query (
	
		--поликлиника 
        select 
            rd.evn_id,
            Diag.diag_id,
            Diag.diag_scode::text as DS2
        from 
            r477.registrydata rd 
             join v_evndiagplsop ds on ds.evndiagplsop_rid = rd.evn_rid
             join Diag on ds.diag_id = Diag.diag_id
             left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
          rd.registry_id = any(_registry_id_arr) 
          and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
          
        union 
        
        --стационар по всему случаю 
        select 
            rd.evn_id,
            Diag.diag_id,
            Diag.diag_scode::text as DS2
        from 
            r477.registrydata rd 
             join v_EvnDiagPS ds on ds.evndiagps_rid = rd.evn_rid
             join Diag on ds.diag_id = Diag.diag_id
	    	left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	             
        where 
          rd.registry_id = any(_registry_id_arr)  
          and ds.diagsetclass_id = 3 
          and not coalesce(rd.region_data ->> 'is_2ksg_pay','false')::boolean 
          and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
          
        union 
        
        --стационар по движению
        select 
            rd.evn_id,
            Diag.diag_id,
            Diag.diag_scode::text as ds2
        from 
            r477.registrydata rd 
             join v_EvnDiagPS ds on ds.evndiagps_pid = rd.evn_id
             join Diag on ds.diag_id = Diag.diag_id
             left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
          rd.registry_id = any(_registry_id_arr)  
          and ds.diagsetclass_id = 3 
          and coalesce(rd.region_data ->> 'is_2ksg_pay','false')::boolean 
          and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
                 	
	  );  

END;
$$;


ALTER FUNCTION r477.p_registry_exp_ds2(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_ds3(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_ds3(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, diag_id bigint, "DS3" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN

	  return query (
	
		--стационар по всему случаю 
        select 
            rd.evn_id,
            Diag.diag_id,
            Diag.diag_scode::text as DS3
        from 
            r477.registrydata rd 
             join v_EvnDiagPS ds on ds.evndiagps_rid = rd.evn_rid
             join Diag on ds.diag_id = Diag.diag_id
             left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
          rd.registry_id = any(_registry_id_arr) 
          and ds.diagsetclass_id = 2
          and not coalesce(rd.region_data ->> 'is_2ksg_pay','false')::boolean 
          and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
          
        union 
        
        --стационар по движению
        select 
            rd.evn_id,
            Diag.diag_id,
            Diag.diag_scode::text as DS3
        from 
            r477.registrydata rd 
             join v_EvnDiagPS ds on ds.evndiagps_pid = rd.evn_id
             join Diag on ds.diag_id = Diag.diag_id
             left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where 
          rd.registry_id = any(_registry_id_arr)  
          and ds.diagsetclass_id = 2
          and coalesce(rd.region_data ->> 'is_2ksg_pay','false')::boolean 
          and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
          and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
          and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
                 	
	  );  
    
    
END;
$$;


ALTER FUNCTION r477.p_registry_exp_ds3(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_kslp(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_kslp(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, "IDSL" text, "Z_SL" numeric)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN

	
      return query (
	
		select distinct 
            rd.evn_id,
            kslp.evnsectionkslplink_code::text as ID_SL,
            kslp.evnsectionkslplink_value::numeric(14,5) as Z_SL
        from 
            r477.registrydata rd 
             join v_EvnSectionKSLPLink kslp on kslp.evnsection_id = rd.evn_id 
        where 
            rd.registry_id = any(_registry_id_arr)  
            and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
            and rd.region_data ->> 'item_type' = 'stac'
            and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
		
	  );  
    
   


END;
$$;


ALTER FUNCTION r477.p_registry_exp_kslp(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_lek_pr(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_lek_pr(p_registry_id bigint) RETURNS TABLE(evn_id bigint, evnusluga_id bigint, "REGNUM" text, "CODE_SH" text, drugmnn_id bigint, drugtherapyscheme_id bigint, morbusonkodrug_id bigint)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  	
BEGIN

    return query (
	
      select distinct 
          rd.evn_id,
          ru.evnusluga_id,
          lpad(DrugMnn.drugmnn_code::text,6,'0') as REGNUM,
          case 
              when (rd.region_data -> 'person' ->> 'age')::integer < 18 or diag_code between 'C81' and 'C96' then 'нет' 
              else DTS.DrugTherapyScheme_Code::text 
          end as CODE_SH,
          MorbusOnkoDrug.DrugMnn_id as drugmnn_id,
          DTS.DrugTherapyScheme_id as drugtherapyscheme_id,
          MorbusOnkoDrug.morbusonkodrug_id
      from r477.registrydata rd 
       join r477.registryusluga ru on rd.registry_id = ru.registry_id and rd.evn_id = ru.evn_id 
       join v_MorbusOnkoDrug MorbusOnkoDrug on MorbusOnkoDrug.evn_id = ru.evnusluga_id
       join fed.DrugMnn on MorbusOnkoDrug.DrugMnn_id = DrugMnn.DrugMNN_id
       join Diag on Diag.Diag_id = rd.Diag_id
       
       left join lateral (
          select DTSMNNLink.DrugTherapyScheme_id from v_DrugTherapySchemeMNNLink DTSMNNLink  
           join EvnSectionDrugTherapyScheme ESDTS on DTSMNNLink.DrugTherapyScheme_id = ESDTS.DrugTherapyScheme_id and ESDTS.EvnSection_id = rd.evn_id
          where DTSMNNLink.DrugMNN_id = DrugMnn.DrugMnn_id
          limit 1
       ) DTSMNNLink on true
      	
       left join lateral (  
        select ES_DTS.DrugTherapyScheme_id from EvnSectionDrugTherapyScheme ES_DTS  
         left join v_DrugTherapySchemeMNNLink DTSMNNLink on DTSMNNLink.DrugTherapyScheme_id = ES_DTS.DrugTherapyScheme_id
        where 
          ES_DTS.EvnSection_id = rd.Evn_id 
          --and DTSMNNLink.DrugTherapyScheme_id is null --убрал условие - его покроет валидация Err_Regnum_Code_sh
        limit 1
       ) DTSMNNLinkES on true
       
       left join v_DrugTherapyScheme DTS on coalesce(DTSMNNLink.DrugTherapyScheme_id,DTSMNNLinkES.DrugTherapyScheme_id) = DTS.DrugTherapyScheme_id
       left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
       where 
         rd.registry_id = any(_registry_id_arr) 
         and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
         and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' 
         and ru.region_data ->> 'evnclass_sysnick' in ('EvnUslugaOnkoGormun','EvnUslugaOnkoChem','EvnUslugaOnkoChemBeam')  
         and 
         	--для USL_TIP = 3 LEK_PR выгружаться не должен 
            case 
            	when ru.region_data ->> 'evnclass_sysnick' = 'EvnUslugaOnkoGormun' then 
                	exists ( 
                    	select 1 from v_EvnUslugaOnkoGormun EvnUslugaOnkoGormun 
                        where 
                        	EvnUslugaOnkoGormun.evnuslugaonkogormun_id = ru.evnusluga_id                             
         					and EvnUslugaOnkoGormun.evnuslugaonkogormun_isdrug = 2
                    )
                else true 
            end              
         and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаленными 
         and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
      
      
    ); 
    
    
END;
$$;


ALTER FUNCTION r477.p_registry_exp_lek_pr(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_napr(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_napr(p_registry_id bigint) RETURNS TABLE(evn_id bigint, "NAPR_DATE" text, "NAPR_MO" text, "NAPR_V" integer, "MET_ISSL" integer, "NAPR_USL" text, clinic_code text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _lpu_code 			text;
    _lpu_sid 			bigint;
BEGIN

  select 
      l.lpu_f003mcod,r.lpu_id
      into _lpu_code, _lpu_sid 
  from r477.registry r  
   join lpu l on r.lpu_id = l.lpu_id
  where r.registry_id = p_registry_id   
  ;  

return query (
	
	--направления из ЭМК 
    select 
        rd.evn_id,
        to_char(ed_zno.EvnDirection_setDate,'yyyy-mm-dd')::text as NAPR_DATE,
        case 
        	when _lpu_code <> coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod,'') then coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod) 
            else null 
        end::text NAPR_MO,
        case 
            when dt.dirtype_code in (3,12) then 1 
            when dt.dirtype_code = 7 then 2 
            when dt.dirtype_code in (6,8,13) then 4 
         end as NAPR_V,
        null::integer as MET_ISSL,
        null::text as NAPR_USL,
        coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text as clinic_code
    from 
        r477.registrydata rd 
         join v_EvnDirection_all ed_zno on ed_zno.EvnDirection_rid = rd.Evn_rid  
         join DirType dt on ed_zno.dirtype_id = dt.dirtype_id
         join LpuSectionProfile lsp on lsp.lpusectionprofile_id = ed_zno.lpusectionprofile_id 
         left join Lpu LpuD on LpuD.Lpu_id = ed_zno.lpu_did
         left join Lpu LpuO on lpuo.org_id = ed_Zno.org_oid
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and ed_zno.DirFailType_id is null				--нет отказа
        and dt.dirtype_code in (3,7,12,6,8,13)					
        and case when dt.dirtype_code in (3,12) then lsp.lpusectionprofile_code in ('18','60') else true end	--онкология, детская онкология       		
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
        
    union 
    
    --назначение на онколога
    select 
        rd.evn_id,
        to_char(EvnPrescr.EvnPrescr_setdate,'YYYY-MM-DD')::text as NAPR_DATE,
        case 
        	when _lpu_code <> coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text then coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text 
            else null 
        end as NAPR_MO,
        1::integer as NAPR_V,
        null::integer as MET_ISSL,
        null::text as NAPR_USL,
        coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text as clinic_code
    from 
        r477.registrydata rd 
         join v_EvnPrescr EvnPrescr on EvnPrescr.EvnPrescr_rid = rd.evn_rid 
         join v_EvnUsluga EU on eu.EvnPrescr_id = EvnPrescr.EvnPrescr_id 
         join UslugaComplex UC on EU.uslugacomplex_id = UC.uslugacomplex_id
         join EvnPrescrDirection on EvnPrescr.EvnPrescr_id = EvnPrescrDirection.EvnPrescr_id
         left join v_EvnDirection_all ED_ZNO on ED_ZNO.EvnDirection_id = EvnPrescrDirection.EvnDirection_id
         left join Lpu LpuD on ED_ZNO.Lpu_did = LpuD.Lpu_id 
         left join Lpu LpuO on lpuo.org_id = ED_ZNO.org_oid 
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and UC.uslugacomplex_code = 'B01.027.001'	--Прием (осмотр, консультация) врача-онколога первичный
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
    
    union 
    
    --паталогогистология из случая 
    select 
        rd.evn_id,
        to_char(Histologic.EvnDirectionHistologic_setDate,'YYYY-MM-DD')::text as NAPR_DATE,
        case when _lpu_code is distinct from LpuD.Lpu_f003mcod::text then LpuD.Lpu_f003mcod::text else null end as NAPR_MO,
        2::integer as NAPR_V,
        null::integer as MET_ISSL,
        null::text as NAPR_USL,
        LpuD.Lpu_f003mcod::text as clinic_code
    from 
        r477.registrydata rd 
        join v_EvnDirectionHistologic Histologic on Histologic.EvnDirectionHistologic_rid = rd.evn_rid 
        left join v_Lpu LpuD on coalesce(Histologic.Lpu_did,Histologic.Lpu_aid) = LpuD.Lpu_id
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
        
    union 
    
    --паталогогистология за период
    select 
        rd.evn_id,
        to_char(Histologic.EvnDirectionHistologic_setDate,'YYYY-MM-DD')::text as NAPR_DATE,
        case when _lpu_code is distinct from LpuD.Lpu_f003mcod::text then LpuD.Lpu_f003mcod::text else null end as NAPR_MO,
        2::integer as NAPR_V,
        null::integer as MET_ISSL,
        null::text as NAPR_USL,
        LpuD.Lpu_f003mcod::text as clinic_code
    from 
        r477.registrydata rd 
        join v_EvnDirectionHistologic Histologic on Histologic.person_id = rd.person_id    	
        left join v_Lpu LpuD on coalesce(Histologic.Lpu_did,Histologic.Lpu_aid) = LpuD.Lpu_id
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and Histologic.EvnDirectionHistologic_setDate between rd.Evn_setDate and rd.Evn_disDate
        and Histologic.lpu_sid = _lpu_sid	--выполнено в МО реестра 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
        
    union 
    
    --лабораторная и функциональная диагностика
    select 
        rd.evn_id,
        to_char(EvnPrescr.EvnPrescr_setdate,'YYYY-MM-DD')::text as NAPR_DATE,
        case 
        	when _lpu_code <> coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text then coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text 
            else null
        end as NAPR_MO,
        3::integer as NAPR_V,
        case 
            when UCA.v2 > 0 then 3
            when UCA.v3 > 0 then 4
            when EvnPrescr.EvnClass_id = 80 then 1
            when EvnPrescr.EvnClass_id = 81 then 2
        end as MET_ISSL,
        UC.UslugaComplex_Code::text as NAPR_USL,
        coalesce(LpuD.Lpu_f003mcod,LpuO.Lpu_f003mcod)::text as clinic_code        
    from 
        r477.registrydata rd 
         join v_EvnPrescr EvnPrescr on EvnPrescr.EvnPrescr_rid = rd.evn_rid and EvnPrescr.EvnClass_id in (80,81) --лаб/функциональная диагностика
         join v_EvnUsluga EU on eu.EvnPrescr_id = EvnPrescr.EvnPrescr_id 
         join UslugaComplex UC on EU.uslugacomplex_id = UC.uslugacomplex_id
         
         left join lateral (
            select
              count (*) filter (where UCAT.uslugacomplexattributetype_sysnick = 'ray') as v2,
              count (*) filter (where UCAT.uslugacomplexattributetype_sysnick in ('kt','mrt')) as v3
              from v_UslugaComplexAttribute UCA
               join UslugaComplexAttributeType UCAT on UCA.uslugacomplexattributetype_id = UCAT.uslugacomplexattributetype_id
              where 
                UC.UslugaComplex_id = UCA.UslugaComplex_id 
                and UCAT.uslugacomplexattributetype_sysnick in ('ray','mrt','kt')
                and EvnPrescr.EvnPrescr_setDate::date <@ daterange(UCA.uslugacomplexattribute_begdate::date,UCA.uslugacomplexattribute_enddate::date,'[]')
        ) UCA on true
         
         left join EvnPrescrDirection on EvnPrescr.EvnPrescr_id = EvnPrescrDirection.EvnPrescr_id
         left join v_EvnDirection_all ED_ZNO on ED_ZNO.EvnDirection_id = EvnPrescrDirection.EvnDirection_id
         left join Lpu LpuD on ED_ZNO.Lpu_did = LpuD.Lpu_id 
         left join Lpu LpuO on lpuo.org_id = ED_ZNO.org_oid
         left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
       	
);  

END;
$$;


ALTER FUNCTION r477.p_registry_exp_napr(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_onk_sl(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_onk_sl(p_registry_id bigint) RETURNS TABLE(evn_id bigint, "DS1_T" integer, "STAD" integer, "ONK_T" integer, "ONK_N" integer, "ONK_M" integer, "MTSTZ" integer, "SOD" numeric, "K_FR" integer, "WEI" numeric, "HEI" integer, "BSA" numeric)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _onkotreatment_id 	bigint   = (select onkotreatment_id from v_OnkoTreatment o where o.onkotreatment_code = 5 limit 1); --айдишник DS1_T = 5
BEGIN

	create temp table t_onk_sl (
    	evn_id bigint,person_id bigint,onko_pid bigint,evn_disdate date,onkotreatment_id bigint,
        diag_id bigint,tumorstage_fid bigint,onkot_fid bigint,onkon_fid bigint,onkom_fid bigint,mtstz integer,
        evnclass_sysnick text
    ) on commit drop
    ;
    
    --create unique index on t_onk_sl (evn_id);    
    
    
    insert into t_onk_sl (
        evn_id,person_id,onko_pid,evn_disdate,onkotreatment_id,
        diag_id,tumorstage_fid,onkot_fid,onkon_fid,onkom_fid,mtstz,
        evnclass_sysnick  
    )
    --специфика по онкологии поликлиника 
    select 
        rd.evn_id,rd.person_id,
        mov.evnvizitpl_id as onko_pid,
        rd.evn_disdate::date as evn_disdate,
        mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
        mov.mtstz,rd.region_data ->> 'evnclass_sysnick' as evnclass_sysnick
    from 
        r477.registrydata rd
        join lateral (
            select  
                pl.evnvizitpl_id,mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,
                mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
                case 
                    when mov.MorbusOnkoVizitPLDop_IsTumorDepoUnknown = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoLympha = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoBones = 2 or
                         mov.MorbusOnkoVizitPLDop_IsTumorDepoLiver = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoLungs = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoBrain = 2 or
                         mov.MorbusOnkoVizitPLDop_IsTumorDepoSkin = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoKidney = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoOvary = 2 or
                         mov.MorbusOnkoVizitPLDop_IsTumorDepoPerito = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoMarrow = 2 or mov.MorbusOnkoVizitPLDop_IsTumorDepoOther = 2 or
                         mov.MorbusOnkoVizitPLDop_IsTumorDepoMulti = 2
                    then 1
                    else null 
                end as mtstz
            from v_EvnVizitPl pl 
             join v_MorbusOnkoVizitPLDop mov on pl.evnvizitpl_id = mov.evnvizit_id
            where pl.evnvizitpl_rid = rd.evn_rid
            order by pl.evnvizitpl_setdate desc 
            limit 1
        ) as mov on true
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) 
        and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
        and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPL'
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
             
    union all            
                    
    --специфика по онкологии из стоматологии
    select 
        rd.evn_id,rd.person_id,
        mov.evndiagplstom_id as onko_pid,
        rd.evn_disdate::date as evn_disdate,
        mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
        mov.mtstz,rd.region_data ->> 'evnclass_sysnick' as evnclass_sysnick
    from 
        r477.registrydata rd
        join lateral (
            select  
                pl.evndiagplstom_id,mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,
                mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
                case 
                    when mov.MorbusOnkoDiagPLStom_IsTumorDepoUnknown = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoLympha = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoBones = 2 or
                         mov.MorbusOnkoDiagPLStom_IsTumorDepoLiver = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoLungs = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoBrain = 2 or
                         mov.MorbusOnkoDiagPLStom_IsTumorDepoSkin = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoKidney = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoOvary = 2 or
                         mov.MorbusOnkoDiagPLStom_IsTumorDepoPerito = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoMarrow = 2 or mov.MorbusOnkoDiagPLStom_IsTumorDepoOther = 2 or
                         mov.MorbusOnkoDiagPLStom_IsTumorDepoMulti = 2
                    then 1
                    else null 
                end as mtstz
            from v_EvnDiagPLStom pl 
             join v_MorbusOnkoDiagPLStom mov on mov.evndiagplstom_id = pl.evndiagplstom_id
            where pl.evndiagplstom_rid = rd.evn_rid
            order by pl.evndiagplstom_setdate desc 
            limit 1
        ) as mov on true  
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) 
        and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
        and rd.region_data ->> 'evnclass_sysnick' = 'EvnVizitPLStom'
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
            
    union all 
        
    --параклиника, для всех выгружаем DS1_T = 5 
    select 
        rd.evn_id,rd.person_id,
        null::bigint as onko_pid,
        rd.evn_disdate::date as evn_disdate,
        _onkotreatment_id as onkotreatment_id,null::bigint as diag_id,
        null::bigint as tumorstage_fid,null::bigint as onkot_fid,null::bigint as onkon_fid,
        null::bigint as onkom_fid,null::integer as mtstz,
        rd.region_data ->> 'evnclass_sysnick' as evnclass_sysnick
    from 
        r477.registrydata rd
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) 
        and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
        and rd.region_data ->> 'evnclass_sysnick' = 'EvnUslugaPar' 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
        
    union all 
    
    --стационары
    select 
        rd.evn_id,rd.person_id,
        mov.evnsection_id as onko_pid,
        rd.evn_disdate::date as evn_disdate,
        mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
        mov.mtstz,rd.region_data ->> 'evnclass_sysnick' as evnclass_sysnick
    from 
        r477.registrydata rd
        join lateral (
            select  
                es.evnsection_id,mov.onkotreatment_id,mov.diag_id,mov.tumorstage_fid,
                mov.onkot_fid,mov.onkon_fid,mov.onkom_fid,
                case 
                    when mov.MorbusOnkoLeave_IsTumorDepoUnknown = 2 or mov.MorbusOnkoLeave_IsTumorDepoLympha = 2 or mov.MorbusOnkoLeave_IsTumorDepoBones = 2 or
                         mov.MorbusOnkoLeave_IsTumorDepoLiver = 2 or mov.MorbusOnkoLeave_IsTumorDepoLungs = 2 or mov.MorbusOnkoLeave_IsTumorDepoBrain = 2 or
                         mov.MorbusOnkoLeave_IsTumorDepoSkin = 2 or mov.MorbusOnkoLeave_IsTumorDepoKidney = 2 or mov.MorbusOnkoLeave_IsTumorDepoOvary = 2 or
                         mov.MorbusOnkoLeave_IsTumorDepoPerito = 2 or mov.MorbusOnkoLeave_IsTumorDepoMarrow = 2 or mov.MorbusOnkoLeave_IsTumorDepoOther = 2 or
                         mov.MorbusOnkoLeave_IsTumorDepoMulti = 2
                    then 1
                    else null 
                end as mtstz
            from v_EvnSection es 
             join v_MorbusOnkoLeave mov on es.evnsection_id = mov.evnsection_id
            where 
            	es.evnsection_rid = rd.evn_rid
                and es.evnsection_ispriem is distinct from 2 
            order by es.evnsection_setdate desc 
            limit 1
        ) as mov on true
        left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) 
        and rd.registrydata_iszno = 1 and coalesce(rd.region_data ->> 'ds_onk','0') = '0' 
        and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection'   
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335  
           
    ;
    
    
return query (
	
	select 
    	t.evn_id,
        OnkoTreatment.onkotreatment_code as DS1_T,
        TumorStageLink.tumorstagelink_codestage as STAD,
        OnkoTLink.onkotlink_codestage as ONK_T,
        OnkoNLink.onkonlink_codestage as ONK_N,
        OnkoMLink.onkomlink_codestage as ONK_M,
        case when OnkoTreatment.onkotreatment_code in (1,2) and t.mtstz = 1 then 1 else null end as MTSTZ,
        case 
        	when t.evnclass_sysnick = 'EvnSection' then 
            	case when coalesce(eu.pid,eg.pid,ecb.pid) is not null then coalesce(eu.sod,0) + coalesce(eg.sod,0) + coalesce(ecb.sod,0) else null end
            else null 
        end as SOD,
        case 
        	when t.evnclass_sysnick = 'EvnSection' then 
            	case when coalesce(eu.pid,eg.pid,ecb.pid) is not null then (coalesce(eu.k_fr,0) + coalesce(eg.k_fr,0) + coalesce(ecb.k_fr,0))::integer else null end
            else null 
        end as K_FR,
        case when t.evnclass_sysnick = 'EvnSection' then wei.wei::numeric else null end as WEI,
        case when t.evnclass_sysnick = 'EvnSection' then hei.hei::integer else null end as HEI,
        case when t.evnclass_sysnick = 'EvnSection' then round(SQRT(wei.wei * hei.hei / 3600)::numeric,2) else null end as BSA
    from t_onk_sl t 
     left join OnkoTreatment on OnkoTreatment.onkotreatment_id = t.onkotreatment_id
     
     --STAD
     left join lateral (
     	select TumorStageLink.tumorstagelink_codestage from dbo.v_tumorstagelink TumorStageLink 
        where 
        	t.tumorstage_fid = TumorStageLink.tumorstage_fid and (t.diag_id = TumorStageLink.Diag_id or TumorStageLink.Diag_id is null)
        	and t.evn_disdate <@ daterange(TumorStageLink.TumorStageLink_begDate::date,TumorStageLink.TumorStageLink_endDate::date)
        order by TumorStageLink.Diag_id nulls last 
        limit 1 
     ) as TumorStageLink on true 
     
     --ONK_T
     left join lateral (
     	select OnkoTLink.onkotlink_codestage from dbo.v_onkotlink OnkoTLink
        where 
        	t.onkot_fid = OnkoTLink.onkot_fid and (t.diag_id = OnkoTLink.Diag_id or OnkoTLink.Diag_id is null)
        	and t.evn_disdate <@ daterange(OnkoTLink.OnkoTLink_begDate::date,OnkoTLink.OnkoTLink_endDate::date)
        order by OnkoTLink.Diag_id nulls last 
        limit 1 
     ) as OnkoTLink on true
     
     --ONK_N
     left join lateral (
     	select OnkoNLink.onkonlink_codestage from dbo.v_onkonlink OnkoNLink
        where 
        	t.onkon_fid = OnkoNLink.onkon_fid and (t.diag_id = OnkoNLink.Diag_id or OnkoNLink.Diag_id is null)
        	and t.evn_disdate <@ daterange(OnkoNLink.OnkoNLink_begDate::date,OnkoNLink.OnkoNLink_endDate::date)
        order by OnkoNLink.Diag_id nulls last 
        limit 1 
     ) as OnkoNLink on true
     
     --ONK_M
     left join lateral (
     	select OnkoMLink.onkomlink_codestage from dbo.v_onkomlink OnkoMLink
        where 
        	t.onkom_fid = OnkoMLink.onkom_fid and (t.diag_id = OnkoMLink.Diag_id or OnkoMLink.Diag_id is null)
        	and t.evn_disdate <@ daterange(OnkoMLink.OnkoMLink_begDate::date,OnkoMLink.OnkoMLink_endDate::date)
        order by OnkoMLink.Diag_id nulls last 
        limit 1 
     ) as OnkoMLink on true
     
     --SOD/K_FR - лучевое лечение
     left join lateral (
    	select 
        	eu.evnuslugaonkobeam_pid as pid,
            sum(coalesce(eu.EvnUslugaOnkoBeam_TotalDoseTumor,0)::numeric(5,2)) as sod,
			sum(coalesce(EvnUslugaOnkoBeam_CountFractionRT,0)::numeric(5,2)) as k_fr
        from v_EvnUslugaOnkoBeam eu          
        where 
        	eu.evnuslugaonkobeam_pid = t.onko_pid
        group by 1          
     ) eu on true
     
     --SOD/K_FR - гормоноимуннотерапия
     left join lateral (
		select
			eg.EvnUslugaOnkoGormun_pid as pid,
            sum(coalesce(eg.evnuslugaonkogormun_totaldosetumor,0)::numeric(5,2)) as sod, 
            sum(coalesce(EvnUslugaOnkoGormun_CountFractionRT,0)::numeric(5,2)) as k_fr
		from v_EvnUslugaOnkoGormun eg		
		where 
        	eg.EvnUslugaOnkoGormun_pid = t.onko_pid
			and eg.EvnUslugaOnkoGormun_IsBeam = 2 and eg.EvnUslugaOnkoGormun_IsDrug = 2
        group by 1 
	 ) eg on true
     
     --SOD/K_FR - хмимиолучевое лечение
     left join lateral (
     	select
        	ecb.evnuslugaonkochembeam_pid as pid,
            sum(coalesce(ecb.evnuslugaonkochembeam_totaldosetumor,0)::numeric(5,2)) as sod,
            sum(coalesce(ecb.evnuslugaonkochembeam_countfractionrt,0)::numeric(5,2)) as k_fr
        from v_EvnUslugaOnkoChemBeam ecb
        where
        	ecb.evnuslugaonkochembeam_pid = t.onko_pid
        group by 1
     ) ecb on true
	 
	 --WEI
     left join lateral (
        select
          case when Okei_id = 36  then PersonWeight_Weight/1000 else PersonWeight_Weight end::numeric(8,1) as wei
        from v_PersonWeight PersonWeight
        where 
        	PersonWeight.Person_id = t.person_id and WeightMeasureType_id = 3 --плановый вид измерения
        	and PersonWeight_setDT::date <= t.evn_disdate
        order by PersonWeight_setDT desc
        limit 1
	) wei on true
    
    --HEI
    left join lateral (
        select PersonHeight_Height as hei from v_PersonHeight PersonHeight
        where 
        	PersonHeight.Person_id = t.Person_id and HeightMeasureType_id = 3 --плановый вид измерения
        	and PersonHeight_setDT <= t.evn_disdate
        order by PersonHeight_setDT desc
        limit 1
	) hei on true
       	
);

END;
$$;


ALTER FUNCTION r477.p_registry_exp_onk_sl(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_onk_usl(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_onk_usl(p_registry_id bigint) RETURNS TABLE(evn_id bigint, evnusluga_id bigint, "USL_TIP" integer, "HIR_TIP" integer, "LEK_TIP_L" integer, "LEK_TIP_V" integer, "LUCH_TIP" integer, "PPTR" integer)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    _evn_id_arr 		bigint[];	
BEGIN

	_evn_id_arr = array(
    	select rd.evn_id from r477.registrydata rd
    	left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
        where rd.registry_id = any(_registry_id_arr) and rd.registrydata_iszno = 1 
        and rd.region_data ->> 'evnclass_sysnick' = 'EvnSection'
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335 
    );
    
    if _evn_id_arr = '{}'::bigint[] then return; end if;
    
    

    return query (
	
        --USL_TIP = 1 хирургическое лечение 
        select  
            ru.evn_id,ru.evnusluga_id,
            1::integer as USL_TIP,
            OnkoSurgicalType.OnkoSurgicalType_Code::integer as HIR_TIP,
            null::integer as LEK_TIP_L,
            null::integer as LEK_TIP_V,
            null::integer as LUCH_TIP,
            null::integer as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoSurg EvnUslugaOnkoSurg on EvnUslugaOnkoSurg.EvnUslugaOnkoSurg_id = ru.evnusluga_id
         join OnkoSurgicalType OnkoSurgicalType   on EvnUslugaOnkoSurg.OnkoSurgicalType_id = OnkoSurgicalType.OnkoSurgicalType_id
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         
             
         union all
             
         --USL_TIP = 2 лек терапия через химиотерапевтическое лечение 
         select  
            ru.evn_id,ru.evnusluga_id,
            2 as USL_TIP,
            null as HIR_TIP,
            DrugTherapyLineType.DrugTherapyLineType_Code::integer as LEK_TIP_L,
            DrugTherapyLoopType.DrugTherapyLoopType_Code::integer as LEK_TIP_V,
            null as LUCH_TIP,
            case when exists (select 1 from MorbusOnkoDrug where MorbusOnkoDrug.evn_id = ru.evnusluga_id and MorbusOnkoDrug.morbusonkodrug_ispreventionvomiting = 2) then 1 else null end  as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoChem EvnUslugaOnkoChem on EvnUslugaOnkoChem.EvnUslugaOnkoChem_id = ru.evnusluga_id
         join DrugTherapyLineType on DrugTherapyLineType.DrugTherapyLineType_id = EvnUslugaOnkoChem.DrugTherapyLineType_id
         join DrugTherapyLoopType on DrugTherapyLoopType.DrugTherapyLoopType_id = EvnUslugaOnkoChem.DrugTherapyLoopType_id
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
             

         union all 
             
         --USL_TIP = 2 лек терапия через гормонотерапию
         select  
            ru.evn_id,ru.evnusluga_id,
            2 as USL_TIP,
            null as HIR_TIP,
            DrugTherapyLineType.DrugTherapyLineType_Code::integer as LEK_TIP_L,
            DrugTherapyLoopType.DrugTherapyLoopType_Code::integer as LEK_TIP_V,
            null as LUCH_TIP,
            case when exists (select 1 from MorbusOnkoDrug where MorbusOnkoDrug.evn_id = ru.evnusluga_id and MorbusOnkoDrug.morbusonkodrug_ispreventionvomiting = 2) then 1 else null end  as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoGormun EvnUslugaOnkoGormun on EvnUslugaOnkoGormun.EvnUslugaOnkoGormun_id = ru.evnusluga_id
         join DrugTherapyLineType on DrugTherapyLineType.DrugTherapyLineType_id = EvnUslugaOnkoGormun.DrugTherapyLineType_id
         join DrugTherapyLoopType on DrugTherapyLoopType.DrugTherapyLoopType_id = EvnUslugaOnkoGormun.DrugTherapyLoopType_id
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isdrug = 2 
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isbeam is distinct from 2 
             
        union all

        --USL_TIP = 3 лучевая терапия  
        select  
            ru.evn_id,ru.evnusluga_id,
            3 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            OnkoRadiotherapy.OnkoRadiotherapy_Code::integer as LUCH_TIP,
            null as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoBeam EvnUslugaOnkoBeam on EvnUslugaOnkoBeam.EvnUslugaOnkoBeam_id = ru.evnusluga_id
         join OnkoRadiotherapy OnkoRadiotherapy on EvnUslugaOnkoBeam.OnkoRadiotherapy_id = OnkoRadiotherapy.OnkoRadiotherapy_id
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
        
        union all
        
         --USL_TIP = 3 лучевая через гормунотерапию
         select  
            ru.evn_id,ru.evnusluga_id,
            3 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            OnkoRadiotherapy.OnkoRadiotherapy_Code::integer as LUCH_TIP,
            null as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoGormun EvnUslugaOnkoGormun on EvnUslugaOnkoGormun.EvnUslugaOnkoGormun_id = ru.evnusluga_id 
         join OnkoRadiotherapy OnkoRadiotherapy on EvnUslugaOnkoGormun.OnkoRadiotherapy_id = OnkoRadiotherapy.OnkoRadiotherapy_id
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isbeam = 2 
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isdrug is distinct from 2 
             
        union all 
        
        --USL_TIP = 4 химиолучева через гормунотерапию, если отмечены галки лучевой и лекарственной терапии
         select  
            ru.evn_id,ru.evnusluga_id,
            4 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            OnkoRadiotherapy.OnkoRadiotherapy_Code::integer as LUCH_TIP,
            case when exists (select 1 from MorbusOnkoDrug where MorbusOnkoDrug.evn_id = ru.evnusluga_id and MorbusOnkoDrug.morbusonkodrug_ispreventionvomiting = 2) then 1 else null end  as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoGormun EvnUslugaOnkoGormun on EvnUslugaOnkoGormun.EvnUslugaOnkoGormun_id = ru.evnusluga_id 
         join OnkoRadiotherapy OnkoRadiotherapy on EvnUslugaOnkoGormun.OnkoRadiotherapy_id = OnkoRadiotherapy.OnkoRadiotherapy_id         
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isbeam = 2 
         and EvnUslugaOnkoGormun.evnuslugaonkogormun_isdrug = 2 
         
		union all

        --USL_TIP = 4 химиолучевая через раздел "химиолучевая"
        select
        	ru.evn_id,ru.evnusluga_id,
            4 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            OnkoRadiotherapy.OnkoRadiotherapy_Code::integer as LUCH_TIP,
            case when exists (select 1 from MorbusOnkoDrug where MorbusOnkoDrug.evn_id = ru.evnusluga_id and MorbusOnkoDrug.morbusonkodrug_ispreventionvomiting = 2) then 1 else null end  as PPTR
        from r477.registryusluga ru 
         join v_EvnUslugaOnkoChemBeam ecb on ecb.evnuslugaonkochembeam_id = ru.evnusluga_id
         join OnkoRadiotherapy on ecb.onkoradiotherapy_id = OnkoRadiotherapy.onkoradiotherapy_id
        where
        	ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         
         union all  

        --USL_TIP = 5 неспецефическое   
        select  
            ru.evn_id,ru.evnusluga_id,
            5 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            null as LUCH_TIP,
            null as PPTR
        from r477.registryusluga ru 
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         and exists (select 1 from v_EvnUslugaOnkoNonSpec eon where ru.evnusluga_id = eon.EvnUslugaOnkoNonSpec_id)     
         
        union all 
        
        --USL_TIP = 6 диагностика 
        select  
            ru.evn_id,ru.evnusluga_id,
            6 as USL_TIP,
            null as HIR_TIP,
            null as LEK_TIP_L,
            null as LEK_TIP_V,
            null as LUCH_TIP,
            null as PPTR
        from r477.registryusluga ru 
        where 
         ru.registry_id = any(_registry_id_arr) and ru.evn_id = any(_evn_id_arr)
         and ru.region_data ->> 'evnclass_sysnick' !~* '^EvnUslugaOnko'
         and exists (
         	select 1 from uslugacomplexattribute uca 
             join v_uslugacomplexattributetype uct on uca.uslugacomplexattributetype_id = uct.uslugacomplexattributetype_id 
            where 
            	uca.uslugacomplex_id = ru.uslugacomplex_id and uct.uslugacomplexattributetype_sysnick = 'diagisl'
                and ru.registryusluga_setdate::date between coalesce(uca.uslugacomplexattribute_begdate::date,'-infinity'::date) and coalesce(uca.uslugacomplexattribute_enddate::date,'infinity'::date)
         )
          
      
    ); 
    
    
END;
$$;


ALTER FUNCTION r477.p_registry_exp_onk_usl(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_os_sluch(bigint); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_os_sluch(p_registry_id bigint) RETURNS TABLE(evn_id bigint, maxevn_id bigint, "OS_SLUCH" integer)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    BEGIN
        
return query (
	
	select
        rd.evn_id,
        rd.evn_id as maxevn_id,
        1::integer as OS_SLUCH 
    from 
        r477.registrydata rd
		left join lateral ( select re.evn_id
			from r477.registryerror re
			where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
			limit 1
			) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr) 
        --and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
        and rd.region_data -> 'deputy' is not null
        and exists (select 1 from v_PersonChild pc where pc.person_id = rd.person_id and coalesce(pc.personchild_countchild,0) > 0) 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
        
    union all 

    select
        rd.evn_id,
        rd.evn_id as maxevn_id,
        2::integer as OS_SLUCH 
    from 
        r477.registrydata rd 
		left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	        
    where 
        rd.registry_id = any(_registry_id_arr)  
        --and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
        and coalesce(nullif(rd.region_data -> 'deputy' ->> 'secname',''),nullif(rd.region_data -> 'person' ->> 'secname','')) is null 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
    
);
	END;
$$;


ALTER FUNCTION r477.p_registry_exp_os_sluch(p_registry_id bigint) OWNER TO developer_rep;

--
-- Name: p_registry_exp_pac(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_pac(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(person_id bigint, "ID_PAC" text, "FAM" text, "IM" text, "OT" text, "W" text, "DR" text, "TEL" text, "FAM_P" text, "IM_P" text, "OT_P" text, "W_P" text, "DR_P" text, "MR" text, "DOCTYPE" text, "DOCSER" text, "DOCNUM" text, "DOCDATE" text, "DOCORG" text, "SNILS" text, "OKATOG" text, "OKATOP" text, "COMENTP" text)
    LANGUAGE plpgsql
    AS $_$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
    BEGIN
return query (
	
    select distinct 
    	t.person_id,
        t.ID_PAC,    
        t.FAM,
        t.IM,
        t.OT,
        t.W,
        t.DR,
        t.TEL,
        t.FAM_P,
        t.IM_P,
        t.OT_P,
        t.W_P,
        t.DR_P,
        t.MR,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCTYPE
        end as DOCTYPE,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCSER
        end as DOCSER,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCNUM
        end as DOCNUM,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCDATE
        end as DOCDATE,
        case 
        	when t.vpolis = '3' and t.DOCNUM is not null and (t.DOCSER is null or t.DOCDATE is null or t.DOCORG is null) then null   
            else t.DOCORG
        end as DOCORG,
        t.SNILS,
        (array_agg(t.OKATOG))[1] as OKATOG,
        (array_agg(t.OKATOP))[1] as OKATOP,
        NULL as COMENTP
    from (
        select 
            rd.person_id,
            rd.person_id::text as ID_PAC,    
            UPPER(case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'surname' else null end) as FAM,
            UPPER(case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'firname' else null end) as IM,
            UPPER(case when rd.region_data -> 'deputy' is null then rd.region_data -> 'person' ->> 'secname' else null end) as OT,
            coalesce(rd.region_data -> 'person' ->> 'sex_id','1')::text as W,
            to_char((rd.region_data -> 'person' ->> 'birthday')::date,'YYYY-MM-DD') as DR,
            null::text as TEL,
            UPPER(rd.region_data -> 'deputy' ->> 'surname') as FAM_P,
            UPPER(rd.region_data -> 'deputy' ->> 'firname') as IM_P,
            UPPER(rd.region_data -> 'deputy' ->> 'secname') as OT_P,
            case when rd.region_data -> 'deputy' is not null then coalesce(rd.region_data -> 'deputy' ->> 'sex_id','1') else null end as W_P,
            to_char((rd.region_data -> 'deputy' ->> 'birthday')::date,'YYYY-MM-DD') as DR_P,
            left(Address.address_address,100) as MR,
            doct.documenttype_code::text AS DOCTYPE,
            case 
                when nullif(trim(doc.document_ser),'') is not null then 
                    case doct.documenttype_code
                        when '14' then regexp_replace(trim(doc.document_ser), '(^[0-9]{2})([0-9]{2}$)', '\1 \2')
                        when '3' then regexp_replace(trim(doc.document_ser), '(^[IVXLCDM]{1,3})([А-Я]{2}$)', '\1-\2')
                        else trim(doc.document_ser) 
                    end 
                else null 
            end as DOCSER,
            nullif(trim(doc.document_num),'') as DOCNUM,
            to_char(doc.document_begdate,'YYYY-MM-DD') as DOCDATE,
            nullif(trim(org.org_nick),'') as DOCORG,
            regexp_replace(
                coalesce(rd.region_data -> 'deputy' ->> 'snils',rd.region_data -> 'person' ->> 'snils'),
                '(...)(...)(...)(..)','\1-\2-\3 \4'
            ) as SNILS,
            kladrU.kladr_ocatd as OKATOG,
            kladrP.kladr_ocatd as OKATOP,
            null::text as COMENTP,
            rd.region_data -> 'polis' ->> 'vpolis' as vpolis
        from r477.registry r 
         join r477.registrydata rd on rd.registry_id = r.registry_id
           
         left join lateral (
            select pb.address_id from PersonBirthPlace pb 
            where pb.person_id = coalesce((rd.region_data -> 'deputy' ->> 'person_id')::bigint,rd.person_id) 
            limit 1
         ) as pb on true 
         left join Address on pb.address_id = Address.address_id
           
         left join dbo.Document doc on doc.document_id = coalesce(rd.region_data -> 'deputy' ->> 'document_id',rd.region_data -> 'person' ->> 'document_id')::bigint  
         left join DocumentType doct on doc.documenttype_id = doct.documenttype_id 
         left join OrgDep on OrgDep.orgdep_id = doc.orgdep_id 
         left join Org on Org.org_id = OrgDep.org_id
           
         left join v_address_kladr kladrU on kladrU.address_id = coalesce(rd.region_data -> 'deputy' ->> 'uaddress_id',rd.region_data -> 'person' ->> 'uaddress_id')::bigint 
         left join v_address_kladr kladrP on kladrP.address_id = coalesce(rd.region_data -> 'deputy' ->> 'paddress_id',rd.region_data -> 'person' ->> 'paddress_id')::bigint  
         left join lateral ( select re.evn_id
									from r477.registryerror re
									where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
									limit 1
									) r_err on true  
        where 
            r.registry_id = any(_registry_id_arr)
            and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
            and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
            and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
    )t
    group by 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20
);
	END;
$_$;


ALTER FUNCTION r477.p_registry_exp_pac(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_pac_zglv(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_pac_zglv(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(registry_id bigint, "VERSION" text, "DATA" text, "FILENAME" text, "FILENAME1" text)
    LANGUAGE plpgsql
    AS $$
DECLARE
	_registry_type_code text = r477.p_registry_get_registry_type_code(p_registry_id);
    _export_code text; 
BEGIN

_export_code = 
	case _registry_type_code 
    	when 'omspol' 		then 'A'
        when 'omsstac' 		then 'H'
        when 'resemdent'	then 'I' 
        when 'htm' 			then 'T'  
        when 'pdn' 			then 'P'      
        else 'H' 
    end
;

return query (
 select
    p_registry_id as registry_id,
    '3.2'::text as VERSION,
    to_char(current_date,'YYYY-MM-DD') as DATA,
    'L'||t.filename as FILENAME,
    t.filename as FILENAME1
 from (
    select 
    	concat(
          _export_code,case when p_iszno = 1 then 'C' else '' end,'M',Lpu.lpu_f003mcod,
          case when KatNasel.katnasel_sysnick = 'oblast' then 'S' else 'T' end,
          case when KatNasel.katnasel_sysnick = 'oblast' then OrgSMO.orgsmo_f002smocod else '01' end,
          '_',to_char(r.registry_enddate,'YY'),to_char(r.registry_enddate,'MM')
    	) as filename
    from r477.Registry r  
     join Lpu on Lpu.Lpu_id = r.Lpu_id
     left join OrgSMO on OrgSMO.OrgSMO_id = r.OrgSmo_id
     left join KatNasel on r.katnasel_id = KatNasel.katnasel_id  
    where 
        r.Registry_id = p_Registry_id
 )t
);
END;
$$;


ALTER FUNCTION r477.p_registry_exp_pac_zglv(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_sl(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_sl(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(registry_id bigint, evn_id bigint, maxevn_id bigint, person_id bigint, "SL_ID" text, "VID_HMP" text, "METOD_HMP" integer, "LPU_1" text, "PODR" text, "PROFIL" integer, "PROFIL_K" integer, "DET" integer, "TAL_D" text, "TAL_NUM" text, "TAL_P" text, "P_CEL" text, "NHISTORY" text, "P_PER" integer, "DATE_1" text, "DATE_2" text, "KD" integer, "DS0" text, "DS1" text, "C_ZAB" integer, "DS_ONK" integer, "DN" integer, "CODE_MES1" text, "CODE_MES2" text, "REAB" integer, "PRVS" integer, "VERS_SPEC" text, "IDDOKT" text, "ED_COL" numeric, "TARIF" numeric, "SUM_M" numeric, "P_IDCASE" bigint, "COMENTSL" text, "N_KSG" text, "VER_KSG" integer, "KSG_PG" integer, "N_KPG" integer, "KOEF_Z" numeric, "KOEF_UP" numeric, "BZTSZ" numeric, "KOEF_D" numeric, "KOEF_U" numeric, "SL_K" integer, "IT_SL" numeric)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);
        _lpu_code 			text;
	BEGIN

	_lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);

return query (

	select
        rd.registry_id,
        rd.evn_id,
        rd.evn_id as maxevn_id,
        rd.person_id,
        --'1'::text as SL_ID,
        rd.evn_id::text as SL_ID,
        rd.region_data ->> 'vid_hmp' as VID_HMP,
        (rd.region_data ->> 'metod_hmp')::integer as METOD_HMP,
        coalesce((rd.region_data -> 'tariff_info' ->> 'lpu_1'), nullif(rd.lpusection_code,''),nullif(LpuBuilding.lpubuilding_code,''), _lpu_code) as LPU_1,
        case
        	when rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' then rd.region_data -> 'tariff_info' ->> 'podr'
        	when rd.region_data ->> 'item_type' ~ '^priem' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when rd.region_data ->> 'item_type' = 'dializ' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when rd.region_data ->> 'item_type' ~ 'stomat' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when rd.region_data ->> 'item_type' ~ '^isl' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
            else null
        end::text as PODR,
        coalesce(flsp.lpusectionprofile_code,lsp.lpusectionprofile_code::integer) as PROFIL,
        LSPB.LpuSectionBedProfile_Code::integer as PROFIL_K,
        case when (rd.region_data -> 'person' ->> 'age')::integer >= 18 then 0 else 1 end as DET,
        rd.region_data ->> 'tal_d' as TAL_D,
        rd.region_data ->> 'tal_num' as TAL_NUM,
        rd.region_data ->> 'tal_p' as TAL_P,
        case rd.region_data ->> 'evnclass_sysnick'
            when 'EvnSection' then null
            else
                case
                    when rd.region_data ->> 'item_type' ~ 'priem_obr' then '3.0'
                    when rd.region_data ->> 'item_type' ~ 'priem_prof' then '1.0'
                    when rd.region_data ->> 'evnclass_sysnick' = 'EvnUslugaPar' then
                    	case when left(Diag.diag_code,1) = 'Z' then '2.6' else '1.0' end
                    else
                    	case
                        	when rd.region_data ->> 'treatment_class_code' = '1' then 
                        		case when (rd.region_data ->> 'vizit_count')::integer = 1 then '1.0' else '3.0' end
                            else rd.region_data ->> 'treatment_class_code'
                        end
                end
        end as P_CEL,
        rd.numcard::text AS NHISTORY,
        (rd.region_data ->> 'p_per')::integer as P_PER,
        to_char(rd.evn_setdate::date,'YYYY-MM-DD') as DATE_1,
        to_char(rd.evn_disdate::date,'YYYY-MM-DD') as DATE_2,
        case when rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' then rd.registrydata_kdpay::integer else null end as KD,
        diag_p.diag_scode::text as DS0,
        (case when char_length(Diag.diag_scode)=4 then left(Diag.diag_scode,3) else
        Diag.diag_scode end)::text as DS1,
        case
            when left(Diag.diag_code,1) = 'Z' then null
            else rd.region_data ->> 'c_zab'
        end::integer as C_ZAB,
        case
        	when p_iszno = 1 or rd.region_data ->> 'item_type' IN ('htm', 'stac') then

                coalesce(rd.region_data ->> 'ds_onk','0')::integer
            else null
        end as DS_ONK,
        case
            when rd.region_data ->> 'treatment_class_code' is distinct from '1.3' then null
            when disp.persondisp_id is null then null
            else
                case
                    when disp.persondisp_begdate::date < rd.evn_setdate::date and disp.persondisp_enddate is null then 1
                    when disp.persondisp_begdate::date <@ daterange(rd.evn_setdate::date,rd.evn_disdate::date,'[]') then 2
                    when disp.persondisp_enddate is not null then case disp.dispouttype_id when 1 then 4 else 6 end
                    else null
                end
        end as DN,
        rd.region_data ->> 'tariff_code' as CODE_MES1,
        null::text as CODE_MES2,
        case
        	when VizitType.vizittype_sysnick = 'rehab' then 1
            when rd.region_data ->> 'item_type' = 'stac' and coalesce(flsp.lpusectionprofile_code,lsp.lpusectionprofile_code::integer) = 158 then 1
            else null
        end as REAB,
        ms.medspecclass_code::integer as PRVS,
        'V021'::text as VERS_SPEC,
        --regexp_replace(rd.medpersonal_snils,'(...)(...)(...)(..)','\1-\2-\3 \4') as IDDOKT,
        rd.region_data ->> 'medpersonal_fio' as IDDOKT,
        case
			when rd.region_data ->> 'item_type' = 'stac' then 1
        	when rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' then rd.registrydata_kdpay::numeric
            when rd.region_data ->> 'ed_col' is null and rd.region_data ->> 'item_type' ~ '^isl' then
            	(select count(*) from r477.registryusluga ru where ru.registry_id = rd.registry_id and rd.evn_id = ru.evn_id)::numeric
            else (rd.region_data ->> 'ed_col')::numeric
        end as ED_COL,
        case 
	        when rd.region_data ->> 'item_type' IN ('stac', 'htm') then (rd.region_data -> 'tariff_info' ->> 'price')::NUMERIC 
        	--when rd.region_data ->> 'item_type' = 'stac' and rd.lpuunittype_id = 1 then rd.registrydata_tariff
            when rd.registrydata_iszno = 1 then rd.registrydata_tariff
            when rd.region_data ->> 'item_type' !~ '^isl' then rd.registrydata_tariff
            when rd.region_data ->> 'item_type' ~ '^isl' and rd.region_data ->> 'tariff_code'<>'000541' then rd.registrydata_tariff
            else 0
        end::numeric as TARIF, 
        rd.registrydata_itogsum::numeric as SUM_M,
        case when rd.region_data ->> 'item_type' ~ '^isl' then (rd.region_data ->> 'p_idcase')::bigint else null end as P_IDCASE,
        null::text as COMENTSL,

        ----------------------KSG_KPG-----------------------
        --case when rd.region_data ->> 'item_type' = 'stac' then rd.region_data ->> 'n_ksg' else null end::text as N_KSG,
        rd.region_data -> 'csg_info' ->> 'n_ksg' AS N_KSG,
        --case when rd.region_data ->> 'item_type' = 'stac' then date_part('year',rd.evn_disdate::date) else null end::integer as VER_KSG,
        (rd.region_data -> 'csg_info' ->> 'ver_ksg')::integer AS VER_KSG,
        --case when rd.region_data ->> 'item_type' = 'stac' then
        --	case when array_length(string_to_array(rd.region_data ->> 'n_ksg','.'),1) > 2 then 1 else 0 end
        --    else null
        --end::integer as KSG_PG,
        --case when rd.region_data ->> 'item_type' = 'stac' then 0 else null end as KSG_PG,
        (rd.region_data -> 'csg_info' ->> 'ksg_pg')::integer AS KSG_PG,
        --null::integer as N_KPG,
        (rd.region_data -> 'csg_info' ->> 'n_kpg')::integer AS N_KPG,
        --case when rd.region_data ->> 'item_type' = 'stac' then rd.mestariff_value else null end::numeric(7,5) as KOEF_Z,
        (rd.region_data -> 'csg_info' ->> 'koef_z')::numeric as KOEF_Z,
        --case when rd.region_data ->> 'item_type' = 'stac' then moc.mesoldcoeff_coeff else null end::numeric(7,5) as KOEF_UP,
        (rd.region_data -> 'csg_info' ->> 'koef_up')::numeric as KOEF_UP,
        --case when rd.region_data ->> 'item_type' = 'stac' then tbst.bztsz else null end::numeric as BZTSZ,
        (rd.region_data -> 'csg_info' ->> 'bztsz')::numeric as BZTSZ,
        --case when rd.region_data ->> 'item_type' = 'stac' then 1 else null end::numeric(7,5) as KOEF_D,
        (rd.region_data -> 'csg_info' ->> 'koef_d')::numeric as KOEF_D,

        (rd.region_data -> 'csg_info' ->> 'koef_u')::numeric AS KOEF_U,

        (rd.region_data -> 'csg_info' ->> 'sl_k')::integer AS SL_K,

        (rd.region_data -> 'csg_info' ->> 'it_sl')::numeric AS IT_SL
    from
        r477.registrydata rd
         left join LpuSection on LpuSection.lpusection_id = rd.lpusection_id
         left join LpuUnit on LpuSection.lpuunit_id = LpuUnit.lpuunit_id
         left join LpuBuilding on LpuUnit.lpubuilding_id = LpuBuilding.lpubuilding_id
         left join LpuSectionProfile lsp on rd.lpusectionprofile_id = lsp.lpusectionprofile_id
         left join fed.LpuSectionProfile flsp on lsp.lpusectionprofile_fedid = flsp.lpusectionprofile_id
         left join Diag on Diag.diag_id = rd.diag_id
         left join VizitType on VizitType.vizittype_id = rd.vizittype_id
         left join fed.MedSpecClass ms on ms.medspecclass_id = rd.medspec_id

         left join fed.LpuSectionBedProfileLink LSBPLink on LSBPLink.LpuSectionBedProfileLink_id = (rd.region_data ->> 'bed_profile_link_id')::BIGINT
		 left join fed.LpuSectionBedProfile LSPB on LSPB.LpuSectionBedProfile_id=LSBPLink.LpuSectionBedProfile_fedid

         left join Diag diag_p on diag_p.diag_id = (rd.region_data ->> 'diag_pid')::integer

         left join lateral (
            --д-учет
            select
                PersonDisp_id,
                PersonDisp_begDate,
                PersonDisp_endDate,
                DispOutType_id
            from v_persondisp PersonDisp
            where
                rd.person_id = PersonDisp.person_id and PersonDisp.diag_id = Diag.diag_id
            order by persondisp_begdate desc
            limit 1
        ) disp on true


        --left join MesOld on MesOld.mes_id = rd.mesitog_id
        --left join lateral (select moc.mesoldcoeff_coeff from MesOldCoeff moc where moc.mes_id = rd.mesitog_id and rd.evn_disdate::date <@ daterange(moc.mesoldcoeff_begdt::date,moc.mesoldcoeff_enddt::date,'[]') limit 1) as moc on true

		left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where
        rd.registry_id = any(_registry_id_arr)
        and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
    	and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
    	and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
    order by rd.evn_id
);
	END;
$$;


ALTER FUNCTION r477.p_registry_exp_sl(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_usl(bigint, integer); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_usl(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, "IDSERV" text, "LPU_USL" text, "LPU_1_USL" text, "PODR_USL" text, "PROFIL_USL" integer, "VID_VME" text, "DET_USL" integer, "DATE_IN" text, "DATE_OUT" text, "DS" text, "CODE_USL" text, "KOL_USL" numeric, "TARIF_USL" numeric, "SUMV_USL" numeric, "PRVS_USL" integer, "CODE_MD" text, "NPL" integer, "COMENTU" text)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);
        _lpu_code 			text;
	BEGIN

_lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);

return query (

	select
        ru.evn_id,
        ru.evnusluga_id::text as IDSERV,
        _lpu_code as LPU_USL,
        coalesce(nullif(rd.lpusection_code,''),nullif(LpuBuilding.lpubuilding_code,''),_lpu_code) as LPU_1_USL,
        case evn.evnclass_sysnick
            when 'EvnSection' then coalesce(rd.region_data ->> 'podr',rd.lpusection_code)
            else null
        end::text as PODR_USL,
        coalesce(flsp.lpusectionprofile_code,lsp.lpusectionprofile_code::integer) as PROFIL_USL,
        case
            when rd.region_data ->> 'item_type' = 'htm' then rd.region_data ->> 'metod_hmp'
            when rd.registrydata_iszno = 1 or rd.region_data ->> 'item_type' = 'priem_prof' or rd.region_data ->> 'item_type' ~ '^isl' then
                 	coalesce(ru.region_data ->> 'vid_vme',ru.registryusluga_codeusl)::text
            else null
        end::text as VID_VME,
        case when (rd.region_data -> 'person' ->> 'age')::integer >= 18 then 0 else 1 end as DET_USL,
        to_char(coalesce(ru.registryusluga_setdate,rd.evn_setdate),'YYYY-MM-DD') as DATE_IN,
        to_char(coalesce(ru.registryusluga_setdate,rd.evn_setdate),'YYYY-MM-DD') as DATE_OUT,
        Diag.diag_scode::text as DS,
        ru.registryusluga_codeusl::text as CODE_USL,
        CASE 
        	WHEN rd.region_data ->> 'item_type' IN ('stomat', 'stomat_neotl') THEN coalesce(ru.registryusluga_kol * UET.uet,1)::numeric 
            ELSE coalesce(nullif(ru.registryusluga_kol,0),1)::numeric 
        END as KOL_USL,
        case
            when rd.region_data ->> 'item_type' ~ '^isl' then coalesce(ru.registryusluga_tariff,0)
            else null
        end::numeric as TARIF_USL,
        case
            when rd.region_data ->> 'item_type' ~ '^isl' then coalesce(ru.registryusluga_sum,0)
            else 0
        end::numeric as SUMV_USL,
        coalesce(mcs.medspecclass_code,case when ru.region_data ->> 'evnclass_sysnick' ~ '^EvnUslugaOnko' then ms.medspecclass_code else null end)::integer as PRVS_USL,
        regexp_replace(
        	coalesce(MedPersonal.Person_Snils,case when ru.region_data ->> 'evnclass_sysnick' ~ '^EvnUslugaOnko' then rd.medpersonal_snils else null end),
            '(...)(...)(...)(..)','\1-\2-\3 \4'
        ) as CODE_MD,
        null::integer as NPL,
        null::text as COMENTU
    from r477.registrydata rd
     join r477.registryusluga ru on rd.registry_id = ru.registry_id and rd.evn_id = ru.evn_id
     join v_Evn evn on rd.evn_id = Evn.evn_id
     left join LpuSection on LpuSection.lpusection_id = rd.lpusection_id
     left join LpuUnit on LpuSection.lpuunit_id = LpuUnit.lpuunit_id
     left join LpuBuilding on LpuUnit.lpubuilding_id = LpuBuilding.lpubuilding_id
     left join LpuSectionProfile lsp on rd.lpusectionprofile_id = lsp.lpusectionprofile_id
     left join fed.LpuSectionProfile flsp on lsp.lpusectionprofile_fedid = flsp.lpusectionprofile_id
     left join Diag on Diag.diag_id = coalesce(ru.diag_id,rd.diag_id)
     left join v_MedStaffFact msf on msf.MedStaffFact_id = ru.medstafffact_id
     left join v_MedPersonal MedPersonal on MedPersonal.MedPersonal_id = msf.MedPersonal_id and MedPersonal.lpu_id = evn.lpu_id
     left join MedSpecOms on MedSpecOms.MedSpecOms_id = msf.MedSpecOms_id
     left join fed.MedSpecClass mcs on MedSpecOms.MedSpecClass_id = mcs.MedSpecClass_id
	 left join fed.MedSpecClass ms on ms.medspecclass_id = rd.medspec_id

     left join lateral (
			select
			COALESCE(pl.evnuslugastom_ued, 1) as uet
		from v_evnuslugastom pl
		where
			pl.evnuslugastom_id = ru.evnusluga_id
			and rd.region_data ->> 'item_type' in ('stomat','stomat_neotl')

		) as UET on true

    where
        rd.registry_id = any(_registry_id_arr)
        and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
        and nullif(ru.registryusluga_codeusl,'') is not null
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        
);
	END;
$$;


ALTER FUNCTION r477.p_registry_exp_usl(p_registry_id bigint, p_iszno integer) OWNER TO developer_rep;

--
-- Name: p_registry_exp_usl_dev(bigint, jsonb); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registry_exp_usl_dev(p_registry_id bigint, p_param jsonb DEFAULT '{}'::jsonb) RETURNS TABLE(evn_id bigint, "IDSERV" text, "LPU_USL" text, "LPU_1_USL" text, "PODR_USL" text, "PROFIL_USL" integer, "VID_VME" text, "DET_USL" integer, "DATE_IN" text, "DATE_OUT" text, "DS" text, "CODE_USL" text, "KOL_USL" numeric, "TARIF_USL" numeric, "SUMV_USL" numeric, "PRVS_USL" integer, "CODE_MD" text, "NPL" integer, "COMENTU" text)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);
        _lpu_code 			text;
		p_iszno integer := (p_param ->> 'p_iszno')::integer;
		_itype text := p_param ->> 'type';
	BEGIN

_lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);

return query (

	select
        ru.evn_id,
        case when _itype = 'priem_obr' then rd.evn_id else ru.evnusluga_id end::text as IDSERV,
        _lpu_code as LPU_USL,
        coalesce((rd.region_data -> 'tariff_info' ->> 'lpu_1'), nullif(rd.lpusection_code,''),nullif(LpuBuilding.lpubuilding_code,''),_lpu_code) as LPU_1_USL,
        case 
        	when _itype = 'stom' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when _itype in ('parusl','mucalc') then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when _itype ~ 'dial' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when _itype ~ 'priem' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        	when _itype ~ 'stom' then rd.region_data ->> 'tariff_code' -- временно, потом сохранять это в Podr 
        else
        	case evn.evnclass_sysnick
           		when 'EvnSection' then coalesce((rd.region_data -> 'tariff_info' ->> 'podr'),rd.lpusection_code)
            	else null
        	end 
        end::text as PODR_USL,
        coalesce(flsp.lpusectionprofile_code,lsp.lpusectionprofile_code::integer) as PROFIL_USL,
        case
            when rd.region_data ->> 'item_type' = 'htm' and rd.registrydata_iszno = 1 then rd.region_data ->> 'metod_hmp'
            when rd.registrydata_iszno = 1 or rd.region_data ->> 'item_type' ~ 'priem_prof' or rd.region_data ->> 'item_type' ~ '^isl' then
                 	coalesce(ru.region_data ->> 'vid_vme',ru.registryusluga_codeusl)::text
            else null
        end::text as VID_VME,
        case when (rd.region_data -> 'person' ->> 'age')::integer >= 18 then 0 else 1 end as DET_USL,
        to_char(coalesce(ru.registryusluga_setdate,rd.evn_setdate),'YYYY-MM-DD') as DATE_IN,
        to_char(coalesce(ru.registryusluga_setdate,rd.evn_setdate),'YYYY-MM-DD') as DATE_OUT,
        Diag.diag_scode::text as DS,
        coalesce(
        	case 
        		when _itype = 'priem_obr' then rd.region_data ->> 'code_usl'
        		when _itype ~ 'priem' then ru.region_data ->> 'code_usl'
        		when _itype = 'dial_t' then rd.region_data ->> 'code_usl'
        		when _itype in ('parusl','mucalc') then rd.region_data ->> 'code_usl'
        		when _itype = 'stom_t' then rd.region_data ->> 'code_usl'
        		else null 
        	end, 
        	ru.registryusluga_codeusl::text
        	) as CODE_USL,
        CASE 
        	--WHEN rd.region_data ->> 'item_type' IN ('stomat', 'stomat_neotl') THEN coalesce(ru.registryusluga_kol * UET.uet,1)::numeric 
        	WHEN rd.region_data ->> 'item_type' IN ('stomat', 'stomat_neotl') THEN coalesce(nullif(ru.registryusluga_kol,0),1)::numeric
            ELSE coalesce(nullif(ru.registryusluga_kol,0),1)::numeric 
        END as KOL_USL,
        case
            when rd.region_data ->> 'item_type' ~ '^isl' then coalesce(ru.registryusluga_tariff,0)
            when rd.region_data ->> 'item_type' = 'htm' then 0
            when (ru.region_data ->> 'is_dializ')::BOOLEAN then coalesce(ru.registryusluga_tariff,0)
            when rd.region_data ->> 'item_type' = 'stac' then 0
            when _itype ~ '^priem' then 
            	case when rd.region_data ->> 'item_type' ~ '^priem_prof' or _itype = 'priem_obr' then coalesce(ru.registryusluga_tariff,0) else 0 end
            when _itype ~ 'dial' then 
            	case when _itype = 'dial_u' then coalesce(ru.registryusluga_tariff,0) else 0 end
            else null
        end::numeric as TARIF_USL,
        case
            when rd.region_data ->> 'item_type' ~ '^isl' then coalesce(ru.registryusluga_sum,0)
            when (ru.region_data ->> 'is_dializ')::BOOLEAN then coalesce(ru.registryusluga_tariff,0)
            when _itype ~ '^priem' then 
            	case when rd.region_data ->> 'item_type' ~ '^priem_prof' or _itype = 'priem_obr' then coalesce(ru.registryusluga_sum,0) else 0 end
            when _itype ~ 'dial' then 
            	case when _itype = 'dial_u' then coalesce(ru.registryusluga_sum,0) else 0 end
            WHEN rd.region_data ->> 'item_type' IN ('stomat', 'stomat_neotl') then null 
            else 0
        end::numeric as SUMV_USL,
        coalesce(mcs.medspecclass_code,case when ru.region_data ->> 'evnclass_sysnick' ~ '^EvnUslugaOnko' then ms.medspecclass_code else null end)::integer as PRVS_USL,
        --regexp_replace(
        --	coalesce(MedPersonal.Person_Snils,case when ru.region_data ->> 'evnclass_sysnick' ~ '^EvnUslugaOnko' then rd.medpersonal_snils else null end),
        --    '(...)(...)(...)(..)','\1-\2-\3 \4'
        --) as CODE_MD,
        rd.region_data ->> 'medpersonal_fio' AS CODE_MD,
        null::integer as NPL,
        null::text as COMENTU
    from r477.registrydata rd
     join r477.registryusluga ru on rd.registry_id = ru.registry_id and rd.evn_id = ru.evn_id
     join v_Evn evn on rd.evn_id = Evn.evn_id
     left join LpuSection on LpuSection.lpusection_id = rd.lpusection_id
     left join LpuUnit on LpuSection.lpuunit_id = LpuUnit.lpuunit_id
     left join LpuBuilding on LpuUnit.lpubuilding_id = LpuBuilding.lpubuilding_id
     left join LpuSectionProfile lsp on rd.lpusectionprofile_id = lsp.lpusectionprofile_id
     left join fed.LpuSectionProfile flsp on lsp.lpusectionprofile_fedid = flsp.lpusectionprofile_id
     left join Diag on Diag.diag_id = coalesce(ru.diag_id,rd.diag_id)
     left join v_MedStaffFact msf on msf.MedStaffFact_id = ru.medstafffact_id
     left join v_MedPersonal MedPersonal on MedPersonal.MedPersonal_id = msf.MedPersonal_id and MedPersonal.lpu_id = evn.lpu_id
     left join MedSpecOms on MedSpecOms.MedSpecOms_id = msf.MedSpecOms_id
     left join fed.MedSpecClass mcs on MedSpecOms.MedSpecClass_id = mcs.MedSpecClass_id
	 left join fed.MedSpecClass ms on ms.medspecclass_id = rd.medspec_id

     left join lateral (
			select
			COALESCE(pl.evnuslugastom_ued, 1) as uet
		from v_evnuslugastom pl
		where
			pl.evnuslugastom_id = ru.evnusluga_id
			and rd.region_data ->> 'item_type' in ('stomat','stomat_neotl')

		) as UET on true
	left join lateral ( select re.evn_id
				from r477.registryerror re
				where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
				limit 1
				) r_err on true	
    where
        rd.registry_id = any(_registry_id_arr)
        and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end
        and nullif(ru.registryusluga_codeusl,'') is not null
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаенными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
        and 
     		case 
     			when _itype ~ 'priem' then rd.region_data ->> 'item_type' ~ '^priem' and (ru.region_data ->> 'is_vizitcode')::BOOLEAN
     				and case when _itype = 'priem_obr' then rd.region_data ->> 'item_type' ~ '^priem_obr' and (ru.region_data ->> 'is_last')::BOOLEAN else true end
     			when _itype ~ 'dial' then rd.region_data ->> 'item_type' = 'dializ' and
     				case 
     					when _itype = 'dial_u' then not (ru.region_data ->> 'is_vizitcode')::BOOLEAN
     					when _itype = 'dial_t' then (ru.region_data ->> 'is_vizitcode')::BOOLEAN and (ru.region_data ->> 'is_last')::BOOLEAN 
     					else true 
     				end
     			when _itype ~ 'stom' then rd.region_data ->> 'item_type' ~ 'stomat' and 
     				case 
     					when _itype = 'stom_u' then not (ru.region_data ->> 'is_vizitcode')::BOOLEAN
     					when _itype = 'stom_t' then (ru.region_data ->> 'is_vizitcode')::BOOLEAN
     					else true 
     				end
     			when _itype in ('parusl','mucalc') then rd.region_data ->> 'item_type' ~ '^isl'
				else true 
			end
);
	END;
$$;


ALTER FUNCTION r477.p_registry_exp_usl_dev(p_registry_id bigint, p_param jsonb) OWNER TO developer_rep;

--
