
            with cte as (select cast(localtimestamp as date) as curdate)
            select
                case when Evn.Evn_id is not null then 'edit' else 'view' end as "accessType",
                EP.EvnPrescr_id
                    ||'-'|| coalesce(Regime.EvnPrescrRegime_id,Diet.EvnPrescrDiet_id,Obs.EvnPrescrObserv_id,EPOB.EvnPrescrOperBlock_id,EPFDU.EvnPrescrFuncDiagUsluga_id,0)
                as "EvnPrescr_key",
                 EP.EvnPrescr_id as "EvnPrescr_id"
                ,EP.EvnPrescr_pid as "EvnPrescr_pid"
                ,EP.EvnPrescr_rid as "EvnPrescr_rid"
                ,to_char(coalesce(EP.EvnPrescr_setDT,Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT), 'dd.mm.yyyy') as "EvnPrescr_setDate"
                ,null as "EvnPrescr_setTime"
                ,coalesce(Regime.EvnPrescrRegime_IsExec,Diet.EvnPrescrDiet_IsExec,Obs.EvnPrescrObserv_IsExec,EP.EvnPrescr_IsExec,1) as "EvnPrescr_IsExec" --EPTTT.EvnPrescrTreatTimetable_IsExec,EPPRTT.EvnPrescrProcTimetable_IsExec,
                ,case when coalesce(EU.EvnUsluga_id,EDr.EvnDrug_id) is null then 1 else 2 end as "EvnPrescr_IsHasEvn"
                -- Если в качестве даты-времени выполнения брать EU.EvnUsluga_setDT, то дата может не отобразиться, если при выполнении не была создана услуга или услуга не связана с назначением
                -- Поэтому решил использовать EP.EvnPrescr_updDT, т.к. после выполнения эта дата не меняется
                ,case when (EP.PrescriptionType_id in (7,11,12,13) and 2 = EP.EvnPrescr_IsExec) then to_char(EP.EvnPrescr_updDT, 'dd.mm.yyyy')
                    ||' '||to_char(EP.EvnPrescr_updDT, 'HH24:MI:SS')
                    else null
                end as "EvnPrescr_execDT"
                ,case when ED.EvnDirection_id is null then 1 else 2 end as "EvnPrescr_IsDir"
                ,coalesce(EP.PrescriptionStatusType_id,Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id) as "PrescriptionStatusType_id"
                ,PT.PrescriptionType_id as "PrescriptionType_id"
                ,PT.PrescriptionType_Code as "PrescriptionType_Code"
                ,PT.PrescriptionType_Name as "PrescriptionType_Name"
                ,(select count(EPin.PrescriptionType_id) from v_EvnPrescr EPin where EPin.EvnPrescr_pid = EP.EvnPrescr_pid and EPin.PrescriptionType_id = EP.PrescriptionType_id group by EPin.PrescriptionType_id) as "cntInPrescriptionTypeGroup"
                ,coalesce(EP.EvnPrescr_IsCito,1) as "EvnPrescr_IsCito"
                ,case
                    when Regime.EvnPrescrRegime_id is not null
                    then (select count(EvnPrescrRegime_id) from v_EvnPrescrRegime where EvnPrescrRegime_pid = EP.EvnPrescr_id and PrescriptionStatusType_id != 3)
                    when Diet.EvnPrescrDiet_id is not null
                    then (select count(EvnPrescrDiet_id) from v_EvnPrescrDiet where EvnPrescrDiet_pid = EP.EvnPrescr_id and PrescriptionStatusType_id != 3)
                    when Obs.EvnPrescrObserv_id is not null
                    then (select count(EvnPrescrObserv_id) from v_EvnPrescrObserv where EvnPrescrObserv_pid = EP.EvnPrescr_id and PrescriptionStatusType_id != 3)
                else
                    null
                end as "EvnPrescr_cnt" --число дней указаннного назначения
                ,IsCito.YesNo_Code as "IsCito_Code"
                ,IsCito.YesNo_Name as "IsCito_Name"
                ,coalesce(EP.EvnPrescr_Descr,Regime.EvnPrescrRegime_Descr,Diet.EvnPrescrDiet_Descr,Obs.EvnPrescrObserv_Descr,'') as "EvnPrescr_Descr",
                --1 режим
                Regime.EvnPrescrRegime_id as "EvnPrescrRegime_id",
                coalesce(PRT.PrescriptionRegimeType_id, 0) as "PrescriptionRegimeType_id",--тип режима
                coalesce(PRT.PrescriptionRegimeType_Code, 0) as "PrescriptionRegimeType_Code",
                coalesce(PRT.PrescriptionRegimeType_Name, '') as "PrescriptionRegimeType_Name",
                --2 диета
                Diet.EvnPrescrDiet_id as "EvnPrescrDiet_id",
                coalesce(PDT.PrescriptionDietType_id, 0) as "PrescriptionDietType_id",--тип диеты
                coalesce(PDT.PrescriptionDietType_Code, '') as "PrescriptionDietType_Code",
                coalesce(PDT.PrescriptionDietType_Name, '') as "PrescriptionDietType_Name",
                --10
                Obs.EvnPrescrObserv_id as "EvnPrescrObserv_id",
                OTT.ObservTimeType_id as "ObservTimeType_id",
                OTT.ObservTimeType_Name as "ObservTimeType_Name",
                EPOP.EvnPrescrObservPos_id as "EvnPrescrObservPos_id",
                OPT.ObservParamType_Name as "ObservParamType_Name",
                case
                    when Obs.EvnPrescrObserv_id is not null
                    then (select count(EvnPrescrObservPos_id) from v_EvnPrescrObservPos where EvnPrescr_id = EP.EvnPrescr_id)
                else
                    null
                end as "cntParam"
                --5
                ,ECPTL.EvnCourseProc_id as "EvnCourseProc_id"
                ,EPTD.EvnPrescrTreatDrug_id as "EvnPrescrTreatDrug_id"
                ,Drug.Drug_id as "Drug_id"
                ,dcm.DrugComplexMnn_id as "DrugComplexMnn_id"
                ,coalesce(Drug.Drug_Name, dcm.DrugComplexMnn_RusName, '') as "Drug_Name"
                ,coalesce(Drug.DrugTorg_Name, dcm.DrugComplexMnn_RusName, '') as "DrugTorg_Name"
                ,LTRIM(to_char(EPTD.EvnPrescrTreatDrug_KolvoEd, '9999999999D99')) as "EvnPrescrTreatDrug_KolvoEd"
                ,coalesce(df.NAME,Drug.DrugForm_Name) as "DrugForm_Name"
                ,LTRIM(to_char(EPTD.EvnPrescrTreatDrug_Kolvo, '9999999999D99')) as "EvnPrescrTreatDrug_Kolvo"
                ,coalesce(ep_mu.SHORTNAME, ep_cu.SHORTNAME) as "EdUnits_Nick"
                ,EPTD.EvnPrescrTreatDrug_DoseDay as "EvnPrescrTreatDrug_DoseDay"
                ,EPTD.EvnPrescrTreatDrug_FactCount as "FactCntDay"
                ,EPT.EvnPrescrTreat_PrescrCount as "PrescrCntDay"
                ,case when EP.PrescriptionType_id = 5 then (
                    select count(1) from v_EvnPrescrTreatDrug where EvnPrescrTreat_id = EP.EvnPrescr_id
                ) else 0 end as "cntDrug"

                ,ec_drug.EvnCourseTreatDrug_id as "EvnCourseTreatDrug_id"
                ,coalesce(CourseDrug.Drug_Name, CourseDcm.DrugComplexMnn_RusName, '') as "CourseDrug_Name"
                ,coalesce(CourseDrug.DrugTorg_Name, CourseDcm.DrugComplexMnn_RusName, '') as "CourseDrugTorg_Name"
                ,LTRIM(to_char(ec_drug.EvnCourseTreatDrug_KolvoEd, '9999999999D99')) as "EvnCourseTreatDrug_KolvoEd"
                ,coalesce(CourseDf.NAME,CourseDrug.DrugForm_Name) as "CourseDrugForm_Name"
                ,LTRIM(to_char(ec_drug.EvnCourseTreatDrug_Kolvo, '9999999999D99')) as "EvnCourseTreatDrug_Kolvo"
                ,coalesce(ec_mu.SHORTNAME, ec_cu.SHORTNAME) as "CourseEdUnits_Nick"
                ,ec_drug.EvnCourseTreatDrug_MaxDoseDay as "EvnCourseTreatDrug_MaxDoseDay"
                ,ec_drug.EvnCourseTreatDrug_MinDoseDay as "EvnCourseTreatDrug_MinDoseDay"
                ,ec_drug.EvnCourseTreatDrug_PrescrDose as "EvnCourseTreatDrug_PrescrDose"
                ,ec_drug.EvnCourseTreatDrug_FactDose as "EvnCourseTreatDrug_FactDose"
                ,ec_drug.EvnCourseTreatDrug_IsHand as "EvnCourseTreatDrug_IsHand"
                ,case when EP.PrescriptionType_id = 5 then (
                    select count(EvnCourseTreatDrug_id) from v_EvnCourseTreatDrug where EvnCourseTreat_id = EPT.EvnCourse_id
                ) else 0 end as "cntCourseDrug"

                ,coalesce(PIT.PrescriptionIntroType_Name, '') as "PrescriptionIntroType_Name"
                ,coalesce(PFT.PerformanceType_Name, '') as "PerformanceType_Name"
                --6
                ,CUC.UslugaComplex_id as "CourseUslugaComplex_id"
                ,CUC.UslugaComplex_2011id as "CourseUslugaComplex_2011id"
                ,CUC.UslugaComplex_Name as "CourseUslugaComplex_Name"
                ,CUC.UslugaComplex_Code as "CourseUslugaComplex_Code"
                ,MS.MedService_id as "MedService_id"
                ,MS.MedService_Name as "MedService_Name"
                --5,6
                ,coalesce(EPT.EvnCourse_id, EPPR.EvnCourse_id) as "EvnCourse_id"
                ,coalesce(to_char(coalesce(EPT.EvnPrescrTreat_setDT,EPPR.EvnPrescrProc_setDT), 'dd.mm.yyyy'), '') as "graf_date"
                ,coalesce(ECT.EvnCourseTreat_MaxCountDay,ECPR.EvnCourseProc_MaxCountDay, 0) as "MaxCountInDay"
                ,coalesce(ECT.EvnCourseTreat_MinCountDay,ECPR.EvnCourseProc_MinCountDay, 0) as "MinCountInDay"
                ,coalesce(ECT.EvnCourseTreat_Duration,ECPR.EvnCourseProc_Duration, 0) as "Duration"
                ,coalesce(ECT.EvnCourseTreat_ContReception,ECPR.EvnCourseProc_ContReception, 0) as "ContReception"
                ,coalesce(ECT.EvnCourseTreat_Interval,ECPR.EvnCourseProc_Interval, 0) as "Interval"
                ,case
                    when EP.PrescriptionType_id = 5 then (select count(EvnPrescrTreat_id) from v_EvnPrescrTreat where ECT.EvnCourseTreat_id = EvnCourse_id)
                    when EP.PrescriptionType_id = 6 then (select count(EvnPrescrProc_id) from v_EvnPrescrProc where ECPR.EvnCourseProc_id = EvnCourse_id)
                    else 0
                end as "PrescrCount"
                ,DTP.DurationType_Nick as "DurationType_Nick"
                ,DTI.DurationType_Nick as "DurationType_IntNick"
                ,DTN.DurationType_Nick as "DurationType_RecNick"
                --6,7,11,12,13
                ,UC.UslugaComplex_id as "UslugaComplex_id"
                ,UC.UslugaComplex_2011id as "UslugaComplex_2011id"
                ,UC.UslugaComplex_Code as "UslugaComplex_Code"
                ,UC.UslugaComplex_Name as "UslugaComplex_Name"
                ,UC.UslugaCategory_id as "UslugaCategory_did"
                --7,12
                ,coalesce(EPOB.EvnPrescrOperBlock_id, EPFDU.EvnPrescrFuncDiagUsluga_id) as "TableUsluga_id"
                ,case
                    when EP.PrescriptionType_id = 7 then (select count(EvnPrescrOperBlock_id) from v_EvnPrescrOperBlock where EvnPrescrOperBlock_id = EP.EvnPrescr_id)
                    when EP.PrescriptionType_id = 12 then (select count(EvnPrescrFuncDiagUsluga_id) from v_EvnPrescrFuncDiagUsluga where EvnPrescrFuncDiag_id = EP.EvnPrescr_id)
                    else 0
                end as "cntUsluga"
                --
                ,ED.EvnDirection_id as "EvnDirection_id"
                ,EQ.EvnQueue_id as "EvnQueue_id"
                ,case when ED.EvnDirection_Num is null /*or coalesce(ED.EvnDirection_IsAuto,1) = 2*/ then '' else cast(ED.EvnDirection_Num as varchar) end as "EvnDirection_Num"
                ,case
                    when TTMS.TimetableMedService_id is not null then
                        case
                            when MS.MedService_id is not null and  MS.LpuSection_id is null and MS.LpuUnit_id is null
                            then coalesce(MS.MedService_Name,'')
                            when MS.MedService_id is not null and  MS.LpuSection_id is null and MS.LpuUnit_id is not null
                            then coalesce(MS.MedService_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                            when MS.MedService_id is not null and  MS.LpuSection_id is not null and MS.LpuUnit_id is not null
                            then coalesce(MS.MedService_Name,'') ||' / '|| coalesce(LSPD.LpuSectionProfile_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                            else coalesce(LSPD.LpuSectionProfile_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                        end ||' / '|| coalesce(Lpu.Lpu_Nick,'')
                    when TTR.TimetableResource_id is not null then coalesce(MS.MedService_Name, '')||' / '||coalesce(R.Resource_Name, '')||' / '||coalesce(Lpu.Lpu_Nick, '')
                    when EQ.EvnQueue_id is not null then
                        case
                            when MS.MedService_id is not null and  MS.LpuSection_id is null and MS.LpuUnit_id is null
                            then coalesce(MS.MedService_Name,'')
                            when MS.MedService_id is not null and  MS.LpuSection_id is null and MS.LpuUnit_id is not null
                            then coalesce(MS.MedService_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                            when MS.MedService_id is not null and  MS.LpuSection_id is not null and MS.LpuUnit_id is not null
                            then coalesce(MS.MedService_Name,'') ||' / '|| coalesce(LSPD.LpuSectionProfile_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                            else coalesce(LSPD.LpuSectionProfile_Name,'') ||' / '|| coalesce(LU.LpuUnit_Name,'')
                        end ||' / '|| coalesce(Lpu.Lpu_Nick,'')
                else '' end as "RecTo"
                ,case
                    when TTMS.TimetableMedService_id is not null then coalesce(to_char(TTMS.TimetableMedService_begTime, 'dd.mm.yyyy'),'')||' '||coalesce(to_char(TTMS.TimetableMedService_begTime, 'HH24:MI:SS'),'')
                    when TTR.TimetableResource_id is not null then coalesce(to_char(TTR.TimetableResource_begTime::date, 'DD.MM.YYYY'), '')||' '||coalesce(to_char(TTR.TimetableResource_begTime::time, 'HH24:MI:SS'), '')
                    when EQ.EvnQueue_id is not null then 'В очереди с '|| coalesce(to_char(EQ.EvnQueue_setDate, 'dd.mm.yyyy'),'')
                else '' end as "RecDate"
                ,case
                    when TTMS.TimetableMedService_id is not null then 'TimetableMedService'
                    when TTR.TimetableResource_id is not null then 'TimetableResource'
                    when EQ.EvnQueue_id is not null then 'EvnQueue'
                else '' end as "timetable"
                ,case
                    when TTMS.TimetableMedService_id is not null  then TTMS.TimetableMedService_id
                    when TTR.TimetableResource_id is not null  then TTR.TimetableResource_id
                    when EQ.EvnQueue_id is not null then EQ.EvnQueue_id
                else null end as "timetable_id"
                ,EP.EvnPrescr_pid as "timetable_pid"
                ,LU.LpuUnitType_SysNick as "LpuUnitType_SysNick"
                ,DT.DirType_Code as "DirType_Code"
                ,EUP.EvnUslugaPar_id as "EvnUslugaPar_id",
                MS.Lpu_id as "Lpu_did",
                MS.LpuUnit_id as "LpuUnit_did",
                LS.LpuSectionProfile_id as "LpuSectionProfile_id",
                coalesce(epl.PayType_id,es.PayType_id,0) as "PayType_id",
                EP.StudyTarget_id as "StudyTarget_id",
                UCMS.UslugaComplexMedService_id as "UslugaComplexMedService_id"
                ,EvnXmlDir.EvnXml_id as "EvnXmlDir_id"
                ,EvnXmlDir.XmlType_id as "EvnXmlDirType_id"
            from v_EvnPrescr EP
                inner join PrescriptionType PT on PT.PrescriptionType_id = EP.PrescriptionType_id
                left join YesNo IsCito on IsCito.YesNo_id = coalesce(EP.EvnPrescr_IsCito,1)
                left join v_EvnPrescrRegime Regime on EP.PrescriptionType_id = 1 and Regime.EvnPrescrRegime_pid = EP.EvnPrescr_id
                left join PrescriptionRegimeType PRT on EP.PrescriptionType_id = 1 and PRT.PrescriptionRegimeType_id = Regime.PrescriptionRegimeType_id
                left join v_EvnPrescrDiet Diet on EP.PrescriptionType_id = 2 and Diet.EvnPrescrDiet_pid = EP.EvnPrescr_id
                left join PrescriptionDietType PDT on EP.PrescriptionType_id = 2 and PDT.PrescriptionDietType_id = Diet.PrescriptionDietType_id
                left join v_EvnPrescrTreat EPT on EP.PrescriptionType_id = 5 and EPT.EvnPrescrTreat_id = EP.EvnPrescr_id
                left join v_EvnCourseProcTreatLink ECPTL on
                    ECPTL.EvnCourseTreat_id = EPT.EvnCourse_id
                    and cast(ECPTL.EvnCourseProcTreatLink_begDate as date) <= (select curdate from cte)
                    and (ECPTL.EvnCourseProcTreatLink_endDate is null
                        or cast(ECPTL.EvnCourseProcTreatLink_endDate as date) > (select curdate from cte))
                left join v_EvnCourseTreat ECT on EP.PrescriptionType_id = 5 and ECT.EvnCourseTreat_id = EPT.EvnCourse_id
                left join v_EvnPrescrTreatDrug EPTD on EP.PrescriptionType_id = 5 and EPTD.EvnPrescrTreat_id = EPT.EvnPrescrTreat_id
                left join v_EvnCourseTreatDrug ec_drug on EP.PrescriptionType_id = 5 and ec_drug.EvnCourseTreat_id = EPT.EvnCourse_id
                left join rls.MASSUNITS ep_mu on EP.PrescriptionType_id = 5 and EPTD.MASSUNITS_ID = ep_mu.MASSUNITS_ID
                left join rls.CUBICUNITS ep_cu on EP.PrescriptionType_id = 5 and EPTD.CUBICUNITS_id = ep_cu.CUBICUNITS_id
                left join rls.MASSUNITS ec_mu on EP.PrescriptionType_id = 5 and ec_drug.MASSUNITS_ID = ec_mu.MASSUNITS_ID
                left join rls.CUBICUNITS ec_cu on EP.PrescriptionType_id = 5 and ec_drug.CUBICUNITS_id = ec_cu.CUBICUNITS_id
                left join PerformanceType PFT on  EP.PrescriptionType_id = 5 and ECT.PerformanceType_id = PFT.PerformanceType_id
                left join PrescriptionIntroType PIT on EP.PrescriptionType_id = 5 and ECT.PrescriptionIntroType_id = PIT.PrescriptionIntroType_id
                left join rls.v_Drug Drug on EP.PrescriptionType_id = 5 and Drug.Drug_id = EPTD.Drug_id
                left join rls.v_DrugComplexMnn dcm on EP.PrescriptionType_id = 5 and dcm.DrugComplexMnn_id = EPTD.DrugComplexMnn_id
                left join rls.CLSDRUGFORMS df on dcm.CLSDRUGFORMS_ID = df.CLSDRUGFORMS_ID
                left join rls.v_Drug CourseDrug on EP.PrescriptionType_id = 5 and CourseDrug.Drug_id = ec_drug.Drug_id
                left join rls.v_DrugComplexMnn CourseDcm on EP.PrescriptionType_id = 5 and CourseDcm.DrugComplexMnn_id = ec_drug.DrugComplexMnn_id
                left join rls.CLSDRUGFORMS CourseDf on CourseDcm.CLSDRUGFORMS_ID = CourseDf.CLSDRUGFORMS_ID
                left join v_EvnPrescrProc EPPR on EP.PrescriptionType_id = 6 and EPPR.EvnPrescrProc_id = EP.EvnPrescr_id
                left join v_EvnCourseProc ECPR on EP.PrescriptionType_id = 6 and ECPR.EvnCourseProc_id = EPPR.EvnCourse_id
                left join DurationType DTP on  EP.PrescriptionType_id in (5,6) and coalesce(ECPR.DurationType_id,ECT.DurationType_id) = DTP.DurationType_id
                left join DurationType DTN on  EP.PrescriptionType_id in (5,6) and coalesce(ECPR.DurationType_recid,ECT.DurationType_recid) = DTN.DurationType_id
                left join DurationType DTI on  EP.PrescriptionType_id in (5,6) and coalesce(ECPR.DurationType_intid,ECT.DurationType_intid) = DTI.DurationType_id
                left join v_EvnPrescrOper EPO on EP.PrescriptionType_id = 7 and EPO.EvnPrescrOper_id = EP.EvnPrescr_id
                left join lateral (
                    select * from v_EvnPrescrOperBlock where EP.PrescriptionType_id = 7 and EvnPrescrOperBlock_id = EP.EvnPrescr_id
                ) EPOB on true
                --left join v_EvnPrescrLabDiag EPLD on EP.PrescriptionType_id = 11 and EPLD.EvnPrescrLabDiag_id = EP.EvnPrescr_id
                left join lateral (
                    select * from v_EvnPrescrLabDiag where EP.PrescriptionType_id = 11 and EvnPrescrLabDiag_id = EP.EvnPrescr_id limit 100
                ) EPLD on true
                --left join v_EvnPrescrFuncDiagUsluga EPFDU on EP.PrescriptionType_id = 12 and EPFDU.EvnPrescrFuncDiag_id = EP.EvnPrescr_id
                left join lateral (
                    select * from v_EvnPrescrFuncDiagUsluga where EP.PrescriptionType_id = 12 and EvnPrescrFuncDiag_id = EP.EvnPrescr_id limit 100
                ) EPFDU on true
                --left join v_EvnPrescrConsUsluga EPCU on EP.PrescriptionType_id = 13 and EPCU.EvnPrescrConsUsluga_id = EP.EvnPrescr_id
                left join lateral (
                    select * from v_EvnPrescrConsUsluga where EP.PrescriptionType_id = 13 and EvnPrescrConsUsluga_id = EP.EvnPrescr_id limit 100
                ) EPCU on true
                left join v_UslugaComplex UC on EP.PrescriptionType_id in (6,7,11,12,13) and UC.UslugaComplex_id = coalesce(EPPR.UslugaComplex_id, EPFDU.UslugaComplex_id, EPLD.UslugaComplex_id, EPOB.UslugaComplex_id, EPCU.UslugaComplex_id)
                left join v_UslugaComplex CUC on EP.PrescriptionType_id = 6 and CUC.UslugaComplex_id = ECPR.UslugaComplex_id
                left join v_EvnPrescrObserv Obs on EP.PrescriptionType_id = 10 and Obs.EvnPrescrObserv_pid = EP.EvnPrescr_id
                left join v_ObservTimeType OTT on EP.PrescriptionType_id = 10 and OTT.ObservTimeType_id = Obs.ObservTimeType_id
                left join v_EvnPrescrObservPos EPOP on EP.PrescriptionType_id = 10 and EPOP.EvnPrescr_id = EP.EvnPrescr_id
                left join ObservParamType OPT on EP.PrescriptionType_id = 10 and OPT.ObservParamType_id = EPOP.ObservParamType_id

                left join lateral (
                    Select
                        ED.EvnDirection_id,
                        ED.EvnQueue_id,
                        coalesce(ED.Lpu_sid, ED.Lpu_id) Lpu_id,
                        ED.EvnDirection_Num,
                        ED.EvnDirection_IsAuto,
                        ED.LpuSection_did,
                        ED.LpuUnit_did,
                        ED.Lpu_did,
                        ED.MedService_id,
                        ED.Resource_id,
                        ED.LpuSectionProfile_id,
                        DirType_id
                    from v_EvnPrescrDirection epd
                    inner join v_EvnDirection_all ED on epd.EvnDirection_id = ED.EvnDirection_id
                        and ED.EvnDirection_failDT is null
                        and coalesce(ED.EvnStatus_id, 16) not in (12,13)
                    where epd.EvnPrescr_id = EP.EvnPrescr_id
                    order by epd.EvnPrescrDirection_insDT desc
                     limit 1
                ) ED on true
                -- службы и параклиника
                left join lateral (
                    Select TimetableMedService_id, TimetableMedService_begTime from v_TimetableMedService_lite TTMS where TTMS.EvnDirection_id = ED.EvnDirection_id limit 1
                ) TTMS on true
                -- очередь
                left join lateral (
                    (Select EQ.EvnQueue_id, EQ.LpuUnit_did, EQ.LpuSectionProfile_did, Lpu_id, EQ.EvnQueue_setDate from v_EvnQueue EQ where EQ.EvnDirection_id = ED.EvnDirection_id
                    and EQ.EvnQueue_recDT is null
                    and EQ.EvnQueue_failDT is null
                    limit 1)
                    -- это костыль для того, чтобы направления у которых есть связь по EQ.EvnQueue_id = ED.EvnQueue_id, но нет реальной записи в TimetableMedService можно было отменить
                    union
                    (Select EQ.EvnQueue_id, EQ.LpuUnit_did, EQ.LpuSectionProfile_did, Lpu_id, EQ.EvnQueue_setDate from v_EvnQueue EQ
                    where (EQ.EvnQueue_id = ED.EvnQueue_id)
                    and (EQ.EvnQueue_recDT is null or TTMS.TimetableMedService_id is null)
                    and EQ.EvnQueue_failDT is null
                    limit 1)
                ) EQ on true
                -- сама служба (todo: надо ли оно)
                left join v_MedService MS on MS.MedService_id = coalesce(ED.MedService_id, EP.MedService_id)
                left join lateral (
                    select
                        ucms_usluga.UslugaComplexMedService_id
                    from v_UslugaComplexMedService ucms_usluga
                    inner join lis.v_AnalyzerTest at
                        on at.UslugaComplexMedService_id = ucms_usluga.UslugaComplexMedService_id
                    where
                        ucms_usluga.MedService_id = coalesce(ED.MedService_id, EP.MedService_id)
                        and ucms_usluga.UslugaComplex_id = UC.UslugaComplex_id
                        and ucms_usluga.UslugaComplexMedService_pid is null
                ) as UCMS on true
                left join lateral (
                    select
                    	TimetableResource_id,
                    	TimetableResource_begTime
                    from v_TimetableResource_lite TTR
                    where TTR.EvnDirection_id = ED.EvnDirection_id
                    limit 1
                ) as TTR on true
                left join v_Resource R on R.Resource_id = ED.Resource_id
                -- отделение для полки и стаца и для очереди
                left join v_LpuSection LS on LS.LpuSection_id = coalesce(ED.LpuSection_did, MS.LpuSection_id)
                -- заказанная услуга для параклиники
                --left join v_EvnUslugaPar EUP on EUP.EvnDirection_id = ED.EvnDirection_id
                -- подразделение для очереди и служб
                left join v_LpuUnit LU on coalesce(ED.LpuUnit_did,EQ.LpuUnit_did,MS.LpuUnit_id) = LU.LpuUnit_id -- todo: в ED.LpuUnit_did пусто, чего не должно быть
                -- профиль для очереди
                left join v_LpuSectionProfile LSPD on coalesce(ED.LpuSectionProfile_id,EQ.LpuSectionProfile_did,LS.LpuSectionProfile_id) = LSPD.LpuSectionProfile_id -- todo: тут на примере оказалось что почему то ED.LpuSectionProfile_id != EQ.LpuSectionProfile_did, чего не должно быть
                -- тип направления
                left join v_DirType DT on ED.DirType_id = DT.DirType_id
                -- ЛПУ
                left join v_Lpu Lpu on Lpu.Lpu_id = coalesce(ED.Lpu_did, LS.Lpu_id, MS.Lpu_id, EQ.Lpu_id)

                left join lateral (
                    select EvnUsluga_id, EvnUsluga_setDT from v_EvnUsluga
                    where EP.EvnPrescr_IsExec = 2 and UC.UslugaComplex_id is not null and EvnPrescr_id = EP.EvnPrescr_id limit 1
                ) EU on true
                left join lateral (
                    select EvnDrug_id, EvnDrug_setDT from v_EvnDrug
                    where EP.EvnPrescr_IsExec = 2 and EP.PrescriptionType_id = 5 and EvnPrescr_id = EP.EvnPrescr_id limit 1
                ) EDr on true
                left join v_EvnUslugaPar EUP on EUP.EvnDirection_id = ED.EvnDirection_id
                left join v_EvnVizitPL epl on epl.EvnVizitPL_id = EP.EvnPrescr_pid
                left join v_EvnSection es on es.EvnSection_id = EP.EvnPrescr_pid
                left join v_Evn Evn on Evn.Evn_id = EP.EvnPrescr_pid
                    and Evn.Evn_id = '500801213069384' AND Evn.Lpu_id = '13101197' AND coalesce(Evn.Evn_IsSigned,1) = 1
                left join lateral (
                    select EvnXml.EvnXml_id, XmlType.XmlType_id
                    from XmlType
                    left join EvnXml on EvnXml.XmlType_id = XmlType.XmlType_id and EvnXml.Evn_id = ED.EvnDirection_id
                    where XmlType.XmlType_id = case
                    when exists (
                        select uca.UslugaComplexAttribute_id
                        from v_UslugaComplexAttribute uca
                        inner join v_UslugaComplexAttributeType ucat on ucat.UslugaComplexAttributeType_id = uca.UslugaComplexAttributeType_id
                        and ucat.UslugaComplexAttributeType_SysNick ilike 'kt'
                        where uca.UslugaComplex_id = UC.UslugaComplex_id
                        limit 1
                    ) then 19
                    when exists (
                        select uca.UslugaComplexAttribute_id
                        from v_UslugaComplexAttribute uca
                        inner join v_UslugaComplexAttributeType ucat on ucat.UslugaComplexAttributeType_id = uca.UslugaComplexAttributeType_id
                        and ucat.UslugaComplexAttributeType_SysNick ilike 'mrt'
                        where uca.UslugaComplex_id = UC.UslugaComplex_id
                        limit 1
                    ) then 18
                    else 2 end
                    limit 1
                ) EvnXmlDir on true
            where
                EP.EvnPrescr_pid  in (500801213069384, 500801213069379, 500801213069378)
                and coalesce(EP.PrescriptionStatusType_id,Regime.PrescriptionStatusType_id,Diet.PrescriptionStatusType_id,Obs.PrescriptionStatusType_id) != 3
                and coalesce(EP.EvnPrescr_setDT,Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT) is not null
                and EP.PrescriptionType_id in (1,2,5,6,7,10,11,12,13) 
            order by
                EP.PrescriptionType_id,
                coalesce(EPT.EvnCourse_id, EPPR.EvnCourse_id),
                EP.EvnPrescr_id,
                coalesce(EP.EvnPrescr_setDT,Regime.EvnPrescrRegime_setDT,Diet.EvnPrescrDiet_setDT,Obs.EvnPrescrObserv_setDT)


        
