CREATE OR REPLACE FUNCTION rpt1.han_evnps_pg (p_evnps_id BIGINT) RETURNS TABLE (
"Pric_lpu" CHARACTER VARYING,
"Org_OKPO" CHARACTER VARYING,
"Lpu_Name" CHARACTER VARYING,
"addressLpu" TEXT,
"EvnPS_NumCard" CHARACTER VARYING,
"EvnPS_setDT" TEXT,
"EvnPS_disDT" TEXT,
"LpuSection_Name" CHARACTER VARYING,
"LpuSectionWard_Name" CHARACTER VARYING,
"Lsection_name" CHARACTER VARYING,
koikodni INTEGER,
"PrehospArrive_Name" CHARACTER VARYING,
"BloodGroupType_Name" CHARACTER VARYING,
"RhFactorType_Name" TEXT,
"PersonAllergicReaction_Kind" TEXT,
fio TEXT,
sex_name CHARACTER VARYING,
age TEXT,
age_year INTEGER,
age_month INTEGER,
age_day INTEGER,
"BirthDay" TEXT,
citizenship CHARACTER VARYING,
person_doc TEXT,
"Document_Ser" CHARACTER VARYING,
"Document_Num" CHARACTER VARYING,
polis TEXT,
"Polis_Ser" CHARACTER VARYING,
"Polis_Num" CHARACTER VARYING,
"OrgSmo_Name" CHARACTER VARYING,
polis_begdate TEXT,
"Person_Snils" CHARACTER VARYING,
"Address_Address" CHARACTER VARYING,
"KLAreaType_id" INTEGER,
"Uaddress" CHARACTER VARYING,
"Org_Name" CHARACTER VARYING,
"Post_Name" CHARACTER VARYING,
"SocStatus_Name" CHARACTER VARYING,
"NameDir" CHARACTER VARYING,
extr TEXT,
"EvnPS_TimeDesease" DOUBLE PRECISION,
"Okei" CHARACTER VARYING,
pl CHARACTER VARYING,
diagdir_name CHARACTER VARYING,
diagpriem_name CHARACTER VARYING,
"EvnPS_setDate" CHARACTER VARYING,
diag_name CHARACTER VARYING,
"EvnSection_setDate" CHARACTER VARYING,
"LeaveType_Name" CHARACTER VARYING,
"anotherMO" CHARACTER VARYING,
"ResultDesease_Name" CHARACTER VARYING,
"Diag_Code" CHARACTER VARYING,
"Mes_Code" CHARACTER VARYING,
"EvnPS_PhaseDescr_pid" CHARACTER VARYING,
"EvnPS_PhaseDescr_did" CHARACTER VARYING,
"Person_Phone" CHARACTER VARYING,
foreigner INTEGER,
"VrachFio" TEXT,
"ZavOtdel" TEXT,
"EvnPS_HospCount" INTEGER,
"mainAnatDiag" TEXT,
"aggMainDiag" TEXT,
"concomDiag" TEXT,
"Davlenie" TEXT,
"RepositoryObserv_TemperatureFrom" TEXT,
"RepositoryObserv_Height" TEXT,
"RepositoryObserv_Weight" TEXT,
"FluorographyYear" TEXT,
"Sanitation" TEXT,
"isPediculos" TEXT,
"isScabies" TEXT,
"PrehospTrauma_id" INTEGER,
allergic_setdt TEXT,
allergicreactiontype_name TEXT,
allergicreaction_kind TEXT,
"allergicReactionLevel_name:" TEXT,
personmedhistory_descr TEXT,
"PrivilegeType_id" INTEGER,
privilegetype_begdate TEXT,
privilegetype_enddate TEXT)
LANGUAGE PLPGSQL AS $plpgsql$
BEGIN

RETURN QUERY
--73002283426848
--73002388031616

SELECT
  COALESCE(ll.Lpu_Nick, ll.Lpu_Name) AS Pric_lpu,
  org.Org_OKPO,

  CASE
  WHEN dbo.GetRegion() = 40
  THEN lpu.Lpu_Name
  ELSE lpu.Lpu_Nick
  END AS Lpu_Name, -- ЛПУ

  CONCAT_WS(' ',
  '',
  Addresslpu.Address_address,
  Lpu.Org_Phone) AS addressLpu,

  EvnPS.EvnPS_NumCard, -- Номер карты
  TO_CHAR(EvnPS.EvnPS_setDT, 'DD.MM.YYYY HH:MI:SS') AS EvnPS_setDT, -- дата поступления
  TO_CHAR(EvnPS.EvnPS_disDT, 'DD.MM.YYYY HH:MI:SS') AS EvnPS_disDT, -- дата выписки
  LpuSection.LpuSection_Name, -- Отделение
  LpuSectionWard_Name, -- палата

  CASE
  WHEN (dbo.GetRegion() = 91 AND EvnPS.LeaveType_id IN (477, 478, 504)) THEN LpuSec.LpuSection_Name
  WHEN ((dbo.GetRegion() = 58 AND EvnPS.LeaveType_id = '368')
  OR EvnPS.LeaveType_id = 5)
  THEN LSection.LpuSection_Name
  END AS Lsection_name, -- переведен в отделение

  rpt.k_day_count_pg(LpuUnit.LpuUnitType_id, EvnPS.EvnPS_setDT, EvnPS.EvnPS_disDT) AS koikodni,

  LS_TransType.LpuSectionTransType_name AS PrehospArrive_Name,
  PBG.BloodGroupType_Name AS BloodGroupType_Name,

  SUBSTRING(PBG.RhFactorType_Name FROM
  (POSITION('(' IN PBG.RhFactorType_Name) + 1) FOR 3) AS RhFactorType_Name,

  COALESCE(PAR.PersonAllergicReaction_Kind, '') AS PersonAllergicReaction_Kind,--#176733

  CONCAT_WS(' ',
  Person.Person_SurName,
  Person.Person_FirName,
  Person.Person_SecName) AS fio,

  Sex.sex_name,

  rpt.ageprint(Person.Person_BirthDay, EvnPS.EvnPS_setDate) AS age,

  dbo.ageymd(Person.Person_BirthDay, EvnPS.EvnPS_setDate, 1) :: INT4 age_year,
  dbo.ageymd(Person.Person_BirthDay, EvnPS.EvnPS_setDate, 2) :: INT4 age_month,
  dbo.ageymd(Person.Person_BirthDay, EvnPS.EvnPS_setDate, 3) :: INT4 age_day,

  TO_CHAR(Person.Person_BirthDay, 'DD.MM.YYYY') AS BirthDay,
  CtznCountry.KLCountry_Name AS citizenship, --гражданство

  CONCAT_WS(' ',
  DocType.DocumentType_Name,
  'серия ' || Doc.Document_Ser,
  '№ ' || Doc.Document_Num) AS person_doc, --паспорт

  Doc.Document_Ser :: VARCHAR,
  Doc.Document_Num :: VARCHAR,

  CASE
  WHEN Polis.polistype_id = 1
  THEN CONCAT_WS(' ',
  'серия ' || Polis.Polis_Ser,
  '№ ' || Polis.Polis_Num)
  WHEN Polis.polistype_id IN (3, 4)
  THEN '№ ' || Person.Person_EdNum
  END AS polis, -- #118000

  Polis.Polis_Ser :: VARCHAR,
  Polis.Polis_Num :: VARCHAR,

  OrgSmo.OrgSmo_Name, --СМО
  TO_CHAR(Polis.Polis_begDate, 'DD.MM.YYYY') AS polis_begdate,
  Person.Person_Snils,
  address.Address_Address, -- адрес

  CASE
  WHEN address.klcity_id IS NOT NULL THEN 1
  WHEN address.kltown_id IS NOT NULL THEN 2
  END AS KLAreaType_id,

  Uaddress.Address_Address AS Uaddress,
  OrgJob.Org_Name, -- место работы

  CASE
  WHEN PP.PrivilegeType_Name IS NOT NULL
  THEN PP.PrivilegeType_Name
  ELSE Post.Post_Name
  END AS Post_Name,-- должность

  SocStatus.SocStatus_Name,

  COALESCE(
  lpudir.Lpu_Nick,
  LpuSectiondir.LpuSection_Name,
  OrgDir.Org_Nick,
  PrehospDirect.PrehospDirect_Name) AS NameDir,  --PROMEDWEB-4699

  CASE
  WHEN EvnPS.PrehospType_id = 1
  THEN 'да'
  ELSE 'нет'
  END extr, -- доставлен по экстренным показаниям

  EvnPS.EvnPS_TimeDesease, --- время с начала заболевания
  CASE EvnPS.Okei_id
  WHEN 100 THEN 'часов'
  WHEN 101 THEN 'суток'
  WHEN 102 THEN 'недели'
  WHEN 104 THEN 'месяцев'
  WHEN 107 THEN 'год'
  END :: VARCHAR AS Okei,-- единицы измерения

  rpt.check2_pg(EvnPS.PrehospType_id = 2, 'да', 'нет') AS pl, -- госпитализирован в плановом порядке
  DiagDir.Diag_FullName :: VARCHAR AS diagdir_name, -- диагноз направившего учреждения

  CASE
  WHEN dbo.GetRegion() != 19
  THEN DiagPriem.Diag_FullName
  ELSE ''
  END :: VARCHAR AS diagpriem_name, --#173336

  CASE
  WHEN EvnPS.Diag_pid IS NOT NULL
  THEN TO_CHAR(EvnPS.EvnPS_setDT, 'DD.MM.YYYY HH:MI:SS') :: VARCHAR
  END AS EvnPS_setDate,

  Diag.Diag_FullName :: VARCHAR AS diag_name, -- основной диагноз
  TO_CHAR(EvnSection.EvnSection_setDate,
  'DD.MM.YYYY HH:MI:SS') :: VARCHAR AS EvnSection_setDate, -- дата установления основного диагноза
  LeaveType.LeaveType_Name, -- исход госпитализации
  anotherMO.lpu_name :: VARCHAR AS anotherMO,--перевод в другую МО
  ResultDesease.ResultDesease_Name, -- исход госпитализации
  Diag.Diag_Code, --МКБ-10
  MesOld.Mes_Code, -- МЭС
  EvnPS.EvnPS_PhaseDescr_pid,---расшифровка диагноза приёмного отделения
  EvnPS.EvnPS_PhaseDescr_did,---расшифровка диагноза направившего		
  Person.Person_Phone, --#118522

  CASE
  WHEN SocStatus.SocStatus_code :: INT = 18
  OR CtznCountry.KLCountry_id != 643
  THEN 1
  ELSE 0 END AS foreigner, --иностранцы -- #172009

  CONCAT(
  msf.Person_SurName || ' ',
  LEFT(msf.Person_FirName, 1) || '.',
  LEFT(msf.Person_SecName, 1) || '. ') AS VrachFio,

  msfZav.ZavOtdel,
  COALESCE(EvnPS.EvnPS_HospCount, 0) AS EvnPS_HospCount,
  DiagAnat.Diag_FullName AS mainAnatDiag,--PROMEDWEB-9834
  anatDiagsAgg.aggMainDiag,--PROMEDWEB-9834
  anatDiagsAgg.concomDiag,--PROMEDWEB-9834
  ceps.RepositoryObserv_Systolic :: TEXT || '/' || ceps.RepositoryObserv_Diastolic :: TEXT AS Davlenie,
  ceps.RepositoryObserv_TemperatureFrom :: TEXT AS RepositoryObserv_TemperatureFrom,
  ceps.RepositoryObserv_Height :: NUMERIC :: TEXT RepositoryObserv_Height,
  ceps.RepositoryObserv_Weight :: NUMERIC :: TEXT RepositoryObserv_Weight,
  SUBSTRING(TO_CHAR(ceps.RepositoryObserv_FluorographyDate, 'DD.MM.YYYY') FROM 4 FOR 7) :: TEXT AS FluorographyYear,
  (CASE WHEN Pediculos.Pediculos_SanitationDT IS NOT NULL THEN 'Проведена' ELSE 'Не проведена' END) :: TEXT Sanitation,
  (CASE WHEN Pediculos.Diag_id IS NOT NULL THEN 'Обнаружен' ELSE 'Не обнаружен' END) :: TEXT isPediculos,
  (CASE WHEN Pediculos.Diag_sid IS NOT NULL THEN 'Обнаружена' ELSE 'Не обнаружена' END) :: TEXT isScabies
  -- Только для Москвы --
  ,
  PrehospTrauma_id :: INT4,
  allergic.allergic_setdt :: TEXT,
  allergic.allergicreactiontype_name :: TEXT,
  allergic.personallergicreaction_kind :: TEXT AS allergicreaction_kind,
  allergic.allergicReactionLevel_name :: TEXT,
  anamnezlife.personmedhistory_descr :: TEXT,
  PersonPrivilege.PrivilegeType_id :: INT,
  TO_CHAR(PersonPrivilege.PrivilegeType_begdate, 'dd.MM.yyyy') :: TEXT PrivilegeType_begdate,
  TO_CHAR(PersonPrivilege.PrivilegeType_enddate, 'dd.MM.yyyy') :: TEXT PrivilegeType_enddate
FROM v_evnps AS EvnPS
  INNER JOIN v_PersonState AS Person
    ON Person.Person_id = EvnPS.Person_id
  LEFT JOIN v_EvnSection AS ES_Last
    ON ES_Last.EvnSection_pid = EvnPS.EvnPS_id -- #145968
    AND ES_Last.EvnSection_Index = ES_Last.evnsection_count - 1
    AND ES_Last.lpu_id = EvnPS.lpu_id
  LEFT JOIN v_EvnOtherLpu AS EOL
    ON EOL.EvnOtherLpu_pid = ES_Last.EvnSection_id--Выписка в другое ЛПУ
  LEFT JOIN v_lpu AS anotherMO
    ON anotherMO.lpu_id = EOL.Org_oid
  LEFT JOIN v_MedStaffFact AS msf
    ON msf.MedStaffFact_id = ES_Last.MedStaffFact_id

  LEFT JOIN LATERAL (SELECT
      ES.EvnSection_id
    FROM v_EvnSection ES
    WHERE ES.EvnSection_pid = EvnPS.EvnPS_id
    AND COALESCE(EvnSection_isPriem, 1) = 2 LIMIT 1)
  ESPriem
    ON TRUE

  LEFT JOIN LATERAL (SELECT
      PrivilegeType_Name
    FROM v_PersonPrivilege PP
    WHERE PP.Person_id = Person.Person_id
    AND (PersonPrivilege_endDate >= EvnPS.EvnPS_setDT
    OR PersonPrivilege_endDate IS NULL)
    AND PrivilegeType_code IN ('81', '82', '83', '84')
    ORDER BY PersonPrivilege_begDate LIMIT 1)
  PP
    ON TRUE

  LEFT JOIN v_EvnSection AS EvnSection
    ON EvnSection.EvnSection_pid = EvnPS.EvnPS_id
    AND EvnSection.EvnSection_Index =
    CASE
    WHEN ESPriem.EvnSection_id IS NULL
    THEN 0
    ELSE 1
    END
    AND EvnSection.lpu_id = EvnPS.lpu_id
  LEFT JOIN v_LpuSection AS LpuSection
    ON LpuSection.LpuSection_id =
    CASE
    WHEN dbo.getregion() = 91
    THEN ES_Last.LpuSection_id
    ELSE EvnSection.LpuSection_id
    END
  LEFT JOIN LpuUnit
    ON LpuUnit.LpuUnit_id = LpuSection.LpuUnit_id

  LEFT JOIN LATERAL (SELECT
      CONCAT(
      msf.Person_SurName || ' ',
      LEFT(msf.Person_FirName, 1) || '.',
      LEFT(msf.Person_SecName, 1) || '. ') AS ZavOtdel
    FROM v_MedStaffFact AS msf
      LEFT JOIN Lpu AS Lpu
        ON Lpu.Lpu_id = msf.Lpu_id
      LEFT JOIN v_LpuBuilding AS lb
        ON lb.LpuBuilding_id = msf.LpuBuilding_id
      LEFT JOIN v_LpuUnit AS lu
        ON lu.LpuUnit_id = msf.LpuUnit_id
      LEFT JOIN v_LpuSection AS ls
        ON ls.LpuSection_id = msf.LpuSection_id
      LEFT JOIN v_PostMed AS ps
        ON ps.PostMed_id = msf.Post_id
      LEFT JOIN v_PersonState AS p
        ON p.Person_id = msf.Person_id
    WHERE msf.Lpu_id = EvnPS.Lpu_id
    AND msf.LpuUnit_id = LpuUnit.LpuUnit_id
    AND msf.LpuSection_id = LpuSection.LpuSection_id
    AND lb.LpuBuilding_id = LpuSection.LpuBuilding_id
    AND ps.PostMed_Name LIKE '%завед%делен%'
    AND COALESCE(msf.WorkData_endDate, date 'infinity') > CURRENT_DATE LIMIT 1)
  msfZav
    ON TRUE

  LEFT JOIN v_Lpu_all AS Lpu
    ON Lpu.Lpu_id = EvnPS.Lpu_id
  LEFT JOIN Org
    ON Org.Org_id = Lpu.Org_id
  LEFT JOIN Sex
    ON Sex.Sex_id = Person.Sex_id
  LEFT JOIN v_Polis AS Polis
    ON Polis.Polis_id = Person.Polis_id
  LEFT JOIN v_OrgSmo AS OrgSmo
    ON OrgSmo.OrgSmo_id = Polis.OrgSmo_id
  LEFT JOIN v_Diag AS Diag
    ON Diag.Diag_id = --#59835
    CASE
    WHEN dbo.GetRegion() = 91
    THEN ES_Last.Diag_id
    ELSE EvnSection.Diag_id
    END
  LEFT JOIN v_Diag AS DiagAnat
    ON DiagAnat.Diag_id = EvnPS.Diag_aid

  LEFT JOIN LATERAL (SELECT
      STRING_AGG(
      CASE WHEN edps.DiagSetClass_id = 2 THEN d.Diag_FullName END,
      ';' || CHR(10)) AS aggMainDiag,-- Осложнение основного
      STRING_AGG(
      CASE WHEN edps.DiagSetClass_id = 3 THEN d.Diag_FullName END,
      ';' || CHR(10)) AS concomDiag -- Сопутствующий
    FROM v_EvnDiagPS AS edps
      INNER JOIN v_Diag AS d
        ON d.Diag_id = edps.Diag_id
    WHERE edps.EvnDiagPS_rid = p_evnps_id
    AND edps.DiagSetClass_id IN (2, 3) -- Осложнение основного / Сопутствующий
    AND edps.DiagSetType_id = 5)
  anatDiagsAgg
    ON TRUE--PROMEDWEB-9834

  LEFT JOIN v_MesOld AS MesOld
    ON MesOld.Mes_id = EvnSection.Mes_id
  LEFT JOIN v_SocStatus AS SocStatus
    ON Person.SocStatus_id = SocStatus.SocStatus_id --#99738
  LEFT JOIN Address AS AddressLpu
    ON AddressLpu.Address_id = Lpu.UAddress_id
  LEFT JOIN v_LpuSectionWard AS LSW
    ON LSW.LpuSectionWard_id = EvnSection.LpuSectionWard_id
  LEFT JOIN v_EvnOtherSection AS OtherSection
    ON EvnSection.EvnSection_pid = OtherSection.EvnOtherSection_pid
  LEFT JOIN v_LpuSection AS LSection
    ON LSection.LpuSection_id = OtherSection.LpuSection_oid
  --Для Крыма
  LEFT JOIN v_EvnOtherSection EOS
    ON EOS.EvnOtherSection_pid = EvnSection.EvnSection_id
  LEFT JOIN v_EvnOtherStac EOST
    ON EOST.EvnOtherStac_pid = EvnSection.EvnSection_id
  LEFT JOIN v_LpuSection LpuSec
    ON LpuSec.LpuSection_id = COALESCE(EOS.LpuSection_oid, EOST.LpuSection_oid) --#190720
  --транспортировка
  LEFT JOIN LpuSectionTransType AS LS_TransType
    ON LS_TransType.LpuSectionTransType_id =
    COALESCE(
    EvnPS.LpuSectionTransType_id,
    EvnSection.LpuSectionTransType_id) --#179827
  LEFT JOIN PrehospArrive
    ON PrehospArrive.PrehospArrive_id = EvnPS.PrehospArrive_id --#99738
  --жительство и прикрепление
  LEFT JOIN Address
    ON Address.Address_id = Person.PAddress_id
  LEFT JOIN Address AS UAddress
    ON UAddress.Address_id = Person.UAddress_id
  --документ, удостоверяющий личность
  LEFT JOIN v_Document Doc
    ON person.Document_id = Doc.Document_id
  LEFT JOIN v_DocumentType DocType
    ON Doc.DocumentType_id = DocType.DocumentType_id
  --гражданство
  LEFT JOIN v_NationalityStatus AS NationalityStatus
    ON Person.NationalityStatus_id = NationalityStatus.NationalityStatus_id
  LEFT JOIN v_KLCountry CtznCountry
    ON CtznCountry.KLCountry_id =
    COALESCE(
    NationalityStatus.KLCountry_id,
    Doc.KLCountry_id)
  LEFT JOIN Job
    ON Job.Job_id = Person.Job_id
  LEFT JOIN Org AS OrgJob
    ON OrgJob.Org_id = Job.Org_id
  LEFT JOIN Post
    ON Post.Post_id = Job.Post_id
  LEFT JOIN v_Lpu AS LpuDir
    ON LpuDir.Lpu_id = EvnPS.Lpu_did
  LEFT JOIN v_LpuSection AS LpuSectiondir
    ON LpuSectiondir.LpuSection_id = EvnPS.LpuSection_did
  LEFT JOIN v_Org AS OrgDir
    ON orgdir.Org_id = EvnPS.Org_did
  LEFT JOIN v_Diag AS DiagDir
    ON DiagDir.Diag_id = EvnPS.Diag_did
  LEFT JOIN v_Diag AS DiagPriem
    ON DiagPriem.Diag_id = EvnPS.Diag_pid
  LEFT JOIN LeaveType
    ON LeaveType.LeaveType_id = ES_Last.LeaveType_id -- #145968
  LEFT JOIN v_EvnLeaveBase AS EvnLeave
    ON EvnLeave.EvnLeaveBase_pid = ES_Last.EvnSection_id
  LEFT JOIN ResultDesease
    ON ResultDesease.ResultDesease_id = EvnLeave.ResultDesease_id
  LEFT JOIN v_PersonCard AS PersonCard
    ON PersonCard.Person_id = Person.Person_id
    AND ((PersonCard.personcard_begDate <= EvnPS.EvnPS_setDate)
    AND (PersonCard.personcard_endDate >= EvnPS.EvnPS_setDate
    OR PersonCard.personcard_endDate IS NULL))
    AND (PersonCard.LpuAttachType_id = 1)
  LEFT JOIN v_Lpu AS ll
    ON PersonCard.Lpu_id = ll.Lpu_id

  LEFT JOIN LATERAL (SELECT
      COALESCE(BGT.BloodGroupType_Name, '') AS BloodGroupType_Name,
      COALESCE(RFT.RhFactorType_Name, '') AS RhFactorType_Name
    FROM v_PersonBloodGroup AS PBG
      LEFT JOIN v_BloodGroupType BGT
        ON BGT.BloodGroupType_id = PBG.BloodGroupType_id
      LEFT JOIN v_RhFactorType RFT
        ON RFT.RhFactorType_id = PBG.RhFactorType_id
    WHERE PBG.Person_id = EvnPS.Person_id
    ORDER BY PBG.PersonBloodGroup_setDT DESC,
    PersonBloodGroup_id DESC LIMIT 1)
  PBG
    ON TRUE --#177128

  LEFT JOIN LATERAL (SELECT
      STRING_AGG(DISTINCT
      CONCAT_WS('; ',
      ART.AllergicReactionType_Name,
      ARL.AllergicReactionLevel_Name,
      COALESCE(
      dm.drugmnn_name,
      par.personallergicreaction_kind)
      ),
      CHR(10)) AS PersonAllergicReaction_Kind
    FROM v_personallergicreaction AS par
      INNER JOIN v_allergicreactiontype AS art
        ON art.allergicreactiontype_id = par.allergicreactiontype_id
      INNER JOIN v_allergicreactionlevel AS arl
        ON arl.allergicreactionlevel_id = par.allergicreactionlevel_id
      LEFT JOIN v_drugmnn AS dm
        ON dm.drugmnn_id = par.drugmnn_id
    WHERE par.person_id = Person.Person_id
    AND art.allergicreactiontype_id = 2)
  PAR
    ON TRUE

  LEFT JOIN v_PrehospDirect AS PrehospDirect
    ON PrehospDirect.PrehospDirect_id = EvnPS.PrehospDirect_id
    AND PrehospDirect.PrehospDirect_id IN (5, 6, 7, 8, 9) --PROMEDWEB-4699

  LEFT JOIN LATERAL (SELECT
      *
    FROM v_Pediculos P
    WHERE P.Evn_id = EvnPS.EvnPS_id
    ORDER BY P.Pediculos_insDT DESC LIMIT 1)
  Pediculos
    ON TRUE

  LEFT JOIN LATERAL (SELECT
      ceps.RepositoryObserv_Systolic,
      ceps.RepositoryObserv_Diastolic,
      ceps.RepositoryObserv_Height,
      ceps.RepositoryObserv_Weight,
      ceps.RepositoryObserv_TemperatureFrom,
      ceps.RepositoryObserv_FluorographyDate
    FROM v_RepositoryObserv ceps
    WHERE ceps.Evn_id = EvnPS.EvnPS_id
    ORDER BY ceps.RepositoryObserv_updDT DESC LIMIT 1)
  ceps
    ON TRUE

  LEFT JOIN LATERAL (SELECT
      STRING_AGG(TO_CHAR(par.personallergicreaction_setdt, 'dd.MM.yyyy') :: TEXT, ', <br>') allergic_setdt,
      STRING_AGG(art.allergicreactiontype_name, ', <br>') allergicreactiontype_name,
      STRING_AGG(par.personallergicreaction_kind, ', <br>') personallergicreaction_kind,
      STRING_AGG(arl.allergicReactionLevel_name, ', <br>') allergicReactionLevel_name
    FROM PersonAllergicReaction par
      LEFT JOIN allergicreactiontype art
        ON par.allergicreactiontype_id = art.allergicreactiontype_id
      LEFT JOIN allergicReactionLevel arl
        ON arl.allergicReactionLevel_id = par.allergicReactionLevel_id
    WHERE par.person_id = EvnPS.person_id)
  AS allergic
    ON TRUE

  LEFT JOIN LATERAL (SELECT
      TO_CHAR(pmh.PersonMedHistory_setDT, 'DD.MM.YYYY') || ' ' || pmh.PersonMedHistory_Descr AS personmedhistory_descr
    FROM dbo.v_PersonMedHistory pmh
    WHERE pmh.Person_id = EvnPS.person_id LIMIT 1)
  anamnezlife
    ON TRUE
  LEFT JOIN LATERAL (SELECT
      PrivilegeType.PrivilegeType_id,
      PrivilegeType.PrivilegeType_begdate,
      PrivilegeType.PrivilegeType_enddate
    FROM v_evnsection es
      LEFT JOIN PrivilegeType
        ON es.PrivilegeType_id = PrivilegeType.PrivilegeType_id
    WHERE PrivilegeType.PrivilegeType_Code IN (81, 82, 83)
    AND es.evnsection_pid = EvnPS.evnps_id
    ORDER BY PrivilegeType.PrivilegeType_Code DESC LIMIT 1)
  PersonPrivilege
    ON TRUE
WHERE EvnPS.EvnPS_id = p_evnps_id LIMIT 1
;
END
$plpgsql$;

