
DROP FUNCTION dbo.p_persondeputy_del(persondeputy_id bigint, INOUT error_code integer, INOUT error_message character varying);

DROP FUNCTION dbo.p_persondeputy_ins(server_id bigint, INOUT persondeputy_id bigint, person_id bigint, person_pid bigint, deputykind_id bigint, persondeputy_begdt timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying);

DROP FUNCTION dbo.p_persondeputy_upd(server_id bigint, INOUT persondeputy_id bigint, person_id bigint, person_pid bigint, deputykind_id bigint, persondeputy_begdt timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying);

DROP FUNCTION dbo.p_personspeccategory_ins(INOUT personspeccategory_id bigint, person_id bigint, personspeccategorytype_id bigint, personspeccategory_begdate timestamp without time zone, personspeccategory_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying);

DROP FUNCTION dbo.p_personspeccategory_upd(INOUT personspeccategory_id bigint, person_id bigint, personspeccategorytype_id bigint, personspeccategory_begdate timestamp without time zone, personspeccategory_enddate timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying);

DROP FUNCTION dbo.p_prehospdirect_del(prehospdirect_id bigint, INOUT error_code integer, INOUT error_message character varying);

DROP FUNCTION dbo.p_prehospdirect_ins(INOUT prehospdirect_id bigint, prehospdirect_code integer, prehospdirect_name character varying, prehospdirect_sysnick character varying, klcountry_id bigint, pmuser_id bigint, INOUT error_code integer, INOUT error_message character varying);

DROP FUNCTION dbo.p_prehospdirect_upd(INOUT prehospdirect_id bigint, prehospdirect_code integer, prehospdirect_name character varying, prehospdirect_sysnick character varying, klcountry_id bigint, pmuser_id bigint, INOUT error_code integer, INOUT error_message character varying);

CREATE OR REPLACE FUNCTION dbo.p_personspeccategory_upd(INOUT personspeccategory_id bigint = NULL::bigint, person_id bigint = NULL::bigint, personspeccategorytype_id bigint = NULL::bigint, personspeccategory_begdate timestamp without time zone = NULL::timestamp without time zone, personspeccategory_enddate timestamp without time zone = NULL::timestamp without time zone, personregister_id bigint = NULL::bigint, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--AUTOGEN
--project ProMed
--update dbo.personspeccategory
if pmuser_id = 0
	then pmuser_id := null; end if;

update dbo.personspeccategory
set person_id = p_personspeccategory_upd.person_id,
personspeccategorytype_id = p_personspeccategory_upd.personspeccategorytype_id,
personspeccategory_begdate = p_personspeccategory_upd.personspeccategory_begdate,
personspeccategory_enddate = p_personspeccategory_upd.personspeccategory_enddate,
personregister_id = p_personspeccategory_upd.personregister_id,
pmuser_updid = pmuser_id,
personspeccategory_upddt = now()

where personspeccategory.personspeccategory_id = p_personspeccategory_upd.personspeccategory_id;

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


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_personspeccategory_ins(INOUT personspeccategory_id bigint = NULL::bigint, person_id bigint = NULL::bigint, personspeccategorytype_id bigint = NULL::bigint, personspeccategory_begdate timestamp without time zone = NULL::timestamp without time zone, personspeccategory_enddate timestamp without time zone = NULL::timestamp without time zone, personregister_id bigint = NULL::bigint, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(personspeccategory_id, 0) = 0
then 
	insert into dbo.personspeccategory(person_id, personspeccategorytype_id, personspeccategory_begdate, personspeccategory_enddate, personregister_id, pmuser_insid, pmuser_updid, personspeccategory_insdt, personspeccategory_upddt)
	values ( person_id, personspeccategorytype_id, personspeccategory_begdate, personspeccategory_enddate, personregister_id, pmuser_id, pmuser_id, now(), now())
	returning personspeccategory.personspeccategory_id into p_personspeccategory_ins.personspeccategory_id;
else
	insert into dbo.personspeccategory(personspeccategory_id, person_id, personspeccategorytype_id, personspeccategory_begdate, personspeccategory_enddate, personregister_id, pmuser_insid, pmuser_updid, personspeccategory_insdt, personspeccategory_upddt)
	values (personspeccategory_id, person_id, personspeccategorytype_id, personspeccategory_begdate, personspeccategory_enddate, personregister_id, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_prehospdirect_del(prehospdirect_id bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--autogen
--project promed
--delete from dbo.prehospdirect
delete from dbo.prehospdirect
where prehospdirect.prehospdirect_id = p_prehospdirect_del.prehospdirect_id;

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


end; $$;

CREATE OR REPLACE FUNCTION dbo.p_prehospdirect_upd(INOUT prehospdirect_id bigint = NULL::bigint, prehospdirect_code integer = NULL::integer, prehospdirect_name character varying = NULL::character varying, prehospdirect_sysnick character varying = NULL::character varying, klcountry_id bigint = NULL::bigint, prehospdirect_begdate timestamp without time zone = NULL::timestamp without time zone, prehospdirect_enddate timestamp without time zone = NULL::timestamp without time zone, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--AUTOGEN
--project ProMed
--update dbo.prehospdirect
if pmuser_id = 0
	then pmuser_id := null; end if;

update dbo.prehospdirect
set prehospdirect_code = p_prehospdirect_upd.prehospdirect_code,
prehospdirect_name = p_prehospdirect_upd.prehospdirect_name,
prehospdirect_sysnick = p_prehospdirect_upd.prehospdirect_sysnick,
klcountry_id = p_prehospdirect_upd.klcountry_id,
prehospdirect_begdate = p_prehospdirect_upd.prehospdirect_begdate,
prehospdirect_enddate = p_prehospdirect_upd.prehospdirect_enddate,
pmuser_updid = pmuser_id,
prehospdirect_upddt = now()

where prehospdirect.prehospdirect_id = p_prehospdirect_upd.prehospdirect_id;

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


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_prehospdirect_ins(INOUT prehospdirect_id bigint = NULL::bigint, prehospdirect_code integer = NULL::integer, prehospdirect_name character varying = NULL::character varying, prehospdirect_sysnick character varying = NULL::character varying, klcountry_id bigint = NULL::bigint, prehospdirect_begdate timestamp without time zone = NULL::timestamp without time zone, prehospdirect_enddate timestamp without time zone = NULL::timestamp without time zone, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(prehospdirect_id, 0) = 0
then 
	insert into dbo.prehospdirect(prehospdirect_code, prehospdirect_name, prehospdirect_sysnick, klcountry_id, prehospdirect_begdate, prehospdirect_enddate, pmuser_insid, pmuser_updid, prehospdirect_insdt, prehospdirect_upddt)
	values ( prehospdirect_code, prehospdirect_name, prehospdirect_sysnick, klcountry_id, prehospdirect_begdate, prehospdirect_enddate, pmuser_id, pmuser_id, now(), now())
	returning prehospdirect.prehospdirect_id into p_prehospdirect_ins.prehospdirect_id;
else
	insert into dbo.prehospdirect(prehospdirect_id, prehospdirect_code, prehospdirect_name, prehospdirect_sysnick, klcountry_id, prehospdirect_begdate, prehospdirect_enddate, pmuser_insid, pmuser_updid, prehospdirect_insdt, prehospdirect_upddt)
	values (prehospdirect_id, prehospdirect_code, prehospdirect_name, prehospdirect_sysnick, klcountry_id, prehospdirect_begdate, prehospdirect_enddate, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;

CREATE OR REPLACE FUNCTION dbo.getrecomendationbydatenew(in_morbustype_id bigint, in_person_id bigint, in_sex_id integer, in_bskregistry_id bigint, in_bskobservrecomendationtype_id integer) RETURNS TABLE(bskobservrecomendation_id integer, bskobservrecomendation_text character varying, bskobservrecomendationtype_id integer, answer character varying)
    LANGUAGE plpgsql
    AS $$
declare
	v_BirthDay date = (select Person_BirthDay from dbo.v_PersonState where Person_id = in_Person_id);
	v_Age int = dbo.Age(v_BirthDay, current_date);

begin

	drop table if exists t_tempRegistryData;
	create temp table t_tempRegistryData(
		BSKRegistryData_id bigint,
		BSKRegistryData_data varchar,
		BSKUnits_name varchar,
		BSKObservElementFormat_id int,
		BSKObservElement_id bigint,
		answer varchar,
		BSKObservElementValues_id bigint
	);

    insert into t_tempRegistryData
    select
		 RD.BSKRegistryData_id
		,coalesce(RD.BSKRegistryData_data,RD.BSKRegistryData_AnswerText,cast(RD.BSKRegistryData_AnswerInt as varchar),cast(RD.BSKRegistryData_Answerfloat as varchar)) BSKRegistryData_data
		,coalesce(RD.BSKUnits_name,U.Unit_Name) BSKUnits_name
		,E.BSKObservElementFormat_id
		,E.BSKObservElement_id
		,'<b>' || BSKObservElement_name || ':</b> ' || RD.BSKRegistryData_data || ' ' || BSKUnits_name as answer
        ,RD.BSKObservElementValues_id
    from dbo.BSKRegistryData as RD
    left join dbo.BSKRegistry as R on R.BSKRegistry_id = RD.BSKRegistry_id
    left join dbo.BSKObservElement as E on E.BSKObservElement_id = RD.BSKObservElement_id
    left join dbo.Unit U on U.Unit_id = E.Unit_id
    where R.Person_id = in_Person_id and R.BSKRegistry_id = in_bskregistry_id;

	drop table if exists t_RecomendationList;
	create temp table t_RecomendationList(
		BSKObservRecomendation_id int,
		BSKObservRecomendation_text varchar,
		BSKObservRecomendationType_id int,
		answer varchar
	);

	-- Ответы из combobox
	insert into t_RecomendationList	(BSKObservRecomendation_id, BSKObservRecomendation_text, BSKObservRecomendationType_id, answer)
    select
       t.BSKObservRecomendation_id,
       ' - ' || t.BSKObservRecomendation_text as BSKObservRecomendation_text,
       t.BSKObservRecomendationType_id
       ,tRD.answer
    from t_tempRegistryData as tRD
    left join lateral (
		select
		   b.BSKObservRecomendation_id,
		   b.BSKObservRecomendation_text,
		   b.BSKObservRecomendationType_id
		from dbo.BSKObservRecomendation as b
		join (
			select RL.BSKObservRecomendation_id
			from dbo.BSKObservRecomendationLink RL
			left join dbo.BSKObservElementValues EV on RL.BSKObservElementValues_id =  EV.BSKObservElementValues_id
			left join dbo.BSKObservElement E on E.BSKObservElement_id = EV.BSKObservElement_id
			where  E.BSKObservElement_deleted = 1
			and EV.BSKObservElementValues_deleted = 1
			and E.BSKObservElement_id = tRD.BSKObservElement_id
			and (EV.BSKObservElementValues_data = tRD.BSKRegistryData_data or EV.BSKObservElementValues_id = tRD.BSKObservElementValues_id)
			and RL.BSKObservRecomendationLink_deleted = 1
			and E.BSKObservElementFormat_id in (1,8)
			group by RL.BSKObservRecomendation_id
		) as q on q.BSKObservRecomendation_id = b.BSKObservRecomendation_id
    ) as t on true
    where t.BSKObservRecomendationType_id = in_BSKObservRecomendationType_id;

	-- Данные из БД
	drop table if exists t_Recomendations_ids;
	create temp table t_Recomendations_ids(id bigint);

    insert into t_Recomendations_ids(id)
    select
        --хлестерин
		case when BSKObservElement_id = 33 then
			case when in_BSKObservRecomendationType_id = 1 then 30 else 57 end
		--диабет
		     when BSKObservElement_id = 34 then
				case when in_BSKObservRecomendationType_id = 1 then 31 else 62 end
		--заболевание почек
		     when BSKObservElement_id = 35 then
				case when in_BSKObservRecomendationType_id = 1 then 32 else 63 end
		--щитовидка
		     when BSKObservElement_id = 36 then
				case when in_BSKObservRecomendationType_id = 1 then 33 else 63 end
		--аутоимуннае заболевания
		     when BSKObservElement_id = 37 then
				case when in_BSKObservRecomendationType_id = 1 then 34 else 63 end
		--неалкогольная болезнь печени
		     when BSKObservElement_id = 43 then
				case when in_BSKObservRecomendationType_id = 1 then 35 else 64 end
		--камни в желчном пузыре
		     when BSKObservElement_id = 44 then
				case when in_BSKObservRecomendationType_id = 1 then 35 else 65
				end
		end as id
    from t_tempRegistryData as tRD
    where tRD.BSKObservElementFormat_id in (7,16)
    and tRD.BSKRegistryData_data != 'Нет';

    --ручной ввод
    insert into t_Recomendations_ids(id)
	select t.BSKObservRecomendation_id
	from dbo.BSKObservRecomendation as t
	where t.BSKObservRecomendation_id in(
		select
		    -- Объём талии мужчины
			case when BSKObservElement_id = 109 and BSKRegistryData_data > '94' and v_Age >=16 and in_Sex_id = 1
				 then
					case when in_BSKObservRecomendationType_id = 1 then 155 else 78 end
		    -- Объём талии женщины
			     when BSKObservElement_id = 109 and BSKRegistryData_data > '80' and v_Age >=16 and in_Sex_id = 2
				 then
					case when in_BSKObservRecomendationType_id = 1 then 155 else 144 end
			-- Индекс массы тела
			     when BSKObservElement_id = 110 and BSKRegistryData_data > '30' and v_Age >=16 and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 156 else 79 end
			--ИБС Индекс массы тела Объём талии
			     when BSKObservElement_id = 320 and BSKRegistryData_data >= '25' and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 41 else 158 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data < '94' and in_Sex_id in (1)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 174 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data < '80' and in_Sex_id in (2)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 174 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data between '94' and '101' and in_Sex_id in (1)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 175 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data between '81' and '87' and in_Sex_id in (2)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 175 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data >= '102' and in_Sex_id in (1)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 233 end
			     when BSKObservElement_id = 321 and BSKRegistryData_data >= '88' and in_Sex_id in (2)
				 then
					case when in_BSKObservRecomendationType_id = 2 then 233 end
		    -- Систолическое давление
		         -- Правая рука
			     when BSKObservElement_id = 50 and BSKRegistryData_data > '140' and v_Age >=16 and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 148 else 81 end
				 -- Левая рука
			     when BSKObservElement_id = 50 and BSKRegistryData_data > '159' and v_Age >=16 and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 148 else 81 end
		    -- Диастолическое давление
		         -- Правая рука
			     when BSKObservElement_id = 54 and BSKRegistryData_data > '99' and v_Age >=16 and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 149 else 81 end
				 -- Левая рука
			     when BSKObservElement_id = 55 and BSKRegistryData_data > '99' and v_Age >=16 and in_Sex_id in (1,2)
				 then
					case when in_BSKObservRecomendationType_id = 1 then 149 else 81 end
			-- Липопротеины низкой плотности
			     when BSKObservElement_id = 88 and BSKRegistryData_data >= '4.9' and in_Sex_id in (1,2) and v_Age > 16
				 then
				    case when in_BSKObservRecomendationType_id = 1 then 55 else 92 end
			     when BSKObservElement_id = 88 and in_Sex_id in (1,2) and v_Age > 2 and v_Age < 16
				 then
					case when BSKRegistryData_data >= '4.0' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 91 end
						 when BSKRegistryData_data >= '3.0' then
							case when in_BSKObservRecomendationType_id = 1 then 150 else 90 end
						 when BSKRegistryData_data >= '2.85' then
							case when in_BSKObservRecomendationType_id = 1 then 150 else 89 end
				    end
			-- Общий холестирин
			     when BSKObservElement_id = 89 and BSKRegistryData_data > '94' and v_Age>2 and v_Age<16 and in_Sex_id in(1,2)
				 then
					case when BSKRegistryData_data > '6.7' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 92 end
						 when BSKRegistryData_data >= '4.4' then
							case when in_BSKObservRecomendationType_id = 1 then 151 else 93 end
					end
			     when BSKObservElement_id = 89 and BSKRegistryData_data > '94' and v_Age>16 and in_Sex_id in(1,2)
				 then
					case when BSKRegistryData_data > '7.5' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 95 end
						 when BSKRegistryData_data >= '5.0' then
							case when in_BSKObservRecomendationType_id = 1 then 151 else 94 end
					end
			     when BSKObservElement_id = 333 and BSKRegistryData_data <= '4'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 205 else 244 end
			     when BSKObservElement_id = 333 and BSKRegistryData_data > '4'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 198 else 245 end
			--Липопротеины низкой плотности
			     when BSKObservElement_id = 334 and BSKRegistryData_data <= '1.8'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 204 else 246 end
			     when BSKObservElement_id = 334 and BSKRegistryData_data > '1.8'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 199 else 247 end
			--Триглицериды
			     when BSKObservElement_id = 336 and BSKRegistryData_data <= '1.7'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 203 else 248 end
			     when BSKObservElement_id = 336 and BSKRegistryData_data > '1.7'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 200 else 249 end
			--Глюкоза, капиллярная кровь
			     when BSKObservElement_id = 337 and BSKRegistryData_data <= '5.5'
				 then
					250
			     when BSKObservElement_id = 337 and BSKRegistryData_data > '5.5'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 201 else 251 end
			--Глюкоза, венозная кровь
			     when BSKObservElement_id = 338 and BSKRegistryData_data <= '6.1'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 202 else 252 end
			     when BSKObservElement_id = 338 and BSKRegistryData_data > '6.1'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 207 else 253 end
			--Глюкоза в крови через 2 часа после перорального глюкозо-толерантного теста
			     when BSKObservElement_id = 339 and BSKRegistryData_data < '7.8'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 208 else 254 end
			     when BSKObservElement_id = 339 and BSKRegistryData_data between '7.8' and '11.09'
				 then
					case when in_BSKObservRecomendationType_id = 2 then 255 end
			     when BSKObservElement_id = 339 and BSKRegistryData_data >= '11.1'
				 then
					case when in_BSKObservRecomendationType_id = 1 then 209 else 256 end
			-- Липопротеины высокой плотности
				 when BSKObservElement_id = 90 and v_Age>=16  and in_Sex_id = 1
				      and (BSKRegistryData_data < '0.7' or BSKRegistryData_data>'1.6') then
					case when in_BSKObservRecomendationType_id = 1 then 152 else 96 end
				 when BSKObservElement_id = 90 and v_Age>=16  and in_Sex_id = 2
				      and (BSKRegistryData_data < '0.9' or BSKRegistryData_data>'1.6') then
					case when in_BSKObservRecomendationType_id = 1 then 152 else 96 end
				 when BSKObservElement_id = 90 and v_Age>2 and v_Age<16  and in_Sex_id in(1,2)
				      and (BSKRegistryData_data < '0.9' or BSKRegistryData_data>'1.6') then
					case when in_BSKObservRecomendationType_id = 1 then 152 else 96 end
		    -- Триглецириды
		    	 when BSKObservElement_id = 91 and v_Age>2 and v_Age<16  and in_Sex_id in(1,2) and BSKRegistryData_data>='0.85' then
		    		 case when in_BSKObservRecomendationType_id = 1 then 153 else 97 end
		    	 when BSKObservElement_id = 91 and v_Age>16  and in_Sex_id in(1,2) and BSKRegistryData_data>='1.7' then
		    		 case when in_BSKObservRecomendationType_id = 1 then 153 else 98 end
		    -- Апо-100
		    	 when BSKObservElement_id = 92 and v_Age>2 and v_Age<16  and in_Sex_id in(1,2) then
		    	     case when BSKUnits_name = 'ммоль/л' and BSKRegistryData_data >= round(90/40.0,2)::varchar then
		    				case when in_BSKObservRecomendationType_id = 1 then 154 else 99 end
		    		      when BSKUnits_name = 'мг.дл' and BSKRegistryData_data >= '90' then
		    		      	 case when in_BSKObservRecomendationType_id = 1 then 154 else 99 end
		    		 end
		    	 when BSKObservElement_id = 92 and v_Age>16  and in_Sex_id in(1,2) then
		    	     case when BSKUnits_name = 'ммоль/л' and BSKRegistryData_data >= round(100/40.0,2)::varchar then
		    				case when in_BSKObservRecomendationType_id = 1 then 154 else 99 end
		    		      when BSKUnits_name = 'мг.дл' and BSKRegistryData_data >= '100' then
		    		      	 case when in_BSKObservRecomendationType_id = 1 then 154 else 99 end
		    		 end
            -- Артериальная гипертензия 88
                 -- Индекс массы тела
			     when BSKObservElement_id = 210  and in_Sex_id in (1,2) then
			         case when BSKRegistryData_data > '19' and  BSKRegistryData_data < '24.9' then
						       case when in_BSKObservRecomendationType_id = 1 then 163 else 0 end
			              when BSKRegistryData_data > '25' and  BSKRegistryData_data < '30' then
						       case when in_BSKObservRecomendationType_id = 1 then 164 else 279 end
			              when BSKRegistryData_data > '30' and  BSKRegistryData_data < '34.9' then
						       case when in_BSKObservRecomendationType_id = 1 then 165 else 279 end
			              when BSKRegistryData_data > '35' and  BSKRegistryData_data < '39.9' then
						       case when in_BSKObservRecomendationType_id = 1 then 166 else 279 end
			              when BSKRegistryData_data > '40' then
						       case when in_BSKObservRecomendationType_id = 1 then 167 else 279 end
				 else 0
				 end
                 -- Окружность талии
			     when BSKObservElement_id = 211  and in_Sex_id in (1) then
			         case when BSKRegistryData_data < '94' then
						       case when in_BSKObservRecomendationType_id = 1 then 0 else 174 end
			              when BSKRegistryData_data >= '94' and  BSKRegistryData_data < '101' then
						       case when in_BSKObservRecomendationType_id = 1 then 168 else 175 end
			              when BSKRegistryData_data > '102' then
						       case when in_BSKObservRecomendationType_id = 1 then 168 else 233 end
				 else 0
				 end
			     when BSKObservElement_id = 211  and in_Sex_id in (2) then
			         case when BSKRegistryData_data < '80' then
						       case when in_BSKObservRecomendationType_id = 1 then 0 else 174 end
			              when BSKRegistryData_data >= '80' and  BSKRegistryData_data < '87' then
						       case when in_BSKObservRecomendationType_id = 1 then 168 else 175 end
			              when BSKRegistryData_data > '88' then
						       case when in_BSKObservRecomendationType_id = 1 then 168 else 233 end
				 else 0
				 end
		    -- Конец арт. гипертензии ----------------

		    -- Апо А1	 93
		    -- не учавствует

		    -- Липопротеин (а)
		    	 when BSKObservElement_id = 94 and v_Age>16  and in_Sex_id in(1,2) then
		    	     case when BSKUnits_name = 'ммоль/л' and BSKRegistryData_data >= round(50/40.0,2)::varchar then
		    				case when in_BSKObservRecomendationType_id = 1 then 55 else 101 end
		    		      when BSKUnits_name = 'мг.дл' and BSKRegistryData_data >= '50' then
		    		      	 case when in_BSKObservRecomendationType_id = 1 then 55 else 101 end
		    		 end
		    --СРБ ВЧ
				 when BSKObservElement_id = 95 and v_Age>16  and in_Sex_id in(1,2) and BSKRegistryData_data > '2' then
					case when in_BSKObservRecomendationType_id = 1 then 50 else 106 end
			-- Скорость клубочковой фильтрации
				 when BSKObservElement_id = 96 and v_Age>16  and in_Sex_id in(1,2) and BSKRegistryData_data < '30' then
					case when in_BSKObservRecomendationType_id = 1 then 140 else 107 end
		    -- МАУ
		    	 when BSKObservElement_id = 97 and v_Age>16  and in_Sex_id in(1,2) then
		    	     case when BSKUnits_name = 'МГ/ммоль' and BSKRegistryData_data >= '3.4' then
		    				case when in_BSKObservRecomendationType_id = 1 then 140 else 108 end
		    		      when BSKUnits_name = 'Мг/24 часа' and BSKRegistryData_data >= '30' then
		    		      	 case when in_BSKObservRecomendationType_id = 1 then 140 else 108 end
		    		 end
		    -- Соотношение микро... к креатинину в моче
				  when BSKObservElement_id = 98 and v_Age>16  and in_Sex_id in(1,2) and BSKRegistryData_data >= '30' then
		    		case when in_BSKObservRecomendationType_id = 1 then 52 else 146 end
		    -- Глюкоза капилярная
		    	  when BSKObservElement_id = 99 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '5.6' and BSKRegistryData_data < '7' then
		    		case when in_BSKObservRecomendationType_id = 1 then 54 else 109 end
		    	  when BSKObservElement_id = 99 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '7' then
		    		case when in_BSKObservRecomendationType_id = 1 then 54 else 110 end
		    -- Глюкоза венозная
		    	  when BSKObservElement_id = 100 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '7' then
		    		case when in_BSKObservRecomendationType_id = 1 then 53 else 109 end
		    	  when BSKObservElement_id = 100 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '6.1' then
		    		case when in_BSKObservRecomendationType_id = 1 then 54 else 110 end
		    -- Через 2 часа капилярная
		    	  when BSKObservElement_id = 101 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '11.1' then
		    		case when in_BSKObservRecomendationType_id = 1 then 53 else 109 end
		    	  when BSKObservElement_id = 101 and v_Age>2  and in_Sex_id in(1,2)
		    		   and BSKRegistryData_data >= '7.8' then
		    		case when in_BSKObservRecomendationType_id = 1 then 54 else 110 end
		    -- Интима медиа
				  when BSKObservElement_id = 102 and v_Age>=40 and v_Age<50 and in_Sex_id = 1 then
					case when BSKRegistryData_data > '1.3' then
							case when in_BSKObservRecomendationType_id = 1 then 56 else 113 end
						 when BSKRegistryData_data > '0.8' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 113 end
						end
				  when BSKObservElement_id = 102 and v_Age>50 and in_Sex_id = 1 then
					case when BSKRegistryData_data > '1.3' then
							case when in_BSKObservRecomendationType_id = 1 then 56 else 113 end
						 when BSKRegistryData_data > '0.9' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 113 end
						end
				  when BSKObservElement_id = 102 and v_Age>=40 and v_Age<60 and in_Sex_id =2 then
					case when BSKRegistryData_data > '1.3' then
							case when in_BSKObservRecomendationType_id = 1 then 56 else 113 end
						 when BSKRegistryData_data > '0.8' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 113 end
						end
				  when BSKObservElement_id = 102 and v_Age>60 and in_Sex_id = 2 then
					case when BSKRegistryData_data > '1.3' then
							case when in_BSKObservRecomendationType_id = 1 then 56 else 113 end
						 when BSKRegistryData_data > '0.9' then
							case when in_BSKObservRecomendationType_id = 1 then 55 else 113 end
						end
			-- Индекс Агатсона
				   when BSKObservElement_id = 102 and v_Age>16 and in_Sex_id in (1,2)  then
					case when in_Sex_id = 1 and BSKRegistryData_data>'100' then
							case when in_BSKObservRecomendationType_id = 1 then 26 else 118 end
						 when in_Sex_id = 1 and BSKRegistryData_data>'11' then
							case when in_BSKObservRecomendationType_id = 1 then 43 else 117 end
					     when in_Sex_id = 2 and BSKRegistryData_data>'100' then
							case when in_BSKObservRecomendationType_id = 1 then 26 else 118 end
						 when in_Sex_id = 2 and BSKRegistryData_data>'11' then
							case when in_BSKObservRecomendationType_id = 1 then 27 else 121 end
					end
			end as id
		from t_tempRegistryData as tRD
	);
    --
    -- результирующий момент
    insert into t_RecomendationList	(BSKObservRecomendation_id, BSKObservRecomendation_text, BSKObservRecomendationType_id, answer)
    select
       t.BSKObservRecomendation_id,
       ' - ' || t.BSKObservRecomendation_text as BSKObservRecomendation_text,
       t.BSKObservRecomendationType_id,
       null as answer
    from dbo.BSKObservRecomendation as t
    where t.BSKObservRecomendation_id in (select id from t_Recomendations_ids)
    	and t.BSKObservRecomendationType_id = in_BSKObservRecomendationType_id;

    return query
	select
		t.BSKObservRecomendation_id,
		t.BSKObservRecomendation_text,
		t.BSKObservRecomendationType_id,
		t.answer
	from t_RecomendationList as t;

END;
$$;

CREATE OR REPLACE FUNCTION dbo.p_getrecomendationbydatenew(p_morbustype_id bigint, p_person_id bigint, p_sex_id integer, p_bskregistry_id bigint, p_bskobservrecomendationtype_id integer) RETURNS TABLE(bskobservrecomendation_id integer, bskobservrecomendation_text character varying, bskobservrecomendationtype_id integer, answer character varying)
    LANGUAGE plpgsql
    AS $$
begin
	return query(select * from dbo.getrecomendationbydatenew
(
                p_MorbusType_id,
                p_Person_id,
                p_Sex_id,
                p_bskregistry_id,
                p_BSKObservRecomendationType_id
));
END;
$$;

CREATE OR REPLACE FUNCTION dbo.p_documentdeputy_del(documentdeputy_id bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--autogen
--project promed
--delete from dbo.documentdeputy
delete from dbo.documentdeputy
where documentdeputy.documentdeputy_id = p_documentdeputy_del.documentdeputy_id;

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


end; $$;

CREATE OR REPLACE FUNCTION dbo.p_documentdeputy_upd(INOUT documentdeputy_id bigint = NULL::bigint, documentauthority_id bigint = NULL::bigint, documentdeputy_ser bigint = NULL::bigint, documentdeputy_num bigint = NULL::bigint, documentdeputy_issue character varying = NULL::character varying, documentdeputy_begdate bytea = NULL::bytea, documentdeputy_enddate bytea = NULL::bytea, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--AUTOGEN
--project ProMed
--update dbo.documentdeputy
if pmuser_id = 0
	then pmuser_id := null; end if;

update dbo.documentdeputy
set documentauthority_id = p_documentdeputy_upd.documentauthority_id,
documentdeputy_ser = p_documentdeputy_upd.documentdeputy_ser,
documentdeputy_num = p_documentdeputy_upd.documentdeputy_num,
documentdeputy_issue = p_documentdeputy_upd.documentdeputy_issue,
documentdeputy_begdate = p_documentdeputy_upd.documentdeputy_begdate,
documentdeputy_enddate = p_documentdeputy_upd.documentdeputy_enddate,
pmuser_updid = pmuser_id,
documentdeputy_upddt = now()

where documentdeputy.documentdeputy_id = p_documentdeputy_upd.documentdeputy_id;

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


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_documentdeputy_ins(INOUT documentdeputy_id bigint = NULL::bigint, documentauthority_id bigint = NULL::bigint, documentdeputy_ser bigint = NULL::bigint, documentdeputy_num bigint = NULL::bigint, documentdeputy_issue character varying = NULL::character varying, documentdeputy_begdate bytea = NULL::bytea, documentdeputy_enddate bytea = NULL::bytea, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(documentdeputy_id, 0) = 0
then 
	insert into dbo.documentdeputy(documentauthority_id, documentdeputy_ser, documentdeputy_num, documentdeputy_issue, documentdeputy_begdate, documentdeputy_enddate, pmuser_insid, pmuser_updid, documentdeputy_insdt, documentdeputy_upddt)
	values ( documentauthority_id, documentdeputy_ser, documentdeputy_num, documentdeputy_issue, documentdeputy_begdate, documentdeputy_enddate, pmuser_id, pmuser_id, now(), now())
	returning documentdeputy.documentdeputy_id into p_documentdeputy_ins.documentdeputy_id;
else
	insert into dbo.documentdeputy(documentdeputy_id, documentauthority_id, documentdeputy_ser, documentdeputy_num, documentdeputy_issue, documentdeputy_begdate, documentdeputy_enddate, pmuser_insid, pmuser_updid, documentdeputy_insdt, documentdeputy_upddt)
	values (documentdeputy_id, documentauthority_id, documentdeputy_ser, documentdeputy_num, documentdeputy_issue, documentdeputy_begdate, documentdeputy_enddate, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_persondeputy_del(persondeputy_id bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--autogen
--project promed
--delete from dbo.persondeputy
delete from dbo.persondeputy
where persondeputy.persondeputy_id = p_persondeputy_del.persondeputy_id;

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


end; $$;

CREATE OR REPLACE FUNCTION dbo.p_persondeputy_upd(server_id bigint = NULL::bigint, INOUT persondeputy_id bigint = NULL::bigint, person_id bigint = NULL::bigint, person_pid bigint = NULL::bigint, deputykind_id bigint = NULL::bigint, persondeputy_begdt timestamp without time zone = NULL::timestamp without time zone, documentdeputy_id bigint = NULL::bigint, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

--AUTOGEN
--project ProMed
--update dbo.persondeputy
if pmuser_id = 0
	then pmuser_id := null; end if;

update dbo.persondeputy
set server_id = p_persondeputy_upd.server_id,
person_id = p_persondeputy_upd.person_id,
person_pid = p_persondeputy_upd.person_pid,
deputykind_id = p_persondeputy_upd.deputykind_id,
persondeputy_begdt = p_persondeputy_upd.persondeputy_begdt,
documentdeputy_id = p_persondeputy_upd.documentdeputy_id,
pmuser_updid = pmuser_id,
persondeputy_upddt = now()

where persondeputy.persondeputy_id = p_persondeputy_upd.persondeputy_id;

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


END; $$;

CREATE OR REPLACE FUNCTION dbo.p_persondeputy_ins(server_id bigint = NULL::bigint, INOUT persondeputy_id bigint = NULL::bigint, person_id bigint = NULL::bigint, person_pid bigint = NULL::bigint, deputykind_id bigint = NULL::bigint, persondeputy_begdt timestamp without time zone = NULL::timestamp without time zone, documentdeputy_id bigint = NULL::bigint, pmuser_id bigint = NULL::bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(persondeputy_id, 0) = 0
then 
	insert into dbo.persondeputy(server_id, person_id, person_pid, deputykind_id, persondeputy_begdt, documentdeputy_id, pmuser_insid, pmuser_updid, persondeputy_insdt, persondeputy_upddt)
	values (server_id,  person_id, person_pid, deputykind_id, persondeputy_begdt, documentdeputy_id, pmuser_id, pmuser_id, now(), now())
	returning persondeputy.persondeputy_id into p_persondeputy_ins.persondeputy_id;
else
	insert into dbo.persondeputy(server_id, persondeputy_id, person_id, person_pid, deputykind_id, persondeputy_begdt, documentdeputy_id, pmuser_insid, pmuser_updid, persondeputy_insdt, persondeputy_upddt)
	values (server_id, persondeputy_id, person_id, person_pid, deputykind_id, persondeputy_begdt, documentdeputy_id, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;

DROP FUNCTION dbo.evnparcard_oborud(character varying);

CREATE OR REPLACE FUNCTION dbo.getbsktimeforckvkag(person_id bigint, type_ integer) RETURNS character varying
    LANGUAGE plpgsql
    AS $$
declare
	BSKRegistryData_data varchar(500) = '';
    numA int;
    setdt timestamp = null; -- Дата госпитализации
    check_ int = 0; -- ЧКВ/КАГ нет
    p_BSKObservElement_id bigint;
    dt timestamp; -- дата выполнения ЧКВ
    --Разница времени
    time_ varchar(10) = '';
    time_hour varchar(10) = '';
    time_minute varchar(10) = '';
    factor_cursor REFCURSOR;
BEGIN
	IF (type_ = 0)
    	THEN p_BSKObservElement_id = 302;
        ELSE p_BSKObservElement_id = 413;
    END IF;

    --в цикле
    open factor_cursor for
    	SELECT
        	case
            	when rd.BSKObservElement_id = 276 then 1 --Дата госпитализации
                when  rd.BSKObservElement_id = p_BSKObservElement_id then 2 END numA, --ЧКВ/КАГ
            case
            	when dbo.isdate(coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data)) = 0 then NULL else coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data) end BSKRegistryData_data
        from dbo.BSKRegistry r
        inner join dbo.BSKRegistryData rd on r.BSKRegistry_id = rd.BSKRegistry_id
        inner join BSKObservElement BE on BE.BSKObservElement_id = rd.BSKObservElement_id
        left join BSKObservElementGroup BEG on BEG.BSKObservElementGroup_id = BE.BSKObservElementGroup_id
        where (1=1)
        	and r.MorbusType_id = 19
            and r.Person_id = GetBSKTimeForCKVKAG.Person_id::bigint
            and rd.BSKObservElement_id in (p_BSKObservElement_id,276)
            and EXISTS (
            	select rdd.BSKRegistry_id
                from  dbo.BSKRegistryData rdd
                inner join BSKObservElement BE on BE.BSKObservElement_id = rdd.BSKObservElement_id
                left join BSKObservElementGroup BEG on BEG.BSKObservElementGroup_id = BE.BSKObservElementGroup_id
                where r.BSKRegistry_id = rdd.BSKRegistry_id
                and BEG.BSKObservElementGroup_id = 32 -- анкеты из КВС
            )
        order by r.BSKRegistry_id desc,numA
        limit 2;

        LOOP
        	FETCH FROM factor_cursor INTO numA, BSKRegistryData_data;
	        exit when not found;

            IF (numA = 1)
            	THEN setdt = BSKRegistryData_data;
            END IF;

            IF (numA = 2 and BSKRegistryData_data is not null)
            	THEN BEGIN
                	check_ = 1;
                    dt = BSKRegistryData_data;
            	END;
            END IF;

        END LOOP;
    CLOSE factor_cursor;

    IF(check_ = 1)
    	THEN
        	--если чкв/каг сделали в течении 60 мин
            IF (dt between setdt and dateadd('minute', 60,  setdt))
            	THEN return 'true';
                ELSE return 'false';
            END IF;
	END IF;

    IF (dateadd('minute', 60, setdt) < dbo.getdate())
    	THEN return 'false';
    END IF;

    time_ = to_char(dateadd('minute', 60, setdt) - dbo.getdate(), 'hh24:mi');

    --формируем формат для отображения
    time_hour = substring(time_, 2, 1);
    time_minute = substring(time_, 4, 2);

    IF (time_hour = '0')
    	THEN time_hour = '';
        ELSE time_hour = time_hour || ' ч ';
    END IF;

    IF (time_minute = '00')
    	THEN time_minute = '';
        ELSE
        	BEGIN
            	IF (substring(time_minute, 1, 1) = '0')
                	THEN time_minute = substring(time_minute, 2, 1) || ' мин ';
                    ELSE time_minute = time_minute || ' мин ';
                END IF;
            END;
    END IF;

return time_hour || time_minute;

end

$$;

CREATE OR REPLACE FUNCTION dbo.getbsktimefortlt(person_id bigint) RETURNS character varying
    LANGUAGE plpgsql
    AS $$
declare
	BSKRegistryData_data varchar(500) = '';
    numA int;
    diag int = 0;
    setdt timestamp = null; -- Дата/время начала болевых симптомов
    hospitaldt timestamp = null; -- дата госпитализации
    placecalldt timestamp = null; -- Дата/время прибытия на место вызова
    failTLT varchar(100) = null;--Причина отказа от ТЛТ в Карте вызова
    TLT int = 0;
    TLTsmp int = 0;
    --костыль
    count varchar; --если в строке содерится 3 символа "-" для даты
    position int;
    --Разница времени
    time_ varchar(10) = '';
    time_hour varchar(10) = '';
    time_minute varchar(10) = '';
    --в цикле
    factor_cursor REFCURSOR;
    SMP_cursor REFCURSOR;
BEGIN
	open factor_cursor for
    	select
        	case
            	when rd.BSKObservElement_id = 300 then 1 --Основной дигноз
                when rd.BSKObservElement_id = 411 then 2 --Диагноз приёмного отделения
                when rd.BSKObservElement_id = 410 then 3 --Диагноз направившего учреждения
                when rd.BSKObservElement_id = 274 then 4 --ТЛТ
                when rd.BSKObservElement_id = 271 then 5 -- Дата/время начала болевых симптомов
                when rd.BSKObservElement_id = 276 then 6 end numA, --Дата госпитализации
            case
            	when rd.BSKObservElement_id in (274,271,276) and dbo.isdate(coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data)) = 0 then NULL else coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data) end BSKRegistryData_data
        from dbo.BSKRegistry r
        inner join dbo.BSKRegistryData rd on r.BSKRegistry_id = rd.BSKRegistry_id
        where r.Person_id = GetBSKTimeForTLT.Person_id::bigint
        	and r.MorbusType_id = 19
            and rd.BSKObservElement_id in (300,411,410, 271, 274, 276)
            and EXISTS (
            	select rdd.BSKRegistry_id
                from  dbo.BSKRegistryData rdd
                inner join dbo.BSKObservElement BE on BE.BSKObservElement_id = rdd.BSKObservElement_id
                left join dbo.BSKObservElementGroup BEG on BEG.BSKObservElementGroup_id = BE.BSKObservElementGroup_id
                where r.BSKRegistry_id = rdd.BSKRegistry_id
                	and BEG.BSKObservElementGroup_id = 32 -- анкеты из КВС
                )
        order by r.BSKRegistry_id desc,numA
        limit 6;
        LOOP
        FETCH FROM factor_cursor INTO numA, BSKRegistryData_data;
        exit when not found;
            IF ((BSKRegistryData_data like '%I21.0%'
                or BSKRegistryData_data like '%I21.1%'
                or BSKRegistryData_data like '%I21.2%'
                or BSKRegistryData_data like '%I21.3%'
                or BSKRegistryData_data like '%I21.9%'
                or BSKRegistryData_data like '%I22.0%'
                or BSKRegistryData_data like '%I22.1%'
                or BSKRegistryData_data like '%I22.8%'
                or BSKRegistryData_data like '%I22.9%') and numA = 1 and diag = 0)

                 then diag = 1;
            END IF;

            IF ((BSKRegistryData_data like '%I21.0%'
                or BSKRegistryData_data like '%I21.1%'
                or BSKRegistryData_data like '%I21.2%'
                or BSKRegistryData_data like '%I21.3%'
                or BSKRegistryData_data like '%I21.9%'
                or BSKRegistryData_data like '%I22.0%'
                or BSKRegistryData_data like '%I22.1%'
                or BSKRegistryData_data like '%I22.8%'
                or BSKRegistryData_data like '%I22.9%') and numA = 2 and diag = 0)

                then diag = 1;
            END IF;
            IF ((BSKRegistryData_data like '%I21.0%'
                or BSKRegistryData_data like '%I21.1%'
                or BSKRegistryData_data like '%I21.2%'
                or BSKRegistryData_data like '%I21.3%'
                or BSKRegistryData_data like '%I21.9%'
                or BSKRegistryData_data like '%I22.0%'
                or BSKRegistryData_data like '%I22.1%'
                or BSKRegistryData_data like '%I22.8%'
                or BSKRegistryData_data like '%I22.9%') and numA = 3 and diag = 0)

                then diag = 1;
            END IF;

            IF (BSKRegistryData_data is not null AND numA = 4 )
                then TLT = 1; -- ТЛТ есть
            END IF;

            IF (BSKRegistryData_data is not null and numA = 5)
                then setdt = BSKRegistryData_data;
            END IF;

            IF (BSKRegistryData_data is not null and numA = 6)
                then hospitaldt = BSKRegistryData_data;
            END IF;
        END LOOP;
    CLOSE factor_cursor;

    --ЕСЛИ ДИАГНОЗ БЕЗ ПОДЪЕМА
    IF (diag = 0)
    	then return '';
    END IF;
    --@diag = 1 ДИАГНОЗ с подъемом
    --12 часов прошло от приема, отсчет ТЛТ прекращаем
    if (dateadd('hour', 12, setdt) < getdate()) -- потом поменять на 12
    	then return '';
    END IF;

    /*o	Рассматриваются КВС с диагнозом ОКС с подъемом сегмента ST (приложение № 1).
    Сначала учитывается основной диагноз, при его отсутствии – диагноз приёмного отделения,
    при отсутствии диагноза приёмного отделения – диагноз направившего учреждения. Если в КВС присутствует услуга ТЛТ (приложение № 1),
    то поле «Оставшееся время для ТЛТ» не заполняется*/
    IF (diag = 1 and TLT = 1)
    	then return '';
    END IF;

    open SMP_cursor for
    	select
        	case
            	when rd.BSKObservElement_id = 270 then 1 -- Дата/время прибытия на место вызова
                when rd.BSKObservElement_id = 274 then 2 -- Дата/время проведения ТЛТ
                --when rd.BSKObservElement_id = 415 then 3 -- Проведение ТЛТ (выполнено, не выполнено)
                when rd.BSKObservElement_id = 275 then 3 end numA, -- Причина отказа от ТЛТ
            case
            	when rd.BSKObservElement_id in (270,274) and dbo.isdate(coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data)) = 0 then NULL else coalesce(to_char(rd.BSKRegistryData_AnswerDT,'yyyy-mm-dd hh24:mi'),rd.BSKRegistryData_data) end BSKRegistryData_data
        from dbo.BSKRegistry r
        inner join dbo.BSKRegistryData rd on r.BSKRegistry_id = rd.BSKRegistry_id
        where r.Person_id = GetBSKTimeForTLT.Person_id::bigint
        	and r.MorbusType_id = 19
            and rd.BSKObservElement_id in (270,274,275)
        	and EXISTS (
            	select rdd.BSKRegistry_id
                from  dbo.BSKRegistryData rdd
                inner join dbo.BSKObservElement BE on BE.BSKObservElement_id = rdd.BSKObservElement_id
                left join dbo.BSKObservElementGroup BEG on BEG.BSKObservElementGroup_id = BE.BSKObservElementGroup_id
                where r.BSKRegistry_id = rdd.BSKRegistry_id
	                and BEG.BSKObservElementGroup_id = 44 -- анкеты из Скорой
                )
        order by r.BSKRegistry_id desc,numA
        limit 3;
        LOOP
            FETCH FROM SMP_cursor INTO numA, BSKRegistryData_data;
            exit when not found;
            if (numA = 1)
                then placecalldt = BSKRegistryData_data;
            END IF;
            if (numA = 2)
                then TLTsmp = 1;
            END IF;
            if (numA = 3)
                then failTLT = BSKRegistryData_data;
            END IF;
        END LOOP;
    CLOSE SMP_cursor;

    if (placecalldt between hospitaldt and dateadd('hour', -3,  hospitaldt) and TLTsmp = 1)
		then return '';
    END IF;
    if (placecalldt between hospitaldt and dateadd('hour', -3,  hospitaldt) and TLTsmp = 0 and (failTLT = 'Противопоказания' or failTLT = 'Вышло время' or failTLT = 'Пациент направлен на ЧКВ' or failTLT = 'Нет показаний'))
    	then return '';
    END IF;

    --получаем разницу в формае hh:mi:ss
    time_ = to_char(dateadd('hour', 12, setdt) - getdate(), 'hh24:mi');

    --формируем формат для отображения
    time_hour = substring(time_, 1, 2);
    time_minute = substring(time_, 4, 2);

    if (time_hour = '00')
    	then time_hour = '';
	    else time_hour = time_hour || ' ч ';
    end IF;

    if (time_minute = '00')
    	then time_minute = '';
        else
           	if (substring(time_minute, 1, 1) = '0')
               	then time_minute = substring(time_minute, 2, 1) || ' мин ';
                else time_minute = time_minute || ' мин ';
            end if;
	end if;

return time_hour || time_minute;

END

$$;

DROP FUNCTION dbo.getevnpartests_usluga(character varying);

CREATE OR REPLACE FUNCTION lis.p_analyzertestformula_ins(analyzer_id bigint, analyzertest_id bigint, analyzertest_pid bigint, usluga_ids character varying, analyzertestformula_code character varying, analyzertestformula_formula character varying, analyzertestformula_comment character varying, analyzertestformula_resultunit character varying, pmuser_id bigint, lpu_id bigint, INOUT error_code character varying = NULL::character varying, INOUT error_message character varying = NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
	p_AnalyzerTestFormula_id bigint;
	p_AnalyzerTestFormulaGroups_id bigint;  		
begin
	-- Задача : сохранить формулу, создать группу для аргументов (услуг), создать список аргументов (услуг)
	--alter table lis.AnalyzerTestFormulaGroups   alter column   AnalyzerTestFormulaGroups_code bigint null
	-- Сохранить формулу
	insert into lis.AnalyzerTestFormula (Analyzer_id,AnalyzerTest_id,AnalyzerTest_pid,AnalyzerTestFormula_Code,AnalyzerTestFormula_Formula,AnalyzerTestFormula_Comment,AnalyzerTestFormula_ResultUnit,
		AnalyzerTestFormula_insDT,AnalyzerTestFormula_updDT,AnalyzerTestFormula_Deleted,pmUser_insID,pmUser_updID)
	values(Analyzer_id,AnalyzerTest_id,AnalyzerTest_pid,AnalyzerTestFormula_Code,AnalyzerTestFormula_Formula,AnalyzerTestFormula_Comment,AnalyzerTestFormula_ResultUnit,
		getdate(),null,1,pmuser_id,null)
	returning AnalyzerTestFormula.AnalyzerTestFormula_id into p_AnalyzerTestFormula_id;
	
	insert into lis.AnalyzerTestFormulaGroups (AnalyzerTestFormulaGroups_code,AnalyzerTestFormula_id)
	values(	null,p_AnalyzerTestFormula_id)
	returning AnalyzerTestFormulaGroups_id into p_AnalyzerTestFormulaGroups_id;
	-- Обновить код группы по id
	
	update lis.AnalyzerTestFormulaGroups set AnalyzerTestFormulaGroups_Code = p_AnalyzerTestFormulaGroups_id where AnalyzerTestFormulaGroups_id = p_AnalyzerTestFormulaGroups_id;
	
	-- сохранить аргументы данной формулы
	insert into lis.AnalyzerTestFormulaArguments (AnalyzerTestFormulaGroups_code,AnalyzerTest_id,Usluga_id)
	Select 
		p_AnalyzerTestFormulaGroups_id as AnalyzerTestFormulaGroups_code, 
		p_AnalyzerTestFormula_ins.AnalyzerTest_id as AnalyzerTest_id,
		(select  UslugaComplex_id from dbo.UslugaComplex  where UslugaComplex_Code =  split.data limit 1) as Usluga_id
	from  lis.split (',', Usluga_ids) split;

EXCEPTION
	when others then error_code:=SQLSTATE; error_message:='p_AnalyzerTestFormula_ins: '||SQLERRM;
END;
$$;

DROP FUNCTION lis.split(delim character varying, text);

DROP FUNCTION vac.intlist2table(character varying);

DROP FUNCTION vac.intlist2table3fld(text);

DROP FUNCTION vac.list2tabledelim(text, delimiter character varying);

CREATE TABLE dbo.documentdeputy (
	documentdeputy_id bigint NOT NULL,
	documentauthority_id bigint,
	documentdeputy_ser bigint,
	documentdeputy_num bigint,
	documentdeputy_issue character varying(1000),
	documentdeputy_begdate bytea,
	documentdeputy_enddate bytea,
	pmuser_insid bigint NOT NULL,
	pmuser_updid bigint NOT NULL,
	documentdeputy_insdt bytea NOT NULL,
	documentdeputy_upddt bytea NOT NULL,
	documentdeputy_rowversion bytea NOT NULL
);
select * from dbo.xp_GenIdentity('dbo.documentdeputy','documentdeputy_id');

COMMENT ON TABLE dbo.documentdeputy IS 'Документы, удостоверяющие полномочия законного представителя';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_id IS 'Идентификатор';

COMMENT ON COLUMN dbo.documentdeputy.documentauthority_id IS 'Идентификатор типа документа';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_ser IS 'Серия';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_num IS 'Номер';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_issue IS 'Кем выдан';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_begdate IS 'Дата начала действия документа (дата выдачи)';

COMMENT ON COLUMN dbo.documentdeputy.documentdeputy_enddate IS 'Дата окончания действия документа';

-- DEPCY: This VIEW depends on the TABLE: dbo.personspeccategory
drop view if exists dbo.v_drug7noz;

drop view if exists dbo.v_personspeccategory;

-- DEPCY: This CONSTRAINT depends on the TABLE: dbo.personspeccategory

ALTER TABLE dbo.personspeccategory
	DROP CONSTRAINT fk_personspeccategory_deleted;

-- DEPCY: This CONSTRAINT depends on the TABLE: dbo.personspeccategory

ALTER TABLE dbo.personspeccategory
	DROP CONSTRAINT fk_personspeccategory_personspeccategorytype_id;

-- DEPCY: This CONSTRAINT depends on the TABLE: dbo.personspeccategory

ALTER TABLE dbo.personspeccategory
	DROP CONSTRAINT fk_personspeccategory_person_id;

-- DEPCY: This CONSTRAINT depends on the TABLE: dbo.personspeccategory

ALTER TABLE dbo.personspeccategory
	DROP CONSTRAINT pk_personspeccategory;

DROP TABLE dbo.personspeccategory;

ALTER TABLE dbo.persondeputy
	ADD COLUMN documentdeputy_id bigint;

COMMENT ON COLUMN dbo.persondeputy.documentdeputy_id IS 'Идентификатор документа, удостоверяющего полномочия законного представителя';

-- DEPCY: This TABLE is a dependency of COLUMN: dbo.personspeccategory.personregister_id

CREATE TABLE dbo.personspeccategory (
	personspeccategory_id bigint NOT NULL,
	person_id bigint,
	personspeccategorytype_id bigint,
	personspeccategory_begdate timestamp without time zone,
	personspeccategory_enddate timestamp without time zone,
	personregister_id bigint,
	pmuser_insid bigint NOT NULL,
	pmuser_updid bigint NOT NULL,
	personspeccategory_insdt timestamp without time zone NOT NULL,
	personspeccategory_upddt timestamp without time zone NOT NULL,
	pmuser_delid bigint,
	personspeccategory_deldt timestamp without time zone,
	personspeccategory_deleted bigint
);
select * from dbo.xp_GenIdentity('dbo.personspeccategory','personspeccategory_id');


COMMENT ON TABLE dbo.personspeccategory IS 'История изменения категории пациента';

COMMENT ON COLUMN dbo.personspeccategory.personspeccategory_id IS 'Идентификатор';

COMMENT ON COLUMN dbo.personspeccategory.person_id IS 'Идентификатор пациента';

COMMENT ON COLUMN dbo.personspeccategory.personspeccategorytype_id IS 'Идентификатор категории';

COMMENT ON COLUMN dbo.personspeccategory.personspeccategory_begdate IS 'Дата установки категории';

COMMENT ON COLUMN dbo.personspeccategory.personspeccategory_enddate IS 'Дата снятия категории';

COMMENT ON COLUMN dbo.personspeccategory.personregister_id IS 'Запись регистра';

ALTER TABLE dbo.prehospdirect
	ADD COLUMN prehospdirect_begdate timestamp without time zone;

COMMENT ON COLUMN dbo.prehospdirect.prehospdirect_begdate IS 'Дата начала действия';

ALTER TABLE dbo.prehospdirect
	ADD COLUMN prehospdirect_enddate timestamp without time zone;

COMMENT ON COLUMN dbo.prehospdirect.prehospdirect_enddate IS 'Дата окончания действия';

-- DEPCY: This CONSTRAINT is a dependency of CONSTRAINT: dbo.persondeputy.fk_persondeputy_documentdeputy_id

ALTER TABLE dbo.documentdeputy
	ADD CONSTRAINT pk_documentdeputy PRIMARY KEY (documentdeputy_id);

ALTER TABLE dbo.persondeputy
	ADD CONSTRAINT fk_persondeputy_documentdeputy_id FOREIGN KEY (documentdeputy_id) REFERENCES dbo.documentdeputy(documentdeputy_id);

ALTER TABLE dbo.personspeccategory
	ADD CONSTRAINT fk_personspeccategory_personregister_id FOREIGN KEY (personregister_id) REFERENCES dbo.personregister(personregister_id);

ALTER TABLE dbo.documentdeputy
	ADD CONSTRAINT fk_documentdeputy_documentauthority_id FOREIGN KEY (documentauthority_id) REFERENCES dbo.documentauthority(documentauthority_id);

CREATE VIEW dbo.v_documentdeputy AS
	SELECT documentdeputy.documentdeputy_id,
    documentdeputy.documentauthority_id,
    documentdeputy.documentdeputy_ser,
    documentdeputy.documentdeputy_num,
    documentdeputy.documentdeputy_issue,
    documentdeputy.documentdeputy_begdate,
    documentdeputy.documentdeputy_enddate,
    documentdeputy.pmuser_insid,
    documentdeputy.pmuser_updid,
    documentdeputy.documentdeputy_insdt,
    documentdeputy.documentdeputy_upddt
   FROM dbo.documentdeputy
  WHERE (1 = 1);

COMMENT ON VIEW dbo.v_documentdeputy IS 'Autogen';

-- DEPCY: This VIEW depends on the VIEW: persis.v_post

drop view if exists onko.v_profilejurnalfull;

-- DEPCY: This VIEW depends on the VIEW: persis.v_post

drop view if exists onko.v_profilejurnal;

-- DEPCY: This VIEW depends on the VIEW: persis.v_post

drop view if exists onko.v_profilejurnalact;

-- DEPCY: This VIEW depends on the VIEW: persis.v_post

drop view if exists onko.v_persononkoprofile;

drop view if exists persis.v_post;

drop view if exists dbo.v_address_kladr;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_deputykind

drop view if exists dbo.v_emkformreport;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_deputykind

drop view if exists dbo.v_evnps_rpt;

drop view if exists dbo.v_deputykind;

drop view if exists dbo.v_documentucost_lite;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_documentucstr

drop view if exists dbo.v_documentucostat_lite;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_documentucstr

drop view if exists dbo.v_documentucostat;

drop view if exists dbo.v_documentucstr;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnusluga


-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnusluga

drop view if exists dbo.v_registryerrorprof;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnusluga

drop view if exists dbo.v_registryerror;
drop view if exists r1.v_registryerror ;

drop view if exists dbo.v_evnusluga;

drop view if exists dbo.v_evnusluga_all;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnvizit

-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnvizit

drop view if exists r1.v_registrynopolis;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_evnvizit

drop view if exists dbo.v_evnvizit;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_vacpersonplan0;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_vacpersonkart;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_inoculation4report5;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_vac_personregion;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_plantuberkulin;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_personplanfinal;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_vacpersonplan0_performed;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_inoculation_all;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_inoculation_fixed;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalvacfixed;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalvac;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalmedtaprefusal;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalmantufixed;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalmantuall;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalmantuaccount;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_inoculationother;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalaccountother;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalaccountall;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_inoculation;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_journalaccount;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_fl_workplace;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_fl_plan;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists vac.v_vac_person;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_job

drop view if exists dbo.v_job_er;

drop view if exists dbo.v_job;

drop view if exists dbo.v_medstafffactcache;

drop view if exists dbo.v_person_er;

drop view if exists dbo.v_person_er2;

drop view if exists dbo.v_personcard;

drop view if exists dbo.v_personcard_all;

drop view if exists dbo.v_personcard_rpt;

drop view if exists dbo.v_personcardstate;

drop view if exists dbo.v_persondeputy;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_persondisp

drop view if exists dbo.v_personstate_all;

drop view if exists dbo.v_persondisp;

drop view if exists dbo.v_personfirname;

drop view if exists dbo.v_personinn;

drop view if exists dbo.v_personjob;

drop view if exists dbo.v_personnationalitystatus;

drop view if exists dbo.v_personpaddress;

drop view if exists dbo.v_personphone;

drop view if exists dbo.v_personpolis;

drop view if exists dbo.v_personsecname;

drop view if exists dbo.v_personsex;

drop view if exists dbo.v_personsnils;

drop view if exists dbo.v_personsoccardnum;

drop view if exists dbo.v_personsocstatus;

drop view if exists dbo.v_personstate_dop;

drop view if exists dbo.v_personsurname;

drop view if exists dbo.v_personuaddress;

drop view if exists dbo.v_prehospdirect;

drop view if exists dbo.v_socstatus;

-- DEPCY: This VIEW depends on the VIEW: dbo.v_surveytypelink

drop view if exists dbo.v_surveytypelink;

drop view if exists dbo.v_timetablemedservice;

drop view if exists lis.v_analyzerrack;

drop view if exists rls.v_drugmnncode;

CREATE OR REPLACE FUNCTION dbo.evnparcard_oborud(list character varying) RETURNS TABLE(id bigint, evnuslugapar_id bigint, oborud_list character varying)
    LANGUAGE sql
    AS $$

	with recursive SL as (
		select ID
		from rpt.GetIDs_FromStrList(EvnParCArd_oborud.List)
	),

	CTE as ( 
		select distinct
			t.EvnUslugaPar_id, 
			t.ID,
			t.Analyzer_id, 
			t.Analyzer_Name,		
			ROW_NUMBER() OVER (PARTITION BY t.EvnUslugaPar_id ORDER BY t.Analyzer_id) as rn, 
			COUNT(*) OVER (PARTITION BY t.EvnUslugaPar_id) as cnt
		from  (
			select distinct 
				EUP.EvnUslugaPar_id, 
				coalesce(ltrim(rtrim(analyzer.Analyzer_Name)),'Ручные методики') as Analyzer_Name, 
				a.Analyzer_id,
				sl.ID,
				eu.UslugaTest_ResultApproved
			from SL 
			inner join dbo.v_EvnUslugaPar EUP     
				 on SL.ID=EUP.EvnUslugaPar_id
			left join dbo.v_UslugaTest EU 
				 on EU.UslugaTest_pid = eup.EvnUslugaPar_id and eup.EvnDirection_id is not null --and EU.UslugaTest_ResultApproved = 2 
			left join dbo.v_EvnLabSample els  
				 on els.EvnLabSample_id = eu.EvnLabSample_id 
			 left join lis.v_Analyzer a 
				on els.Analyzer_id = a.Analyzer_id 
			 left join lateral(
				select 
					Analyzer_Name
				from lis.v_Analyzer a 
				inner join lis.v_AnalyzerTest at on at.Analyzer_id = a.Analyzer_id
				inner join lis.v_AnalyzerTestRefValues atrv on atrv.AnalyzerTest_id = at.AnalyzerTest_id
				where atrv.RefValues_id = EU.RefValues_id
				limit 1
			) as analyzer on true
		) as t 
		where coalesce(t.UslugaTest_ResultApproved,1)=2
	),
	q (EvnUslugaPar_id,ID,a_list,rn,cnt) as ( 		 
		SELECT  
			EvnUslugaPar_id, 
			CTE.ID,
			CAST(CTE.Analyzer_Name AS VARCHAR), 
			rn, 
			cnt 
		FROM CTE 
		WHERE  rn = 1 
		
		UNION ALL 
		
		SELECT  
			CTE.EvnUslugaPar_id, 
			CTE.ID,
			CAST(coalesce(q.a_list || '; ','') || coalesce(CTE.Analyzer_Name,'') AS VARCHAR), 
			CTE.rn, 
			CTE.cnt 
		FROM q 
		JOIN CTE ON CTE.EvnUslugaPar_id = q.EvnUslugaPar_id 
			AND CTE.rn = q.rn + 1 
	) 

	select 
		id, 
		EvnUslugaPar_id,
		coalesce(a_list,'') as Oborud_List 
	from q 
	where rn=cnt;
	
$$;

CREATE OR REPLACE FUNCTION dbo.getevnpartests_usluga(list character varying) RETURNS TABLE(v1 bigint, test_numback bigint, evnuslugapar_id bigint, id bigint, uslugacomplex_name_pid character varying, uslugacomplex_name character varying, evnuslugapar_resultvalueold character varying, evnuslugapar_resultvalue character varying, uslugatest_resultunit character varying, evnuslugapar_resultnorm character varying, uslugatest_comment character varying, rv numeric, lower numeric, upper numeric, lcrit numeric, ucrit numeric, arrows integer, table_prot integer, grarrows integer)
    LANGUAGE sql
    AS $$

	with SL as (
		select ID
		from rpt.GetIDs_FromStrList(getEvnParTests_Usluga.List)
	),
 
	uslugas as ( 
		select distinct
			ROW_NUMBER()OVER(partition BY eup.EvnUslugaPar_id 
				ORDER BY analyzertest.AnalyzerTest_SortCode, euin.Uslugatest_id /*coalesce(eup.EvnUslugaPar_id,analyzertest.AnalyzerTest_SysNick, analyzertest.UslugaComplex_Name, uc.UslugaComplex_Name)*/
				) as v1,  
			ROW_NUMBER()OVER(partition BY eup.EvnUslugaPar_id 
				ORDER BY analyzertest.AnalyzerTest_SortCode desc, euin.Uslugatest_id desc /*coalesce(eup.EvnUslugaPar_id,analyzertest.AnalyzerTest_SysNick, analyzertest.UslugaComplex_Name, uc.UslugaComplex_Name)*/
				) as Test_NumBack,  
			eup.EvnUslugaPar_id,
			SL.ID,  
			ucp.UslugaComplex_Name as UslugaComplex_Name_PID,  
			coalesce(analyzertest.AnalyzerTest_SysNick, analyzertest.UslugaComplex_Name, uc.UslugaComplex_Name) as UslugaComplex_Name,  
			euin.Uslugatest_ResultValue as EvnUslugaPar_ResultValueOLD,   

			coalesce(ltrim(rtrim(cast(euin.Uslugatest_ResultValue as CHAR(200)))), '') ||
			  (coalesce('беременность: '|| cast(myPregnancyUnitType.PregnancyUnitType_Name as CHAR) || ' ' || 
			  cast(RefValues_PregnancyFrom as CHAR) || ' - ' || cast(RefValues_PregnancyTo as CHAR) || '  ' || cast(PregnancyUnitType_Name as CHAR),'')) ||
			  (coalesce('фаза цикла: ' || cast(myHormonalPhaseType.HormonalPhaseType_Name as CHAR), '')) ||
			  (coalesce('Время суток: c ' || cast(RefValues_TimeOfDayFrom as CHAR) || ' по ' || cast(RefValues_TimeOfDayTo as CHAR) || ' ч.', '')) 
			  /*+ ' ' + (coalesce(rtrim(ltrim(cast('(' + RefValues_Description + ')' as CHAR))), ''))*/ as EvnUslugaPar_ResultValue, 

			euin.Uslugatest_ResultUnit,  

			case when euin.Uslugatest_ResultQualitativeText = '' 
			then coalesce(euin.Uslugatest_ResultLower,'') || ' - ' || coalesce(euin.Uslugatest_ResultUpper,'')  
			else euin.Uslugatest_ResultQualitativeText end as EvnUslugaPar_ResultNorm,	
			case 
					when dbo.isnumeric(euin.Uslugatest_ResultValue) = 1 and 
						 (
						   coalesce(euin.UslugaTest_ResultValue, '') not in ( '-', ',', '+', '*', '/', '&', '%', '++', '+++')				   
						 ) 
						 --and CHARINDEX (',', (coalesce(euin.UslugaTest_ResultValue, '')),CHARINDEX (',',coalesce(euin.UslugaTest_ResultValue,''))+1) = 0				
						and coalesce(euin.UslugaTest_ResultValue, '') not like '%,%,%'--'^_%' escape '\'
						and coalesce(euin.UslugaTest_ResultValue, '') not like '%-%-%'    
						 then replace(euin.UslugaTest_ResultValue, ',', '.')::float::decimal(10,2)
					else null 
			end as RV,  		
			--case when isnumeric(euin.Uslugatest_ResultValue) =1 then convert(decimal(10,2), cast(replace(euin.UslugaTest_ResultValue, ',', '.') as float)) else null end RV,	
			case when dbo.isnumeric(euin.Uslugatest_ResultLower)=1 then cast(replace(euin.Uslugatest_ResultLower, ',', '.') as float)::decimal(10,2)  else null end as lower,
			case when dbo.isnumeric(euin.Uslugatest_ResultUpper)=1 then cast(replace(euin.Uslugatest_ResultUpper, ',', '.') as float)::decimal(10,2) else null end as Upper,
			case when dbo.isnumeric(euin.UslugaTest_ResultLowerCrit)=1 then cast(replace(euin.UslugaTest_ResultLowerCrit, ',', '.') as float)::decimal(10,2) else null end LCrit,
			case when dbo.isnumeric(euin.UslugaTest_ResultUpperCrit)=1 then cast(replace(euin.UslugaTest_ResultUpperCrit, ',', '.') as float)::decimal(10,2)  else null end UCrit,
			euin.UslugaTest_Comment

			From SL 
			inner join dbo.v_EvnUslugaPar eup  on SL.ID = eup.EvnUslugaPar_id
				and eup.EvnDirection_id > 0
			inner join dbo.v_Uslugatest euin  on euin.Uslugatest_pid = eup.EvnUslugaPar_id
				and euin.Uslugatest_ResultApproved = 2 
			inner join dbo.v_EvnLabSample els  on euin.EvnLabSample_id = els.EvnLabSample_id  
			inner join dbo.v_UslugaComplex ucp  on ucp.UslugaComplex_id = eup.UslugaComplex_id  
			inner join dbo.v_UslugaComplex uc  on euin.UslugaComplex_id = uc.UslugaComplex_id  
			left join dbo.v_RefValues rv  on rv.RefValues_id = euin.RefValues_id  

			left join lateral ( 
				select * 
				from dbo.HormonalPhaseType HPT 
				where HPT.HormonalPhaseType_id = rv.HormonalPhaseType_id
				limit 1
			) as myHormonalPhaseType on true

			left join lateral ( 
				select * 
				from dbo.PregnancyUnitType PUT 
				where PUT.PregnancyUnitType_id = rv.PregnancyUnitType_id
				limit 1
			) as myPregnancyUnitType on true
     
			left join lateral (  
				select 
					at_child.AnalyzerTest_id, 
					at_child.AnalyzerTest_SysNick,  
					at_child.AnalyzerTest_SortCode,  
					uctest.UslugaComplex_Name,  
					ucms_parent.UslugaComplex_Name as UslugaComplex_ParentName  
				from lis.v_AnalyzerTest at_child   
				left join lis.v_AnalyzerTest at  on at.AnalyzerTest_id = coalesce(at_child.AnalyzerTest_pid, at.AnalyzerTest_id)  
				inner join dbo.v_UslugaComplexMedService ucms_at  on at_child.UslugaComplexMedService_id = ucms_at.UslugaComplexMedService_id  
				left join dbo.v_UslugaComplexMedService ucms_parent  on ucms_parent.UslugaComplexMedService_id = coalesce(ucms_at.UslugaComplexMedService_pid, ucms_at.UslugaComplexMedService_id)  
				inner join lis.v_Analyzer a  on a.Analyzer_id = at.Analyzer_id  
				left join dbo.v_UslugaComplex uctest  on uctest.UslugaComplex_id =at_child.UslugaComplex_id  
				where  
					ucms_at.UslugaComplex_id = uc.UslugaComplex_id  
					and ucms_parent.UslugaComplex_id = eup.UslugaComplex_id  
					and ucms_at.MedService_id = els.MedService_id  
					and coalesce(at.AnalyzerTest_IsNotActive, 1) = 1  
					and coalesce(a.Analyzer_IsNotActive, 1) = 1  
					and (at.AnalyzerTest_endDT >= dbo.tzGetDate() or at.AnalyzerTest_endDT is null)  
				limit 1
			) as analyzertest on true
			
			left join lateral (  
				select  Analyzer_Name  
				from lis.v_Analyzer a  
				inner join lis.v_AnalyzerTest at on at.Analyzer_id = a.Analyzer_id  
				inner join lis.v_AnalyzerTestRefValues atrv on atrv.AnalyzerTest_id = at.AnalyzerTest_id  
				where  atrv.RefValues_id = euin.RefValues_id  
			) as analyzer on true
	),

	arrows as (
		select      
			v1,  Test_NumBack, EvnUslugaPar_id,ID,UslugaComplex_Name_PID, UslugaComplex_Name,  
			EvnUslugaPar_ResultValueOLD, EvnUslugaPar_ResultValue, Uslugatest_ResultUnit, EvnUslugaPar_ResultNorm,
			UslugaTest_Comment,RV,lower,Upper,LCrit,UCrit,
			cast (case 
				when RV>UCrit and Ucrit is not null then 1 --2 стрелки вверх
				else case when RV > Upper and Upper is not null then 2 --1 стрелка вверх
						  else case when  RV < LCrit and LCrit is not null then 3 --2 стрелки вниз 
									else case when  RV < lower and lower is not null then 4 -- 1 стрелка вниз
										 end
							   end
					 end
			end as integer) as Arrows,	

		  -- #164980 решила попробовать получить деление через разницу прямой и обратной нумерации тестов
		  -- Пример: весго 9 тестов в исследовании. Необходимо чтобы в певой таблице были тестоы 1 - 5, во 2-ой 6 - 9.
		  -- Если разница отрицательна или нулевая - значит это 1-ая половина тестов (для 1-ой таблицы)
			case when uslugas.v1 - uslugas.Test_NumBack <= 0 then 1 else 2 end as Table_Prot

		  -- #164980 другой способ деления - через поиск среднего значения
		  -- но не хватает вычисления значения на конкретное исследование
		  -- case when uslugas.v1 > (select avg(v1) as cnt from uslugas) 
			 --then 2 else 1 end as Table_Prot
		from uslugas 
	)

	select *,
		case when Arrows is null then 0 else 1 end as grArrows
	from arrows;

$$;

CREATE OR REPLACE FUNCTION lis.split(delim character varying, list text) RETURNS TABLE(listpos integer, data character varying)
    LANGUAGE plpgsql
    AS $$
DECLARE pos      int;
        textpos  int;
        chunklen int;
        str      varchar(4000);
        tmpstr   varchar(4000);
        leftover varchar(4000);
       begin
 	CREATE TEMP table tbl  (listpos int  GENERATED BY DEFAULT AS IDENTITY, data  varchar NOT NULL) ON COMMIT DROP ;
    textpos := 1;
    leftover := ' ';
   /* WHILE textpos <= datalength(list) / 2
    BEGIN
    SET chunklen = 4000 - datalength(leftover) / 2
    SET tmpstr = ltrim(leftover + substring(list, textpos, chunklen))
    SET textpos = textpos + chunklen*/
    tmpstr:=list;
    pos := position(delim in tmpstr);
    WHILE pos > 0
    loop
	    str := substring(tmpstr, 1, pos - 1);
        insert into  tbl (data) VALUES(str);
        tmpstr := ltrim(substring(tmpstr, pos + 1, length(tmpstr)));
        pos := position(delim in tmpstr);
    end loop;
    leftover := tmpstr;
   -- END

    IF ltrim(rtrim(leftover)) <> '' then
         INSERT into tbl (data) VALUES(leftover);
    end if;
       

      RETURN query select * from tbl;
  end;
 $$;

CREATE OR REPLACE FUNCTION vac.intlist2table(list character varying) RETURNS TABLE(listpos integer, number bigint)
    LANGUAGE plpgsql IMMUTABLE
    AS $$
/*
DECLARE pos      int;
        textpos  int;
        chunklen smallint;
        str      varchar(4000);
        tmpstr   varchar(4000);
        leftover varchar(4000);
*/
begin
	/*
-- =============================================
-- Author:		<Нигматуллин Тагир>
-- Create date: <03.05.2012>
-- Description:	Функция преобразует строку с запятыми в таблицу, состоящую   их двух полей. 
-- number - это значение элемента списка, а listpos - это порядковый номер элемента в списке.
--  позаимстврвано из http://www.sql.ru/articles/mssql/03060701arraysandlistsinsqlserver.shtml#iter-list-of-integers
-- =============================================
*/
/*
	CREATE TEMP table tbl  (listpos int NOT NULL GENERATED BY DEFAULT AS IDENTITY, number  bigint NOT NULL) ON COMMIT DROP ;
   -- sextpos := 1;
    leftover := ' ';
  /*    WHILE textpos <= datalength(list) / 2
      BEGIN
         SET chunklen = 4000 - datalength(leftover) / 2
         SET tmpstr = ltrim(leftover + substring(list, textpos, chunklen))
         SET textpos = textpos + chunklen
*/
   	tmpstr:=list;
     pos := position(',' in tmpstr);
     WHILE pos > 0
     loop
         str := substring(tmpstr, 1, pos - 1);
         INSERT into tbl (number) VALUES(to_number(str));
         tmpstr := ltrim(substring(tmpstr, pos + 1, length(tmpstr)));
         pos := position(',' in tmpstr);
            --SET pos = charindex(delimiter, tmpstr)
     end loop;

    /*     SET leftover = tmpstr
      END*/

      IF ltrim(rtrim(tmpstr)) <> '' then
         insert into tbl (number) VALUES(to_number(tmpstr));
      end if;
       

      RETURN query select * from tbl t;
*/
	return query
	select
		(row_number() over())::int as listpos,
		q.number::bigint as number
	from regexp_split_to_table(list, '\s*,\s*') as q(number);



   END;
$$;

CREATE OR REPLACE FUNCTION vac.intlist2table3fld(list text) RETURNS TABLE(listpos integer, number bigint, string character varying)
    LANGUAGE plpgsql
    AS $$
declare
	pos      int;
    textpos  int;
    chunklen int;
    str      varchar(4000);
    tmpstr   varchar(4000);
    leftover varchar(4000);
    num bigint;
    string varchar(200);
BEGIN
/*
-- =============================================
-- Author:		<Нигматуллин Тагир>
-- Create date: <17.01.2013>
-- Description:	Функция преобразует строку с запятыми в таблицу, состоящую   их трех полей. 
		-- num1 - это значение первого элемента списка, 
		-- str - это значение второго элемента списка, 
		-- istpos - это порядковый номер элемента в списке.
--  позаимстврвано из http://www.sql.ru/articles/mssql/03060701arraysandlistsinsqlserver.shtml#iter-list-of-integers
-- =============================================
*/  
   CREATE TEMP table  tbl (listpos int NOT null GENERATED BY DEFAULT AS IDENTITY, number  bigint NOT NULL,  string  varchar(200) NOT NULL)  ON COMMIT DROP ;
      textpos := 1;
      leftover := ' ';
     -- WHILE textpos <= datalength(list) / 2
     -- BEGIN
--         SET chunklen = 4000 - datalength(leftover) / 2
--         SET tmpstr = ltrim(leftover + substring(list, textpos, chunklen))
--         SET textpos = textpos + chunklen

        tmpstr:=list; 
     	pos := position(',' in tmpstr);
        WHILE pos > 0
        loop
            str := substring(tmpstr, 1, pos - 1);
         --   INSERT tbl (number) VALUES(convert(int, str))
            num := to_number(SubString(str, 1, position('_' in str) - 1));
            string = SubString(str, position('_' in str) + 1,  length(str));
            INSERT  into tbl (number, string) VALUES(num, string);
            tmpstr := ltrim(substring(tmpstr, pos + 1, length(tmpstr)));
            pos := position(',' in tmpstr);
            --SET pos = charindex(delimiter, tmpstr)
         end loop;

         leftover := tmpstr;
          -- END
      IF ltrim(rtrim(leftover)) <> '' then
         num := SubString(leftover, 1, position('_' in leftover) - 1)::bigint;
         string := SubString(leftover, position('_' in  leftover) + 1,  length(leftover));
         
         insert into tbl (number, string) VALUES(num, string);
       
	  end if;
      RETURN query select * from tbl t;
     
     END;
$$;

CREATE OR REPLACE FUNCTION vac.list2tabledelim(list text, delimiter character varying = ','::character varying) RETURNS TABLE(listpos integer, paramval character varying)
    LANGUAGE plpgsql
    AS $$
DECLARE  
	pos      int;
    textpos  int;
    chunklen int;
    str      varchar(4000);
    tmpstr   varchar(4000);
    leftover varchar(4000);
BEGIN
   /*
    * -- =============================================
-- Author:		<Нигматуллин Тагир>
-- Create date: <03.05.2012>
-- Description:	Функция преобразует строку с запятыми в таблицу, состоящую   их двух полей. 
-- paramval - это значение элемента списка, а listpos - это порядковый номер элемента в списке.
--  позаимстврвано из http://www.sql.ru/articles/mssql/03060701arraysandlistsinsqlserver.shtml#iter-list-of-integers
-- =============================================
*/
  
	CREATE TEMP TABLE  tbl (listpos int NOT NULL GENERATED BY DEFAULT AS IDENTITY,paramval  varchar(1000) NOT NULL) ON COMMIT DROP ;
    textpos := 1;
    leftover := ' ';
    tmpstr:=list;
    pos := position(delimiter in tmpstr);
    WHILE pos > 0
    loop
        str := substring(tmpstr, 1, pos - 1);
        INSERT into tbl (paramval) VALUES(str);
        tmpstr := ltrim(substring(tmpstr, pos + 1, length(tmpstr)));
        pos := position(delimiter in tmpstr);
     end loop;
     IF ltrim(rtrim(tmpstr)) <> '' then
         INSERT into tbl (paramval) VALUES(tmpstr);
     end if;
	 
    return query select * from tbl t;
end;
$$;


CREATE VIEW dbo.v_personspeccategory AS
	SELECT personspeccategory.personspeccategory_id,
    personspeccategory.person_id,
    personspeccategory.personspeccategorytype_id,
    personspeccategory.personspeccategory_begdate,
    personspeccategory.personspeccategory_enddate,
    personspeccategory.personregister_id,
    personspeccategory.pmuser_insid,
    personspeccategory.pmuser_updid,
    personspeccategory.personspeccategory_insdt,
    personspeccategory.personspeccategory_upddt
   FROM dbo.personspeccategory
  WHERE ((1 = 1) AND ((personspeccategory.personspeccategory_deleted = 1) OR (personspeccategory.personspeccategory_deleted IS NULL)));

COMMENT ON VIEW dbo.v_personspeccategory IS 'Autogen';

ALTER TABLE dbo.personspeccategory
	ADD CONSTRAINT fk_personspeccategory_deleted FOREIGN KEY (personspeccategory_deleted) REFERENCES dbo.yesno(yesno_id);

ALTER TABLE dbo.personspeccategory
	ADD CONSTRAINT fk_personspeccategory_personspeccategorytype_id FOREIGN KEY (personspeccategorytype_id) REFERENCES dbo.personspeccategorytype(personspeccategorytype_id);

ALTER TABLE dbo.personspeccategory
	ADD CONSTRAINT fk_personspeccategory_person_id FOREIGN KEY (person_id) REFERENCES dbo.person(person_id);

ALTER TABLE dbo.personspeccategory
	ADD CONSTRAINT pk_personspeccategory PRIMARY KEY (personspeccategory_id);

-- DEPCY: This VIEW is a dependency of VIEW: onko.v_profilejurnalfull

CREATE VIEW dbo.v_personcardstate AS
	SELECT personcardstate.server_id,
    personcardstate.personcardstate_id,
    personcardstate.personcard_id,
    personcardstate.person_id,
    personcardstate.lpu_id,
    personcardstate.lpuregion_id,
    personcardstate.lpuattachtype_id,
    personcardstate.personcardstate_code,
    personcardstate.personcardstate_begdate,
    personcardstate.personcardstate_enddate,
    personcardstate.cardclosecause_id,
    personcardstate.personcard_isattachcondit,
    personcardstate.personcard_isattachauto,
    personcardstate.personcard_attachautodt,
    personcardstate.pmuser_insid,
    personcardstate.pmuser_updid,
    personcardstate.personcardstate_insdt,
    personcardstate.personcardstate_upddt,
    personcardstate.personcardstate_dmspolisnum,
    personcardstate.personcardstate_dmsbegdate,
    personcardstate.personcardstate_dmsenddate,
    personcardstate.orgsmo_id,
    personcardstate.personcardattach_id,
    personcardstate.lpuregion_fapid,
    personcardstate.lpuregiontype_id,
    personcardstate.medstafffact_id
   FROM dbo.personcardstate
  WHERE (1 = 1);

-- DEPCY: This VIEW is a dependency of VIEW: onko.v_profilejurnalfull

CREATE VIEW dbo.v_socstatus AS
	SELECT socstatus.socstatus_id,
    socstatus.socstatus_code,
    socstatus.socstatus_name,
    socstatus.socstatus_sysnick,
    socstatus.pmuser_insid,
    socstatus.pmuser_updid,
    socstatus.socstatus_insdt,
    socstatus.socstatus_upddt,
    socstatus.region_id,
    socstatus.socstatus_agefrom,
    socstatus.socstatus_ageto,
    socstatus.socstatus_begdt,
    socstatus.socstatus_enddt,
    socstatus.socstatusrpn_id
   FROM dbo.socstatus
  WHERE ((1 = 1) AND ((socstatus.region_id = dbo.getregion()) OR (socstatus.region_id IS NULL)));

-- DEPCY: This VIEW is a dependency of VIEW: onko.v_profilejurnalfull

CREATE VIEW persis.v_post AS
	SELECT post.id,
    post.insdt,
    post.pmuser_insid,
    post.upddt,
    post.pmuser_updid,
    post.version,
    post.code,
    post.name,
    post.postkind_id,
    post.maxpopulation,
    post.primaryhealthcare,
    post.frmpentry_id,
    post.tariflist,
    post.professionalgroup_id,
    post.speciality_id,
    post.post_nick,
    post.klcountry_id,
    post.begdt,
    post.enddt,
    post.postfss_id,
    post.medpost_id
   FROM persis.post
  WHERE ((1 = 1) AND ((post.post_deleted = 1) OR (post.post_deleted IS NULL)) AND ((post.klcountry_id =
        CASE
            WHEN (dbo.getregion() = 101) THEN 398
            ELSE 643
        END) OR (post.klcountry_id IS NULL)));

-- DEPCY: This VIEW is a dependency of VIEW: onko.v_profilejurnalfull

CREATE VIEW onko.v_persononkoprofile AS
	SELECT p.persononkoprofile_id,
    p.person_id,
    p.persononkoprofile_dtbeg,
    p.lpu_id,
    l.lpu_nick,
    l.lpu_name,
    p.medstafffact_id,
    m.person_fin AS medpersonal_fin,
    m.person_fio AS medpersonal_fio,
    post.name AS medpersonal_dolgnostname,
    p.pmuser_insid,
    p.persononkoprofiles_insdt,
    p.pmuser_updid,
    p.persononkoprofile_upddt,
    COALESCE(( SELECT 2
           FROM onko.persononkoquestions t
          WHERE (t.persononkoprofile_id = p.persononkoprofile_id)
         LIMIT 1), 1) AS monitored,
    ( SELECT ('Вопросы: '::text || string_agg(((t.onkoquestions_id)::character varying)::text, ','::text)) AS string_agg
           FROM onko.persononkoquestions t
          WHERE (t.persononkoprofile_id = p.persononkoprofile_id)) AS profileresult,
    p.evn_id
   FROM (((onko.persononkoprofile p
     LEFT JOIN LATERAL ( SELECT v_lpu.lpu_nick,
            v_lpu.lpu_name
           FROM dbo.v_lpu
          WHERE (v_lpu.lpu_id = p.lpu_id)
         LIMIT 1) l ON (true))
     LEFT JOIN LATERAL ( SELECT m_1.person_fin,
            m_1.person_fio,
            m_1.post_id
           FROM dbo.v_medstafffact m_1
          WHERE (m_1.medstafffact_id = p.medstafffact_id)
         LIMIT 1) m ON (true))
     LEFT JOIN LATERAL ( SELECT v_post.name
           FROM persis.v_post
          WHERE (v_post.id = m.post_id)
         LIMIT 1) post ON (true))
  WHERE (p.persononkoprofile_statusid = 0);

CREATE VIEW onko.v_profilejurnalfull AS
	SELECT p.person_id,
    p.server_id,
    p.personevn_id,
    p.person_surname AS surname,
    p.person_firname AS firname,
    p.person_secname AS secname,
    (((((p.person_surname)::text || ' '::text) || COALESCE(("substring"((p.person_firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((p.person_secname)::text, 1, 1) || '.'::text), '__'::text)) AS fio,
    p.person_birthday AS birthday,
    NULL::text AS date_smert,
    p.sex_id,
        CASE
            WHEN (p.sex_id = 1) THEN 'М'::text
            WHEN (p.sex_id = 2) THEN 'Ж'::text
            ELSE NULL::text
        END AS sex,
    adr.address_address AS address,
    COALESCE((((rg.lpuregiontype_name)::text || ' №'::text) || (rg.lpuregion_name)::text), ' '::text) AS uch,
    card.lpuregion_id,
    p.socstatus_id,
    s_st.socstatus_name,
    card.lpu_id,
    lpu.lpu_name,
    lpu.lpu_nick,
    prof.lpu_id AS lpuprofile_id,
    lpu_prof.lpu_name AS lpuprofile_name,
    lpu_prof.lpu_nick AS lpuprofile_nick,
    prof.persononkoprofile_id,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN ' '::text
            ELSE 'Анкета заполнена'::text
        END AS statusonkoprofile,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN 1
            ELSE 2
        END AS statusonkoprofile_id,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN 'Анкета не заполнена'::text
            ELSE 'Анкета заполнена'::text
        END AS statusonkoprofile_tmp,
    prof.persononkoprofile_dtbeg,
    prof.medstafffact_id,
    COALESCE(prof.medpersonal_fin, ' '::text) AS medpersonal_fin,
    COALESCE(prof.monitored, '-1'::integer) AS monitored,
        CASE
            WHEN (prof.monitored = 2) THEN 'Необходим Онкоконтроль'::text
            WHEN (prof.monitored = 1) THEN 'Не нужен Онкоконтроль'::text
            ELSE ' '::text
        END AS monitored_name,
    prof.profileresult,
    p.person_deaddt,
        CASE
            WHEN (p.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM (((((((dbo.v_personstate p
     JOIN onko.v_persononkoprofile prof ON ((prof.person_id = p.person_id)))
     LEFT JOIN dbo.v_socstatus s_st ON ((s_st.socstatus_id = p.socstatus_id)))
     LEFT JOIN dbo.v_personcardstate card ON (((card.person_id = p.person_id) AND (card.lpuattachtype_id = 1))))
     LEFT JOIN dbo.v_address adr ON ((adr.address_id = p.paddress_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = card.lpu_id)))
     LEFT JOIN dbo.v_lpu lpu_prof ON ((lpu_prof.lpu_id = prof.lpu_id)))
     LEFT JOIN dbo.v_lpuregion rg ON ((card.lpuregion_id = rg.lpuregion_id)))
  WHERE (p.person_birthday <= dbo.dateadd('year'::character varying, '-18'::integer, dbo.getdate()));

-- DEPCY: This VIEW is a dependency of VIEW: onko.v_profilejurnal

CREATE VIEW onko.v_profilejurnalact AS
	WITH tbl AS (
         SELECT prof_1.person_id,
            min(prof_1.persononkoprofile_id) AS persononkoprofile_id
           FROM onko.persononkoprofile prof_1
          WHERE ((prof_1.persononkoprofile_dtbeg >= (('1/1/'::text || to_char(dbo.getdate(), 'yyyy'::text)))::timestamp without time zone) AND (prof_1.persononkoprofile_dtbeg <= (('31/12/'::text || to_char(dbo.getdate(), 'yyyy'::text)))::timestamp without time zone))
          GROUP BY prof_1.person_id
        )
 SELECT DISTINCT prof.persononkoprofile_id,
    prof.person_id,
    prof.persononkoprofile_dtbeg,
    prof.lpu_id,
    prof.lpu_nick,
    prof.lpu_name,
    prof.medstafffact_id,
    prof.medpersonal_fin,
    prof.medpersonal_fio,
    prof.medpersonal_dolgnostname,
    prof.pmuser_insid,
    prof.persononkoprofiles_insdt,
    prof.pmuser_updid,
    prof.persononkoprofile_upddt,
    prof.monitored,
    prof.profileresult
   FROM (onko.v_persononkoprofile prof
     JOIN tbl ON (((tbl.person_id = prof.person_id) AND (tbl.persononkoprofile_id = prof.persononkoprofile_id))));

CREATE VIEW onko.v_profilejurnal AS
	SELECT p.person_id,
    p.server_id,
    p.personevn_id,
    p.personsurname_surname AS surname,
    p.personfirname_firname AS firname,
    p.personsecname_secname AS secname,
    (((((p.personsurname_surname)::text || ' '::text) || COALESCE((ROW((p.personfirname_firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE((ROW((p.personsecname_secname)::text, 1, 1) || '.'::text), '__'::text)) AS fio,
    p.personbirthday_birthday AS birthday,
    NULL::text AS date_smert,
    p.sex_id,
        CASE
            WHEN (p.sex_id = 1) THEN 'М'::text
            WHEN (p.sex_id = 2) THEN 'Ж'::text
            ELSE ' '::text
        END AS sex,
    adr.address_address AS address,
    COALESCE(((((rg.lpuregiontype_name)::text || ' №'::text) || repeat(' '::text, (2 - length((rg.lpuregion_name)::text)))) || (rg.lpuregion_name)::text), ' '::text) AS uch,
    card.lpuregion_id,
    p.socstatus_id,
    s_st.socstatus_name,
    card.lpu_id,
    lpu.lpu_name,
    lpu.lpu_nick,
    prof.lpu_id AS lpuprofile_id,
    lpu_prof.lpu_name AS lpuprofile_name,
    lpu_prof.lpu_nick AS lpuprofile_nick,
    prof.persononkoprofile_id,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN ' '::text
            ELSE 'Анкета заполнена'::text
        END AS statusonkoprofile,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN 1
            ELSE 2
        END AS statusonkoprofile_id,
        CASE
            WHEN (prof.persononkoprofile_id IS NULL) THEN 'Анкета не заполнена'::text
            ELSE 'Анкета заполнена'::text
        END AS statusonkoprofile_tmp,
    prof.persononkoprofile_dtbeg,
    prof.medstafffact_id,
    COALESCE(prof.medpersonal_fin, ' '::text) AS medpersonal_fin,
    COALESCE(prof.monitored, '-1'::integer) AS monitored,
        CASE
            WHEN (prof.monitored = 2) THEN 'Необходим Онкоконтроль'::text
            WHEN (prof.monitored = 1) THEN 'Не нужен Онкоконтроль'::text
            ELSE ' '::text
        END AS monitored_name,
    prof.profileresult,
    per.person_deaddt,
        CASE
            WHEN (per.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM ((((((((dbo.personstate p
     JOIN LATERAL ( SELECT person.person_deaddt
           FROM dbo.person
          WHERE ((person.person_id = p.person_id) AND (person.person_deleted = 1))
         LIMIT 1) per ON (true))
     LEFT JOIN onko.v_profilejurnalact prof ON ((prof.person_id = p.person_id)))
     LEFT JOIN dbo.v_socstatus s_st ON ((s_st.socstatus_id = p.socstatus_id)))
     LEFT JOIN dbo.personcardstate card ON (((p.person_id = card.person_id) AND (card.lpuattachtype_id = 1))))
     LEFT JOIN LATERAL ( SELECT adr_1.server_id,
            adr_1.address_id,
            adr_1.klareatype_id,
            adr_1.klcountry_id,
            adr_1.klrgn_id,
            adr_1.klsubrgn_id,
            adr_1.klcity_id,
            adr_1.kltown_id,
            adr_1.klstreet_id,
            adr_1.address_zip,
            adr_1.address_house,
            adr_1.address_corpus,
            adr_1.address_flat,
            adr_1.address_address,
            adr_1.pmuser_insid,
            adr_1.pmuser_updid,
            adr_1.address_insdt,
            adr_1.address_upddt,
            adr_1.klareastat_id,
            adr_1.address_begdate,
            adr_1.address_nick,
            adr_1.personsprterrdop_id,
            adr_1.addressspecobject_id
           FROM dbo.v_address adr_1
          WHERE (adr_1.address_id = p.paddress_id)
         LIMIT 1) adr ON (true))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = card.lpu_id)))
     LEFT JOIN dbo.v_lpu lpu_prof ON ((lpu_prof.lpu_id = prof.lpu_id)))
     LEFT JOIN dbo.v_lpuregion rg ON (((card.lpuregion_id = rg.lpuregion_id) AND ((prof.lpu_id = rg.lpu_id) OR (prof.lpu_id IS NULL)))))
  WHERE (p.personbirthday_birthday <= dbo.dateadd('year'::character varying, '-18'::integer, dbo.getdate()));

CREATE VIEW dbo.v_address_kladr AS
	SELECT address.server_id,
    address.address_id,
    address.klareatype_id,
    address.klcountry_id,
    address.klrgn_id,
    address.klsubrgn_id,
    address.klcity_id,
    address.kltown_id,
    address.klstreet_id,
    address.address_zip,
    address.address_house,
    address.address_corpus,
    address.address_flat,
    address.address_address,
    address.pmuser_insid,
    address.pmuser_updid,
    address.address_insdt,
    address.address_upddt,
    COALESCE(NULLIF(rtrim((kls.kladr_code)::text), ''::text), NULLIF(rtrim((town.kladr_code)::text), ''::text), NULLIF(rtrim((city.kladr_code)::text), ''::text), NULLIF(rtrim((subrgn.kladr_code)::text), ''::text), NULLIF(rtrim((rgn.kladr_code)::text), ''::text)) AS kladr_code,
    COALESCE(NULLIF(rtrim((kls.kladr_ocatd)::text), ''::text), NULLIF(rtrim((town.kladr_ocatd)::text), ''::text), NULLIF(rtrim((city.kladr_ocatd)::text), ''::text), NULLIF(rtrim((subrgn.kladr_ocatd)::text), ''::text), NULLIF(rtrim((rgn.kladr_ocatd)::text), ''::text)) AS kladr_ocatd,
    address.address_nick
   FROM (((((dbo.address
     LEFT JOIN LATERAL ( SELECT kls_1.klstreet_id,
            kls_1.klarea_id,
            kls_1.klsocr_id,
            kls_1.klstreet_name,
            kls_1.kladr_code,
            kls_1.kladr_index,
            kls_1.kladr_gninmb,
            kls_1.kladr_uno,
            kls_1.kladr_ocatd,
            kls_1.kladr_actual,
            kls_1.klstreet_oid,
            kls_1.pmuser_insid,
            kls_1.pmuser_updid,
            kls_1.klstreet_insdt,
            kls_1.klstreet_upddt,
            kls_1.server_id,
            kls_1.klstreet_localname,
            kls_1.klstreet_aoguid,
            kls_1.klstreet_pguid,
            kls_1.klstreet_oktmo,
            kls_1.klstreet_begdt,
            kls_1.klstreet_enddt,
            kls_1.klstreet_aoid
           FROM dbo.klstreet kls_1
          WHERE (kls_1.klstreet_id = address.klstreet_id)
         LIMIT 1) kls ON (true))
     LEFT JOIN LATERAL ( SELECT town_1.klarea_id,
            town_1.klsocr_id,
            town_1.klcountry_id,
            town_1.klarealevel_id,
            town_1.klarea_pid,
            town_1.klarea_name,
            town_1.kladr_code,
            town_1.kladr_index,
            town_1.kladr_gninmb,
            town_1.kladr_uno,
            town_1.kladr_ocatd,
            town_1.kladr_actual,
            town_1.klarea_oid,
            town_1.pmuser_insid,
            town_1.pmuser_updid,
            town_1.klarea_insdt,
            town_1.klarea_upddt,
            town_1.server_id,
            town_1.klareacentretype_id,
            town_1.klarea_localname,
            town_1.klarea_aoguid,
            town_1.klarea_pguid,
            town_1.klarea_oktmo,
            town_1.klarea_begdt,
            town_1.klarea_enddt,
            town_1.klarea_aoid
           FROM dbo.klarea town_1
          WHERE (town_1.klarea_id = address.kltown_id)
         LIMIT 1) town ON (true))
     LEFT JOIN LATERAL ( SELECT city_1.klarea_id,
            city_1.klsocr_id,
            city_1.klcountry_id,
            city_1.klarealevel_id,
            city_1.klarea_pid,
            city_1.klarea_name,
            city_1.kladr_code,
            city_1.kladr_index,
            city_1.kladr_gninmb,
            city_1.kladr_uno,
            city_1.kladr_ocatd,
            city_1.kladr_actual,
            city_1.klarea_oid,
            city_1.pmuser_insid,
            city_1.pmuser_updid,
            city_1.klarea_insdt,
            city_1.klarea_upddt,
            city_1.server_id,
            city_1.klareacentretype_id,
            city_1.klarea_localname,
            city_1.klarea_aoguid,
            city_1.klarea_pguid,
            city_1.klarea_oktmo,
            city_1.klarea_begdt,
            city_1.klarea_enddt,
            city_1.klarea_aoid
           FROM dbo.klarea city_1
          WHERE (city_1.klarea_id = address.klcity_id)
         LIMIT 1) city ON (true))
     LEFT JOIN LATERAL ( SELECT subrgn_1.klarea_id,
            subrgn_1.klsocr_id,
            subrgn_1.klcountry_id,
            subrgn_1.klarealevel_id,
            subrgn_1.klarea_pid,
            subrgn_1.klarea_name,
            subrgn_1.kladr_code,
            subrgn_1.kladr_index,
            subrgn_1.kladr_gninmb,
            subrgn_1.kladr_uno,
            subrgn_1.kladr_ocatd,
            subrgn_1.kladr_actual,
            subrgn_1.klarea_oid,
            subrgn_1.pmuser_insid,
            subrgn_1.pmuser_updid,
            subrgn_1.klarea_insdt,
            subrgn_1.klarea_upddt,
            subrgn_1.server_id,
            subrgn_1.klareacentretype_id,
            subrgn_1.klarea_localname,
            subrgn_1.klarea_aoguid,
            subrgn_1.klarea_pguid,
            subrgn_1.klarea_oktmo,
            subrgn_1.klarea_begdt,
            subrgn_1.klarea_enddt,
            subrgn_1.klarea_aoid
           FROM dbo.klarea subrgn_1
          WHERE (subrgn_1.klarea_id = address.klsubrgn_id)
         LIMIT 1) subrgn ON (true))
     LEFT JOIN LATERAL ( SELECT rgn_1.klarea_id,
            rgn_1.klsocr_id,
            rgn_1.klcountry_id,
            rgn_1.klarealevel_id,
            rgn_1.klarea_pid,
            rgn_1.klarea_name,
            rgn_1.kladr_code,
            rgn_1.kladr_index,
            rgn_1.kladr_gninmb,
            rgn_1.kladr_uno,
            rgn_1.kladr_ocatd,
            rgn_1.kladr_actual,
            rgn_1.klarea_oid,
            rgn_1.pmuser_insid,
            rgn_1.pmuser_updid,
            rgn_1.klarea_insdt,
            rgn_1.klarea_upddt,
            rgn_1.server_id,
            rgn_1.klareacentretype_id,
            rgn_1.klarea_localname,
            rgn_1.klarea_aoguid,
            rgn_1.klarea_pguid,
            rgn_1.klarea_oktmo,
            rgn_1.klarea_begdt,
            rgn_1.klarea_enddt,
            rgn_1.klarea_aoid
           FROM dbo.klarea rgn_1
          WHERE (rgn_1.klarea_id = address.klrgn_id)
         LIMIT 1) rgn ON (true));

-- DEPCY: This VIEW is a dependency of VIEW: dbo.v_emkformreport

CREATE VIEW dbo.v_deputykind AS
	SELECT deputykind.deputykind_id,
    deputykind.deputykind_code,
    deputykind.deputykind_name,
    deputykind.pmuser_insid,
    deputykind.pmuser_updid,
    deputykind.deputykind_insdt,
    deputykind.deputykind_upddt
   FROM dbo.deputykind
  WHERE (1 = 1);

-- DEPCY: This VIEW is a dependency of VIEW: dbo.v_emkformreport

CREATE VIEW dbo.v_evnps_rpt AS
	SELECT evn.evnclass_id,
    evn.evn_id AS evnps_id,
    (evn.evn_setdt)::date AS evnps_setdate,
    (to_char(evn.evn_setdt, 'HH24:MI:SS'::text))::character varying(5) AS evnps_settime,
    (evn.evn_diddt)::date AS evnps_diddate,
    (to_char(evn.evn_diddt, 'HH24:MI:SS'::text))::character varying(5) AS evnps_didtime,
    (evn.evn_disdt)::date AS evnps_disdate,
    (to_char(evn.evn_disdt, 'HH24:MI:SS'::text))::character varying(5) AS evnps_distime,
    evn.evn_pid AS evnps_pid,
    evn.evn_rid AS evnps_rid,
    evn.lpu_id,
    evn.server_id,
    evn.personevn_id,
    personevn.person_id,
    evn.evn_setdt AS evnps_setdt,
    evn.evn_disdt AS evnps_disdt,
    evn.evn_diddt AS evnps_diddt,
    evn.evn_insdt AS evnps_insdt,
    evn.evn_upddt AS evnps_upddt,
    evn.evn_index AS evnps_index,
    evn.evn_count AS evnps_count,
    evn.pmuser_insid,
    evn.pmuser_updid,
    evnps.leavetype_id,
    evnps.evnps_numcard,
    evnps.person_age,
    evnps.evnps_iscont,
    evnps.diag_id,
    evnps.mes_id,
    evnps.diag_aid,
    evnps.diag_pid,
    evnps.diag_did,
    evnps.evndirection_id,
    evnps.prehosparrive_id,
    evnps.prehospdirect_id,
    evnps.prehosptoxic_id,
    evnps.paytype_id,
    evnps.prehosptrauma_id,
    evnps.prehosptype_id,
    evnps.lpu_did,
    evnps.org_did,
    evnps.lpusection_did,
    evnps.orgmilitary_did,
    evnps.lpusection_pid,
    evnps.medpersonal_pid,
    evnps.evnps_phasedescr_pid,
    evnps.evnps_phasedescr_did,
    evnps.evndirection_num,
    evnps.evndirection_setdt,
    evnps.evnps_codeconv,
    evnps.evnps_numconv,
    evnps.evnps_timedesease,
    evnps.evnps_hospcount,
    evnps.evnps_isunlaw,
    evnps.evnps_isunport,
    evnps.evnps_isimperhosp,
    evnps.evnps_isshortvolume,
    evnps.evnps_iswrongcure,
    evnps.evnps_isdiagmismatch,
    evnps.mes_oldcode,
    ((date_part('day'::text, evn.evn_disdt) - date_part('day'::text, evn.evn_setdt)) + abs((sign((date_part('day'::text, evn.evn_disdt) - date_part('day'::text, evn.evn_setdt))) - (1)::double precision))) AS evnps_koikodni1,
    ((date_part('day'::text, evn.evn_disdt) - date_part('day'::text, evn.evn_setdt)) + (1)::double precision) AS evnps_koikodni2,
    v_entrancemodetype.entrancemodetype_name AS evnps_entrancemode,
    evnps.evnps_drugactions,
    evnps.deputykind_id,
    deputy.deputykind_name,
    evnps.evnps_deputyfio,
    evnps.evnps_deputycontact,
    timedesease.timedeseasetype_name,
        CASE
            WHEN (evnps.lpu_did IS NOT NULL) THEN lpu_did.lpu_nick
            WHEN (evnps.org_did IS NOT NULL) THEN org_did.org_name
            WHEN (evnps.lpusection_did IS NOT NULL) THEN lpusection_did.lpusection_name
            ELSE NULL::character varying
        END AS whoorgdirected,
        CASE
            WHEN (evnps.medpersonal_did IS NOT NULL) THEN medpersonal_did.person_fio
            ELSE NULL::text
        END AS whomedpersonaldirected
   FROM (((((((((dbo.evnps
     JOIN dbo.evn ON ((evn.evn_id = evnps.evn_id)))
     JOIN dbo.v_personevn personevn ON (((evn.personevn_id = personevn.personevn_id) AND (evn.server_id = personevn.server_id))))
     LEFT JOIN dbo.v_lpu lpu_did ON ((lpu_did.lpu_id = evnps.lpu_did)))
     LEFT JOIN dbo.v_org org_did ON ((org_did.org_id = evnps.org_did)))
     LEFT JOIN LATERAL ( SELECT mp.person_fio
           FROM dbo.v_medpersonal mp
          WHERE (mp.medpersonal_id = evnps.medpersonal_did)
          ORDER BY mp.workdata_begdate DESC
         LIMIT 1) medpersonal_did ON (true))
     LEFT JOIN dbo.v_lpusection lpusection_did ON ((lpusection_did.lpusection_id = evnps.lpusection_did)))
     LEFT JOIN dbo.v_deputykind deputy ON ((deputy.deputykind_id = evnps.deputykind_id)))
     LEFT JOIN dbo.v_entrancemodetype ON ((v_entrancemodetype.entrancemodetype_id = evnps.entrancemodetype_id)))
     LEFT JOIN nsi.v_timedeseasetype timedesease ON ((timedesease.timedeseasetype_id = evnps.timedeseasetype_id)))
  WHERE (evn.evn_deleted = 1);

CREATE VIEW dbo.v_emkformreport AS
	SELECT evnps.evnps_id,
    person.person_id,
    lpu.lpu_id,
    lpu.lpu_name,
    ((rtrim(COALESCE((' '::text || (addresslpu.address_address)::text), ''::text)) || ' '::text) || rtrim(COALESCE((' '::text || (lpu.org_phone)::text), ''::text))) AS addresslpu,
    evnps.evnps_numcard,
    evnps.evnps_setdt,
    evnps.evnps_disdt,
    lpusection.lpusection_name,
    lsw.lpusectionward_name,
    evnps.evnps_entrancemode,
    evnps.evnps_drugactions,
        CASE
            WHEN (evnps.leavetype_id = 5) THEN lsection.lpusection_name
            ELSE NULL::character varying
        END AS lsection_name,
        CASE
            WHEN (lpuunit.lpuunittype_id = 1) THEN evnps.evnps_koikodni1
            ELSE evnps.evnps_koikodni2
        END AS koikodni,
    prehosparrive.prehosparrive_name,
    ((((COALESCE(rtrim((person.person_surname)::text), ''::text) || ' '::text) || COALESCE(rtrim((person.person_firname)::text), ''::text)) || ' '::text) || COALESCE(rtrim((person.person_secname)::text), ''::text)) AS fio,
    sex.sex_name,
        CASE
            WHEN (evnps.person_age >= 1) THEN dbo.ageymd(person.person_birthday, (evnps.evnps_setdate)::timestamp without time zone, 1)
            ELSE
            CASE
                WHEN (dbo.ageymd(person.person_birthday, (evnps.evnps_setdate)::timestamp without time zone, 1) < 1) THEN dbo.ageymd(person.person_birthday, (evnps.evnps_setdate)::timestamp without time zone, 2)
                ELSE
                CASE
                    WHEN (dbo.ageymd(person.person_birthday, (evnps.evnps_setdate)::timestamp without time zone, 2) < 1) THEN dbo.ageymd(person.person_birthday, (evnps.evnps_setdate)::timestamp without time zone, 3)
                    ELSE NULL::integer
                END
            END
        END AS age,
    address.address_address,
    person.person_phone AS personphone_phone,
    evnps.deputykind_name,
    evnps.evnps_deputyfio,
    evnps.evnps_deputycontact,
    orgjob.org_name,
    evnps.timedeseasetype_name,
    person.person_ednum,
    post.post_name,
    evnps.whoorgdirected,
    evnps.whomedpersonaldirected,
        CASE
            WHEN ((evnps.prehosptype_id = 1) OR (evnps.prehosptype_id = 3)) THEN 'да'::text
            ELSE 'нет'::text
        END AS extr,
    evnps.evnps_timedesease,
        CASE
            WHEN (evnps.prehosptype_id = 2) THEN 'да'::text
            ELSE 'нет'::text
        END AS pl,
    ((COALESCE(rtrim((diagdir.diag_code)::text), ''::text) || ' '::text) || COALESCE(rtrim((diagdir.diag_name)::text), ''::text)) AS diagdir_name,
    evnps.evnps_phasedescr_pid,
    evnps.evnps_phasedescr_did,
    ((COALESCE(rtrim((diagpriem.diag_code)::text), ''::text) || ' '::text) || COALESCE(rtrim((diagpriem.diag_name)::text), ''::text)) AS diagpriem_name,
    evnps.evnps_setdt AS evnps_setdate,
    ((COALESCE(rtrim((diag.diag_code)::text), ''::text) || ' '::text) || COALESCE(rtrim((diag.diag_name)::text), ''::text)) AS diag_name,
    evnsection.evnsection_setdate,
    ((COALESCE(rtrim((diagosl.diag_code)::text), ''::text) || ' '::text) || COALESCE(rtrim((diagosl.diag_name)::text), ''::text)) AS diagosl_name,
    ((COALESCE(rtrim((diagsop.diag_code)::text), ''::text) || ' '::text) || COALESCE(rtrim((diagsop.diag_name)::text), ''::text)) AS diagsop_name,
    leavetype.leavetype_name,
    resultdesease.resultdesease_name,
    person.person_birthday,
    area.klareatype_name,
    area.klareatype_sysnick
   FROM (((((((((((((((((((((((((((dbo.v_evnps_rpt evnps
     JOIN dbo.v_evnsection evnsection ON ((evnsection.evnsection_pid = evnps.evnps_id)))
     JOIN dbo.v_lpusection lpusection ON ((lpusection.lpusection_id = evnsection.lpusection_id)))
     JOIN dbo.lpuunit ON ((lpuunit.lpuunit_id = lpusection.lpuunit_id)))
     JOIN dbo.v_lpu_all lpu ON ((lpu.lpu_id = evnps.lpu_id)))
     JOIN dbo.org ON ((org.org_id = lpu.org_id)))
     JOIN dbo.v_personstate person ON ((person.person_id = evnps.person_id)))
     JOIN dbo.sex ON ((sex.sex_id = person.sex_id)))
     LEFT JOIN dbo.diag ON ((diag.diag_id = evnps.diag_id)))
     LEFT JOIN dbo.v_evndiagps evndiagps ON ((evndiagps.evndiagps_pid = evnps.evnps_id)))
     LEFT JOIN dbo.diag diagosl ON (((diagosl.diag_id = evndiagps.diag_id) AND (evndiagps.diagsetclass_id = 2))))
     LEFT JOIN dbo.diag diagsop ON (((diagsop.diag_id = evndiagps.diag_id) AND (evndiagps.diagsetclass_id = 3))))
     LEFT JOIN dbo.address addresslpu ON ((addresslpu.address_id = lpu.uaddress_id)))
     LEFT JOIN dbo.v_lpusectionward lsw ON ((lsw.lpusectionward_id = evnsection.lpusection_id)))
     LEFT JOIN dbo.v_evnothersection othersection ON ((evnps.evnps_id = othersection.evnothersection_pid)))
     LEFT JOIN dbo.v_lpusection lsection ON ((lsection.lpusection_id = othersection.lpusection_oid)))
     LEFT JOIN dbo.prehosparrive ON ((prehosparrive.prehosparrive_id = evnps.prehosparrive_id)))
     LEFT JOIN dbo.address ON ((address.address_id = person.paddress_id)))
     LEFT JOIN dbo.job ON ((job.job_id = person.job_id)))
     LEFT JOIN dbo.org orgjob ON ((orgjob.org_id = job.org_id)))
     LEFT JOIN dbo.post ON ((post.post_id = job.post_id)))
     LEFT JOIN dbo.v_lpusection lpusectiondir ON ((lpusectiondir.lpusection_id = evnps.lpusection_did)))
     LEFT JOIN dbo.diag diagdir ON ((diagdir.diag_id = evnps.diag_did)))
     LEFT JOIN dbo.diag diagpriem ON ((diagpriem.diag_id = evnps.diag_pid)))
     LEFT JOIN dbo.leavetype ON ((leavetype.leavetype_id = evnps.leavetype_id)))
     LEFT JOIN dbo.v_evnleave evnleave ON ((evnleave.evnleave_pid = evnps.evnps_id)))
     LEFT JOIN dbo.resultdesease ON ((resultdesease.resultdesease_id = evnleave.resultdesease_id)))
     LEFT JOIN dbo.v_klareatype area ON ((area.klareatype_id = address.klareatype_id)));

-- DEPCY: This VIEW is a dependency of VIEW: dbo.v_documentucost_lite

CREATE VIEW dbo.v_documentucstr AS
	SELECT documentucstr.documentucstr_id,
    documentucstr.documentucstr_oid,
    documentucstr.documentuc_id,
    documentucstr.drug_id,
    documentucstr.drugfinance_id,
    documentucstr.drugnds_id,
    documentucstr.drugproducer_id,
    documentucstr.documentucstr_price,
    documentucstr.documentucstr_pricer,
    documentucstr.documentucstr_edcount,
    documentucstr.documentucstr_count,
    documentucstr.documentucstr_sum,
    documentucstr.documentucstr_sumr,
    documentucstr.documentucstr_sumnds,
    documentucstr.documentucstr_sumndsr,
    documentucstr.documentucstr_ser,
    documentucstr.documentucstr_certnum,
    documentucstr.documentucstr_certdate,
    documentucstr.documentucstr_certgodndate,
    documentucstr.documentucstr_certorg,
    documentucstr.documentucstr_islab,
    documentucstr.druglabresult_name,
    documentucstr.documentucstr_rashcount,
    documentucstr.documentucstr_regdate,
    documentucstr.documentucstr_regprice,
    documentucstr.documentucstr_godndate,
    documentucstr.documentucstr_setdate,
    documentucstr.documentucstr_decl,
    documentucstr.documentucstr_barcod,
    documentucstr.documentucstr_certnm,
    documentucstr.documentucstr_certdm,
    documentucstr.documentucstr_ntu,
    documentucstr.documentucstr_nzu,
    documentucstr.documentucstr_reason,
    documentucstr.evnrecept_id,
    documentucstr.pmuser_insid,
    documentucstr.pmuser_updid,
    documentucstr.documentucstr_insdt,
    documentucstr.documentucstr_upddt,
    documentucstr.evndrug_id,
    documentucstr.receptotov_id,
    documentucstr.prepseries_id,
    documentucstr.documentucstr_plankolvo,
    documentucstr.okei_id,
    documentucstr.documentucstr_planprice,
    documentucstr.documentucstr_plansum,
    documentucstr.person_id,
    documentucstr.documentucstr_isnds,
    documentucstr.evncoursetreatdrug_id,
    documentucstr.whsdocumentuc_id,
    documentucstr.goodsunit_id,
    documentucstr.documentucstr_factprice,
    documentucstr.cmpcallcarddrug_id,
    documentucstr.documentucstr_execdt,
    documentucstr.drugdocumentstatus_id,
    documentucstr.storagezone_id,
    documentucstr.documentucstr_sid,
    documentucstr.goodsunit_bid,
    documentucstr.documentucstr_iszhnvlp
   FROM dbo.documentucstr
  WHERE ((1 = 1) AND ((documentucstr.documentucstr_deleted = 1) OR (documentucstr.documentucstr_deleted IS NULL)));

CREATE VIEW dbo.v_documentucost_lite AS
	SELECT vdocumentucstr.documentucstr_id,
    vdocumentucstr.documentuc_id,
    documentuc.contragent_tid,
    documentuc.contragent_sid,
    vdocumentucstr.drug_id,
    documentuc.documentuc_setdate,
    documentuc.documentuc_diddate,
    vdocumentucstr.documentucstr_godndate,
    vdocumentucstr.documentucstr_count,
    vdocumentucstr.documentucstr_price,
    vdocumentucstr.documentucstr_pricer,
    round((vdocumentucstr.documentucstr_count - fnc.expr), 4) AS documentucstr_ost,
    drugfinance.drugfinance_id,
    drugfinance.drugfinance_name,
    whsdocumentcostitemtype.whsdocumentcostitemtype_id,
    whsdocumentcostitemtype.whsdocumentcostitemtype_name,
    vdocumentucstr.documentucstr_ser,
    vdocumentucstr.documentucstr_certnum AS documentucstr_numsert,
    vdocumentucstr.documentucstr_islab
   FROM ((((dbo.v_documentucstr vdocumentucstr
     JOIN LATERAL ( SELECT d.documentuc_id,
            d.documentuc_pid,
            d.documentuc_num,
            d.documentuc_setdate,
            d.documentuc_diddate,
            d.documentuc_dognum,
            d.documentuc_dogdate,
            d.documentuc_invnum,
            d.documentuc_invdate,
            d.documentuc_sum,
            d.documentuc_sumr,
            d.documentuc_sumnds,
            d.documentuc_sumndsr,
            d.lpu_id,
            d.contragent_id,
            d.contragent_sid,
            d.mol_sid,
            d.contragent_tid,
            d.mol_tid,
            d.drugfinance_id,
            d.drugdocumenttype_id,
            d.drugdocumentstatus_id,
            d.pmuser_insid,
            d.pmuser_updid,
            d.documentuc_insdt,
            d.documentuc_upddt,
            d.org_id,
            d.storage_sid,
            d.subaccounttype_sid,
            d.storage_tid,
            d.subaccounttype_tid,
            d.whsdocumentcostitemtype_id,
            d.whsdocumentuc_id,
            d.drugdocumentclass_id,
            d.documentuc_plandt,
            d.documentuc_begdt,
            d.documentuc_enddt,
            d.documentuc_invoicenum,
            d.documentuc_invoicedate,
            d.emergencyteam_id,
            d.documentuc_isimport,
            d.storagezone_sid,
            d.storagezone_tid,
            d.person_id,
            d.evnreceptgeneraldruglink_id,
            d.mdlpstatus_id,
            d.pmuser_delid,
            d.documentuc_deldt,
            d.documentuc_deleted
           FROM dbo.documentuc d
          WHERE ((d.documentuc_id = vdocumentucstr.documentuc_id) AND (d.drugdocumenttype_id < 6) AND (COALESCE(d.documentuc_deleted, (1)::bigint) = 1))
         LIMIT 1) documentuc ON (true))
     LEFT JOIN dbo.drugfinance ON ((drugfinance.drugfinance_id = documentuc.drugfinance_id)))
     LEFT JOIN dbo.whsdocumentcostitemtype ON ((whsdocumentcostitemtype.whsdocumentcostitemtype_id = documentuc.whsdocumentcostitemtype_id)))
     LEFT JOIN LATERAL ( SELECT COALESCE(sum(documentucstrrash.documentucstr_count), (0)::numeric) AS expr
           FROM (dbo.documentucstr documentucstrrash
             JOIN dbo.documentuc du ON (((du.documentuc_id = documentucstrrash.documentuc_id) AND (du.drugdocumenttype_id <> 4) AND (du.drugdocumenttype_id < 6) AND (COALESCE(du.documentuc_deleted, (1)::bigint) = 1))))
          WHERE ((documentucstrrash.documentucstr_oid = vdocumentucstr.documentucstr_id) AND (documentucstrrash.documentucstr_id <> vdocumentucstr.documentucstr_id) AND (documentucstrrash.documentucstr_oid <> vdocumentucstr.documentucstr_id) AND (COALESCE(documentucstrrash.documentucstr_deleted, (1)::bigint) = 1))) fnc ON (true))
  WHERE (vdocumentucstr.drug_id IS NOT NULL);

CREATE VIEW dbo.v_documentucostat_lite AS
	SELECT vdocumentucstr.documentucstr_id,
    vdocumentucstr.documentuc_id,
    vdocumentucstr.drug_id,
    documentuc.documentuc_setdate,
    vdocumentucstr.documentucstr_godndate,
    vdocumentucstr.documentucstr_price,
    vdocumentucstr.documentucstr_pricer,
    (vdocumentucstr.documentucstr_count - ( SELECT COALESCE(sum(documentucstrrash.documentucstr_rashcount), (0)::numeric) AS expr1
           FROM dbo.v_documentucstr documentucstrrash
          WHERE ((documentucstrrash.documentucstr_oid = vdocumentucstr.documentucstr_id) AND (documentucstrrash.documentucstr_id <> vdocumentucstr.documentucstr_id) AND (documentucstrrash.documentuc_id <> 97)))) AS documentucstr_ost,
    drugfinance.drugfinance_id,
    drugfinance.drugfinance_name,
    whsdocumentcostitemtype.whsdocumentcostitemtype_id,
    whsdocumentcostitemtype.whsdocumentcostitemtype_name,
    vdocumentucstr.documentucstr_ser,
    vdocumentucstr.documentucstr_certnum AS documentucstr_numsert,
    vdocumentucstr.documentucstr_islab
   FROM (((dbo.v_documentucstr vdocumentucstr
     JOIN dbo.documentuc ON (((vdocumentucstr.documentuc_id = documentuc.documentuc_id) AND (documentuc.drugdocumenttype_id < 6) AND (COALESCE(documentuc.documentuc_deleted, (1)::bigint) = 1))))
     LEFT JOIN dbo.drugfinance ON ((drugfinance.drugfinance_id = documentuc.drugfinance_id)))
     LEFT JOIN dbo.whsdocumentcostitemtype ON ((whsdocumentcostitemtype.whsdocumentcostitemtype_id = documentuc.whsdocumentcostitemtype_id)))
  WHERE (vdocumentucstr.drug_id IS NOT NULL);

CREATE VIEW dbo.v_documentucostat AS
	SELECT vdocumentucstr.documentucstr_id,
    vdocumentucstr.documentuc_id,
    vdocumentucstr.drug_id,
    documentuc.documentuc_setdate,
    vdocumentucstr.documentucstr_godndate,
    vdocumentucstr.documentucstr_price,
    vdocumentucstr.documentucstr_pricer,
    (vdocumentucstr.documentucstr_count - COALESCE(sum(documentucstrrash.documentucstr_rashcount), (0)::numeric)) AS documentucstr_ost,
    drugfinance.drugfinance_id,
    drugfinance.drugfinance_name,
    vdocumentucstr.documentucstr_ser,
    vdocumentucstr.documentucstr_certnum AS documentucstr_numsert,
    vdocumentucstr.documentucstr_islab,
    ((((COALESCE((('годн. '::text || ((vdocumentucstr.documentucstr_godndate)::character varying)::text) || ', '::text), ''::text) || COALESCE((('цена '::text || ((vdocumentucstr.documentucstr_price)::character varying(20))::text) || ' р., '::text), ''::text)) || COALESCE((((('ост. '::text || (((vdocumentucstr.documentucstr_count - COALESCE(sum(documentucstrrash.documentucstr_count), (0)::numeric)))::character varying(20))::text) || ' '::text) || rtrim((drugunit.drugunit_name)::text)) || ', '::text), ''::text)) || COALESCE((('фин. '::text || rtrim((drugfinance.drugfinance_name)::text)) || ', '::text), ''::text)) || COALESCE((('сер. '::text || rtrim((vdocumentucstr.documentucstr_ser)::text)) || ' '::text), ''::text)) AS documentucstr_fullname
   FROM (((((dbo.v_documentucstr vdocumentucstr
     JOIN dbo.documentuc ON (((vdocumentucstr.documentuc_id = documentuc.documentuc_id) AND (documentuc.drugdocumenttype_id < 6) AND (COALESCE(documentuc.documentuc_deleted, (1)::bigint) = 1))))
     JOIN dbo.drugfinance ON ((drugfinance.drugfinance_id = documentuc.drugfinance_id)))
     JOIN dbo.drug ON ((drug.drug_id = vdocumentucstr.drug_id)))
     LEFT JOIN dbo.drugunit ON ((drug.drugunit_id = drugunit.drugunit_id)))
     LEFT JOIN dbo.v_documentucstr documentucstrrash ON ((documentucstrrash.documentucstr_oid = vdocumentucstr.documentucstr_id)))
  GROUP BY vdocumentucstr.documentuc_id, vdocumentucstr.documentucstr_id, documentuc.documentuc_setdate, vdocumentucstr.documentucstr_godndate, vdocumentucstr.drug_id, vdocumentucstr.documentucstr_price, vdocumentucstr.documentucstr_pricer, vdocumentucstr.documentucstr_count, drugfinance.drugfinance_name, drugfinance.drugfinance_id, vdocumentucstr.documentucstr_ser, vdocumentucstr.documentucstr_certnum, vdocumentucstr.documentucstr_islab, drugunit.drugunit_name;


CREATE VIEW dbo.v_surveytypelink AS
	SELECT surveytypelink.surveytypelink_id,
    surveytypelink.surveytype_id,
    surveytypelink.uslugacomplex_id,
    surveytypelink.surveytypelink_from,
    surveytypelink.surveytypelink_to,
    surveytypelink.dispclass_id,
    surveytypelink.sex_id,
    surveytypelink.region_id,
    surveytypelink.pmuser_insid,
    surveytypelink.pmuser_updid,
    surveytypelink.surveytypelink_insdt,
    surveytypelink.surveytypelink_upddt,
    surveytypelink.surveytypelink_isdel,
    surveytypelink.educationinstitutiontype_id,
    surveytypelink.surveytypelink_begdate,
    surveytypelink.surveytypelink_enddate,
    surveytypelink.surveytypelink_monthfrom,
    surveytypelink.surveytypelink_monthto,
    surveytypelink.surveytypelink_isneedusluga,
    surveytypelink.mes_id,
    surveytypelink.surveytypelink_isearlier,
    surveytypelink.surveytypelink_isuslpack,
    surveytypelink.surveytypelink_isprimaryflow,
    surveytypelink.surveytypelink_kolvo,
    surveytypelink.surveytypelink_isimpossible,
    surveytypelink.surveytypelink_ispay,
    surveytypelink.surveytypelink_iswow,
    surveytypelink.surveytypelink_complexsurvey,
    surveytypelink.surveytypelink_islowweight,
    surveytypelink.surveytypelink_period,
    surveytypelink.surveytypelink_isdelontype_id
   FROM dbo.surveytypelink
  WHERE ((1 = 1) AND ((surveytypelink.region_id = dbo.getregion()) OR (surveytypelink.region_id IS NULL)));



CREATE VIEW dbo.v_evnusluga AS
	SELECT evnclass.evnclass_id,
    evnclass.evnclass_name,
    evnclass.evnclass_sysnick,
    evnusluga.evn_id AS evnusluga_id,
    ((evnusluga.evn_setdt)::date)::timestamp without time zone AS evnusluga_setdate,
    (evnusluga.evn_setdt)::time without time zone AS evnusluga_settime,
    ((evnusluga.evn_disdt)::date)::timestamp without time zone AS evnusluga_disdate,
    (evnusluga.evn_disdt)::time without time zone AS evnusluga_distime,
    ((evnusluga.evn_diddt)::date)::timestamp without time zone AS evnusluga_diddate,
    (evnusluga.evn_diddt)::time without time zone AS evnusluga_didtime,
    evnusluga.evn_pid AS evnusluga_pid,
    evnusluga.evn_rid AS evnusluga_rid,
    evnusluga.lpu_id,
    evnusluga.server_id,
    evnusluga.personevn_id,
    evnusluga.evn_setdt AS evnusluga_setdt,
    evnusluga.evn_disdt AS evnusluga_disdt,
    evnusluga.evn_diddt AS evnusluga_diddt,
    evnusluga.evn_insdt AS evnusluga_insdt,
    evnusluga.evn_upddt AS evnusluga_upddt,
    evnusluga.evn_index AS evnusluga_index,
    evnusluga.evn_count AS evnusluga_count,
    evnusluga.pmuser_insid,
    evnusluga.pmuser_updid,
    evnusluga.person_id,
    evnusluga.morbus_id,
    evnusluga.evn_issigned AS evnusluga_issigned,
    evnusluga.pmuser_signid,
    evnusluga.evn_signdt AS evnusluga_signdt,
    evnusluga.evn_isarchive AS evnusluga_isarchive,
    evnusluga.evn_guid AS evnusluga_guid,
    evnusluga.evn_indexminusone AS evnusluga_indexminusone,
    evnusluga.evnstatus_id,
    evnusluga.evn_statusdate AS evnusluga_statusdate,
    evnusluga.evn_istransit AS evnusluga_istransit,
    evnusluga.paytype_id,
    evnusluga.usluga_id,
    evnusluga.medpersonal_id,
    evnusluga.uslugaplace_id,
    evnusluga.lpu_uid,
    evnusluga.lpusection_uid,
    evnusluga.evnusluga_kolvo,
    evnusluga.org_uid,
    evnusluga.uslugacomplex_id,
    evnusluga.evnusluga_iscito,
    evnusluga.medpersonal_sid,
    evnusluga.evnusluga_result,
    evnusluga.evndirection_id,
    evnusluga.uslugacomplextariff_id,
    evnusluga.evnusluga_coefftariff,
    evnusluga.mesopertype_id,
    evnusluga.evnusluga_ismodern,
    evnusluga.evnusluga_price,
    evnusluga.evnusluga_summa,
    evnusluga.evnprescr_id,
    evnusluga.evnprescrtimetable_id,
    evnusluga.evncourse_id,
    evnusluga.evnusluga_isvizitcode,
    evnusluga.evnusluga_isinreg,
    evnusluga.evnusluga_ispaid,
    evnusluga.medstafffact_id,
    evnusluga.medspecoms_id,
    evnusluga.lpusectionprofile_id,
    evnusluga.evnusluga_medpersonalcode,
    evnusluga.evnusluga_indexrep,
    evnusluga.evnusluga_indexrepinreg,
    evnusluga.diagsetclass_id,
    evnusluga.diag_id,
    evnusluga.lpudispcontract_id,
    evnusluga.evnusluga_isminususluga,
    evnusluga.mes_id,
    evnusluga.uslugaexecutionreason_id,
    evnusluga.uslugaexecutiontype_id,
    evnusluga.registry_sid,
    evnusluga.evnusluga_isapp,
    evnusluga.medstafffact_sid
   FROM (dbo.evnusluga
     JOIN dbo.evnclass ON ((evnclass.evnclass_id = evnusluga.evnclass_id)))
  WHERE ((evnusluga.evn_deleted = 1) OR (evnusluga.evn_deleted IS NULL));



CREATE VIEW dbo.v_evnvizit AS
	SELECT evnclass.evnclass_id,
    evnclass.evnclass_name,
    evnvizit.evn_id AS evnvizit_id,
    ((evnvizit.evn_setdt)::date)::timestamp without time zone AS evnvizit_setdate,
    (evnvizit.evn_setdt)::time without time zone AS evnvizit_settime,
    ((evnvizit.evn_disdt)::date)::timestamp without time zone AS evnvizit_disdate,
    (evnvizit.evn_disdt)::time without time zone AS evnvizit_distime,
    ((evnvizit.evn_diddt)::date)::timestamp without time zone AS evnvizit_diddate,
    (evnvizit.evn_diddt)::time without time zone AS evnvizit_didtime,
    evnvizit.evn_pid AS evnvizit_pid,
    evnvizit.evn_rid AS evnvizit_rid,
    evnvizit.lpu_id,
    evnvizit.server_id,
    evnvizit.personevn_id,
    evnvizit.evn_setdt AS evnvizit_setdt,
    evnvizit.evn_disdt AS evnvizit_disdt,
    evnvizit.evn_diddt AS evnvizit_diddt,
    evnvizit.evn_insdt AS evnvizit_insdt,
    evnvizit.evn_upddt AS evnvizit_upddt,
    evnvizit.evn_index AS evnvizit_index,
    evnvizit.evn_count AS evnvizit_count,
    evnvizit.pmuser_insid,
    evnvizit.pmuser_updid,
    evnvizit.person_id,
    evnvizit.morbus_id,
    evnvizit.evn_issigned AS evnvizit_issigned,
    evnvizit.pmuser_signid,
    evnvizit.evn_signdt AS evnvizit_signdt,
    evnvizit.evn_isarchive AS evnvizit_isarchive,
    evnvizit.evn_guid AS evnvizit_guid,
    evnvizit.evn_indexminusone AS evnvizit_indexminusone,
    evnvizit.evnstatus_id,
    evnvizit.evn_statusdate AS evnvizit_statusdate,
    evnvizit.evn_istransit AS evnvizit_istransit,
    evnvizit.lpusection_id,
    evnvizit.medpersonal_id,
    evnvizit.medpersonal_sid,
    evnvizit.paytype_id,
    evnvizit.evnvizit_isinreg,
    evnvizit.evndirection_id,
    evnvizit.timetablegraf_id,
    evnvizit.mes_id,
    evnvizit.evnvizit_uet,
    evnvizit.evnvizit_uetoms,
    evnvizit.evnvizit_ispaid,
    evnvizit.medstafffact_id,
    evnvizit.evnvizit_indexrep,
    evnvizit.evnvizit_indexrepinreg,
    evnvizit.lpudispcontract_id,
    evnvizit.evnvizit_isinregzno,
    evnvizit.registry_sid
   FROM (dbo.evnvizit
     JOIN dbo.evnclass ON ((evnclass.evnclass_id = evnvizit.evnclass_id)))
  WHERE ((evnvizit.evn_deleted = 1) OR (evnvizit.evn_deleted IS NULL));


CREATE VIEW dbo.v_registryerrorprof AS
	SELECT registryerror.registry_id,
    person.person_id,
    evn.server_id,
    evn.personevn_id,
    registryerror.evn_pid AS evn_id,
    evn.evnclass_id,
    registryerrortype.registryerrortype_form,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    evnvizit.medpersonal_id,
    msf.medstafffact_id,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    (((((rtrim((COALESCE(person.person_surname, ''::character varying))::text) || ' '::text) || rtrim((COALESCE(person.person_firname, ''::character varying))::text)) || ' '::text) || rtrim((COALESCE(person.person_secname, ''::character varying))::text)))::character varying AS person_fio,
    person.person_birthday,
        CASE
            WHEN (p.server_id = 0) THEN 1
            ELSE 0
        END AS person_isbdz,
    date_trunc('day'::text, evn.evnpldisp_setdt) AS evn_setdate,
    date_trunc('day'::text, evn.evnpldisp_disdt) AS evn_disdate,
    (((rtrim((lpusection.lpusection_code)::text) || '. '::text) || (lpusection.lpusection_name)::text))::character varying AS lpusection_name,
    lpusection.lpuunit_id,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evn.evnpldisp_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    evnusluga.evnusluga_setdate,
    uslugacomplex.uslugacomplex_code,
    registryerror.evn_pid,
    registryerror.registryerror_desc
   FROM (((((((((((dbo.registryerrorprof registryerror
     JOIN dbo.registryerrortype ON ((registryerrortype.registryerrortype_id = registryerror.registryerrortype_id)))
     JOIN dbo.registryerrorclass ON ((registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id)))
     JOIN dbo.lpusection ON ((lpusection.lpusection_id = registryerror.lpusection_id)))
     JOIN dbo.v_evnpldisp evn ON ((evn.evnpldisp_id = registryerror.evn_pid)))
     JOIN dbo.v_person_reg person ON (((person.server_id = evn.server_id) AND (person.personevn_id = evn.personevn_id))))
     JOIN dbo.person p ON ((p.person_id = person.person_id)))
     LEFT JOIN LATERAL ( SELECT evnvizit_1.medpersonal_id,
            evnvizit_1.lpusection_id
           FROM (dbo.v_evnvizit evnvizit_1
             JOIN dbo.v_evnusluga evnusluga_1 ON (((evnvizit_1.evnvizit_id = evnusluga_1.evnusluga_pid) AND (evnusluga_1.uslugacomplex_id IN ( SELECT DISTINCT v_surveytypelink.uslugacomplex_id
                   FROM dbo.v_surveytypelink
                  WHERE (v_surveytypelink.surveytype_id = ANY (ARRAY[(19)::bigint, (27)::bigint])))))))
          WHERE (evnvizit_1.evnvizit_pid = evn.evnpldisp_id)
         LIMIT 1) evnvizit ON (true))
     LEFT JOIN LATERAL ( SELECT msf_1.medstafffact_id
           FROM dbo.v_medstafffact msf_1
          WHERE ((msf_1.medpersonal_id = evnvizit.medpersonal_id) AND (evnvizit.lpusection_id = msf_1.lpusection_id))
          ORDER BY msf_1.postoccupationtype_id
         LIMIT 1) msf ON (true))
     LEFT JOIN dbo.lpusectionprofile ON ((lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id)))
     LEFT JOIN dbo.v_evnusluga evnusluga ON ((evnusluga.evnusluga_id = registryerror.evn_id)))
     LEFT JOIN dbo.uslugacomplex uslugacomplex ON ((uslugacomplex.uslugacomplex_id = evnusluga.uslugacomplex_id)));

CREATE VIEW dbo.v_registryerror AS
	SELECT registryerror.registry_id,
    person.person_id,
    evnvizit.server_id,
    evnvizit.personevn_id,
    registryerror.evn_pid AS evn_id,
    evnvizit.evnclass_id,
    registryerrortype.registryerrortype_form,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    evnvizit.medpersonal_id,
    msf.medstafffact_id,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    ((((rtrim((COALESCE(person.person_surname, ''::character varying))::text) || ' '::text) || rtrim((COALESCE(person.person_firname, ''::character varying))::text)) || ' '::text) || rtrim((COALESCE(person.person_secname, ''::character varying))::text)) AS person_fio,
    person.person_birthday,
        CASE
            WHEN (p.server_id = 0) THEN 1
            ELSE 0
        END AS person_isbdz,
    ((evnvizit.evnvizit_setdt)::date)::timestamp without time zone AS evn_setdate,
    ((evnvizit.evnvizit_disdt)::date)::timestamp without time zone AS evn_disdate,
    ((rtrim((lpusection.lpusection_code)::text) || '. '::text) || (lpusection.lpusection_name)::text) AS lpusection_name,
    lpusection.lpuunit_id,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evnvizit.evnvizit_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    evnusluga.evnusluga_setdate,
    uslugacomplex.uslugacomplex_code,
    registryerror.evn_pid,
    registryerror.registryerror_desc,
    registryerror.err_naturedisease
   FROM ((((((((((dbo.registryerror
     JOIN dbo.v_evnvizit evnvizit ON ((evnvizit.evnvizit_id = registryerror.evn_pid)))
     JOIN dbo.v_person_reg person ON (((person.personevn_id = evnvizit.personevn_id) AND (person.server_id = evnvizit.server_id))))
     JOIN dbo.person p ON ((p.person_id = person.person_id)))
     JOIN dbo.registryerrortype ON ((registryerrortype.registryerrortype_id = registryerror.registryerrortype_id)))
     JOIN dbo.registryerrorclass ON ((registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id)))
     JOIN dbo.lpusection ON ((lpusection.lpusection_id = registryerror.lpusection_id)))
     LEFT JOIN LATERAL ( SELECT msf_1.medstafffact_id
           FROM dbo.v_medstafffact msf_1
          WHERE ((msf_1.medpersonal_id = evnvizit.medpersonal_id) AND (evnvizit.lpusection_id = msf_1.lpusection_id))
          ORDER BY msf_1.postoccupationtype_id
         LIMIT 1) msf ON (true))
     LEFT JOIN dbo.lpusectionprofile ON ((lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id)))
     LEFT JOIN dbo.v_evnusluga evnusluga ON ((evnusluga.evnusluga_id = registryerror.evn_id)))
     LEFT JOIN dbo.uslugacomplex uslugacomplex ON ((uslugacomplex.uslugacomplex_id = evnusluga.uslugacomplex_id)));

CREATE VIEW dbo.v_evnusluga_all AS
	SELECT evnclass.evnclass_id,
    evnclass.evnclass_name,
    evnclass.evnclass_sysnick,
    evnusluga.evn_id AS evnusluga_id,
    ((evnusluga.evn_setdt)::date)::timestamp without time zone AS evnusluga_setdate,
    (evnusluga.evn_setdt)::time without time zone AS evnusluga_settime,
    ((evnusluga.evn_disdt)::date)::timestamp without time zone AS evnusluga_disdate,
    (evnusluga.evn_disdt)::time without time zone AS evnusluga_distime,
    ((evnusluga.evn_diddt)::date)::timestamp without time zone AS evnusluga_diddate,
    (evnusluga.evn_diddt)::time without time zone AS evnusluga_didtime,
    evnusluga.evn_pid AS evnusluga_pid,
    evnusluga.evn_rid AS evnusluga_rid,
    evnusluga.lpu_id,
    evnusluga.server_id,
    evnusluga.personevn_id,
    evnusluga.evn_setdt AS evnusluga_setdt,
    evnusluga.evn_disdt AS evnusluga_disdt,
    evnusluga.evn_diddt AS evnusluga_diddt,
    evnusluga.evn_insdt AS evnusluga_insdt,
    evnusluga.evn_upddt AS evnusluga_upddt,
    evnusluga.evn_index AS evnusluga_index,
    evnusluga.evn_count AS evnusluga_count,
    evnusluga.pmuser_insid,
    evnusluga.pmuser_updid,
    evnusluga.person_id,
    evnusluga.morbus_id,
    evnusluga.evn_issigned AS evnusluga_issigned,
    evnusluga.pmuser_signid,
    evnusluga.evn_signdt AS evnusluga_signdt,
    evnusluga.evn_isarchive AS evnusluga_isarchive,
    evnusluga.evn_guid AS evnusluga_guid,
    evnusluga.evn_indexminusone AS evnusluga_indexminusone,
    evnusluga.evnstatus_id,
    evnusluga.evn_statusdate AS evnusluga_statusdate,
    evnusluga.evn_istransit AS evnusluga_istransit,
    evnusluga.paytype_id,
    evnusluga.usluga_id,
    evnusluga.medpersonal_id,
    evnusluga.uslugaplace_id,
    evnusluga.lpu_uid,
    evnusluga.lpusection_uid,
    evnusluga.evnusluga_kolvo,
    evnusluga.org_uid,
    evnusluga.uslugacomplex_id,
    evnusluga.evnusluga_iscito,
    evnusluga.medpersonal_sid,
    evnusluga.evnusluga_result,
    evnusluga.evndirection_id,
    evnusluga.uslugacomplextariff_id,
    evnusluga.evnusluga_coefftariff,
    evnusluga.mesopertype_id,
    evnusluga.evnusluga_ismodern,
    evnusluga.evnusluga_price,
    evnusluga.evnusluga_summa,
    evnusluga.evnprescr_id,
    evnusluga.evnprescrtimetable_id,
    evnusluga.evncourse_id,
    evnusluga.evnusluga_isvizitcode,
    evnusluga.evnusluga_isinreg,
    evnusluga.evnusluga_ispaid,
    evnusluga.medstafffact_id,
    evnusluga.medspecoms_id,
    evnusluga.lpusectionprofile_id,
    evnusluga.evnusluga_medpersonalcode,
    evnusluga.evnusluga_indexrep,
    evnusluga.evnusluga_indexrepinreg,
    evnusluga.diagsetclass_id,
    evnusluga.diag_id,
    evnusluga.lpudispcontract_id,
    evnusluga.evnusluga_isminususluga,
    evnusluga.mes_id,
    evnusluga.uslugaexecutionreason_id,
    evnusluga.uslugaexecutiontype_id,
    evnusluga.registry_sid,
    evnusluga.evnusluga_isapp,
    evnusluga.medstafffact_sid
   FROM (dbo.evnusluga
     JOIN dbo.evnclass ON ((evnclass.evnclass_id = evnusluga.evnclass_id)))
  WHERE ((evnusluga.evn_deleted = 1) OR ((evnusluga.evn_deleted IS NULL) AND (evnclass.evnclass_id = ANY (ARRAY[(21)::bigint, (22)::bigint, (23)::bigint, (24)::bigint, (29)::bigint, (37)::bigint, (43)::bigint, (47)::bigint, (52)::bigint, (62)::bigint, (74)::bigint, (75)::bigint, (76)::bigint, (100)::bigint, (197)::bigint]))));


CREATE VIEW r1.v_registrynopolis AS
	SELECT registrynopolis.registry_id,
    registrynopolis.evn_id,
    evn.evn_rid,
    evn.server_id,
    evn.personevn_id,
    registrynopolis.person_id,
    registrynopolis.evn_code,
    registrynopolis.person_surname,
    registrynopolis.person_firname,
    registrynopolis.person_secname,
    registrynopolis.person_birthday,
    registrynopolis.pmuser_insid,
    registrynopolis.pmuser_updid,
    registrynopolis.registrynopolis_insdt,
    registrynopolis.registrynopolis_upddt,
    ls.lpusection_id,
    ls.lpusection_name,
    registrynopolis.evn_sid
   FROM ((((r1.registrynopolis
     JOIN dbo.v_evn evn ON ((evn.evn_id = registrynopolis.evn_id)))
     LEFT JOIN dbo.v_evnvizit ev ON ((registrynopolis.evn_id = ev.evnvizit_id)))
     LEFT JOIN dbo.v_evnsection es ON ((registrynopolis.evn_id = es.evnsection_id)))
     LEFT JOIN dbo.v_lpusection ls ON ((COALESCE(ev.lpusection_id, es.lpusection_id) = ls.lpusection_id)))
UNION ALL
 SELECT registrycmpnopolis.registry_id,
    registrycmpnopolis.evn_id,
    NULL::bigint AS evn_rid,
    person.server_id,
    person.personevn_id,
    registrycmpnopolis.person_id,
    NULL::character varying AS evn_code,
    registrycmpnopolis.person_surname,
    registrycmpnopolis.person_firname,
    registrycmpnopolis.person_secname,
    registrycmpnopolis.person_birthday,
    registrycmpnopolis.pmuser_insid,
    registrycmpnopolis.pmuser_updid,
    registrycmpnopolis.registrynopolis_insdt,
    registrycmpnopolis.registrynopolis_upddt,
    cmpclosecard.lpusection_id,
    ls.lpusection_name,
    NULL::bigint AS evn_sid
   FROM (((r1.registrycmpnopolis registrycmpnopolis
     JOIN dbo.v_cmpclosecard cmpclosecard ON ((registrycmpnopolis.evn_id = cmpclosecard.cmpclosecard_id)))
     LEFT JOIN dbo.v_lpusection ls ON ((cmpclosecard.lpusection_id = ls.lpusection_id)))
     JOIN dbo.v_personstate person ON ((person.person_id = registrycmpnopolis.person_id)));


-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW dbo.v_job AS
	SELECT job.server_id,
    job.job_id,
    job.org_id,
    job.orgunion_id,
    job.post_id,
    job.personjob_begdate,
    job.personjob_enddate,
    job.job_nfdata,
    job.pmuser_insid,
    job.pmuser_updid,
    job.job_insdt,
    job.job_upddt
   FROM dbo.job
  WHERE (1 = 1);

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_vac_person AS
	SELECT p.person_id,
    p.server_id,
    p.personevn_id,
    p.personsurname_surname AS surname,
    p.personfirname_firname AS firname,
    p.personsecname_secname AS secname,
    (((((p.personsurname_surname)::text || ' '::text) || COALESCE(("substring"((p.personfirname_firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((p.personsecname_secname)::text, 1, 1) || '.'::text), '__'::text)) AS fio,
    p.personbirthday_birthday AS birthday,
    NULL::text AS date_smert,
    p.sex_id,
        CASE
            WHEN (p.sex_id = 1) THEN 'М'::text
            WHEN (p.sex_id = 2) THEN 'Ж'::text
            ELSE NULL::text
        END AS sex,
    p.paddress_id,
    adr.address_address AS address,
    adr.klcountry_id,
    adr.klareastat_id,
    adr.klareatype_id,
    adr.klrgn_id,
    adr.klsubrgn_id,
    adr.klcity_id,
    adr.kltown_id,
    adr.klstreet_id,
    adr.address_house,
    (((rg.lpuregiontype_name)::text || ' №'::text) || (rg.lpuregion_name)::text) AS uch,
    card.lpuregion_id,
    p.socstatus_id,
    s_st.socstatus_name,
    card.lpu_id,
    lpu.lpu_name,
    orglpus.lpu_id AS org_lpu_id,
    orglpu.lpu_name AS org_lpu_name,
    org.org_id,
    org.org_name,
        CASE
            WHEN (org.org_id IS NULL) THEN 0
            ELSE 1
        END AS organized,
    0 AS group_risk,
    0 AS risktubercul,
    0 AS riskhepetitis,
    person.person_deaddt
   FROM ((((((((((dbo.personstate p
     JOIN LATERAL ( SELECT person_1.server_id,
            person_1.person_id,
            person_1.person_isunknown,
            person_1.person_isdead,
            person_1.bdz_id,
            person_1.lgot_id,
            person_1.promed_id,
            person_1.pmuser_insid,
            person_1.pmuser_updid,
            person_1.person_insdt,
            person_1.person_upddt,
            person_1.person_guid,
            person_1.person_deaddt,
            person_1.personclosecause_id,
            person_1.person_closedt,
            person_1.person_maxevndt,
            person_1.person_identdt,
            person_1.personidentstate_id,
            person_1.bdz_guid,
            person_1.person_deleted,
            person_1.person_deldt,
            person_1.pmuser_delid,
            person_1.person_isinerz,
            person_1.person_isencryphiv,
            person_1.person_isanonym,
            person_1.person_comment,
            person_1.person_isnotinn,
            person_1.person_isinfoms
           FROM dbo.person person_1
          WHERE (person_1.person_id = p.person_id)
         LIMIT 1) person ON (true))
     LEFT JOIN LATERAL ( SELECT s_st_1.socstatus_id,
            s_st_1.socstatus_code,
            s_st_1.socstatus_name,
            s_st_1.socstatus_sysnick,
            s_st_1.pmuser_insid,
            s_st_1.pmuser_updid,
            s_st_1.socstatus_insdt,
            s_st_1.socstatus_upddt,
            s_st_1.region_id,
            s_st_1.socstatus_agefrom,
            s_st_1.socstatus_ageto,
            s_st_1.socstatus_begdt,
            s_st_1.socstatus_enddt,
            s_st_1.socstatusrpn_id
           FROM dbo.v_socstatus s_st_1
          WHERE (s_st_1.socstatus_id = p.socstatus_id)
         LIMIT 1) s_st ON (true))
     LEFT JOIN LATERAL ( SELECT card_1.server_id,
            card_1.personcardstate_id,
            card_1.personcard_id,
            card_1.person_id,
            card_1.lpu_id,
            card_1.lpuregion_id,
            card_1.lpuattachtype_id,
            card_1.personcardstate_code,
            card_1.personcardstate_begdate,
            card_1.personcardstate_enddate,
            card_1.cardclosecause_id,
            card_1.personcard_isattachcondit,
            card_1.personcard_isattachauto,
            card_1.personcard_attachautodt,
            card_1.pmuser_insid,
            card_1.pmuser_updid,
            card_1.personcardstate_insdt,
            card_1.personcardstate_upddt,
            card_1.personcardstate_dmspolisnum,
            card_1.personcardstate_dmsbegdate,
            card_1.personcardstate_dmsenddate,
            card_1.orgsmo_id,
            card_1.personcardattach_id,
            card_1.lpuregion_fapid,
            card_1.lpuregiontype_id,
            card_1.medstafffact_id
           FROM dbo.v_personcardstate card_1
          WHERE ((card_1.person_id = p.person_id) AND (card_1.lpuattachtype_id = 1))
         LIMIT 1) card ON (true))
     LEFT JOIN LATERAL ( SELECT adr_1.server_id,
            adr_1.address_id,
            adr_1.klareatype_id,
            adr_1.klcountry_id,
            adr_1.klrgn_id,
            adr_1.klsubrgn_id,
            adr_1.klcity_id,
            adr_1.kltown_id,
            adr_1.klstreet_id,
            adr_1.address_zip,
            adr_1.address_house,
            adr_1.address_corpus,
            adr_1.address_flat,
            adr_1.address_address,
            adr_1.pmuser_insid,
            adr_1.pmuser_updid,
            adr_1.address_insdt,
            adr_1.address_upddt,
            adr_1.klareastat_id,
            adr_1.address_begdate,
            adr_1.address_nick,
            adr_1.personsprterrdop_id,
            adr_1.addressspecobject_id
           FROM dbo.v_address adr_1
          WHERE (adr_1.address_id = p.paddress_id)
         LIMIT 1) adr ON (true))
     LEFT JOIN LATERAL ( SELECT lpu_1.server_id,
            lpu_1.lpu_id,
            lpu_1.lpu_sysnick,
            lpu_1.lpu_isenable,
            lpu_1.org_id,
            lpu_1.org_code,
            lpu_1.lpu_name,
            lpu_1.lpu_nick,
            lpu_1.org_name,
            lpu_1.org_nick,
            lpu_1.lpu_email,
            lpu_1.org_www,
            lpu_1.lpu_isemailfixed,
            lpu_1.lpu_phone,
            lpu_1.uaddress_id,
            lpu_1.uaddress_address,
            lpu_1.paddress_id,
            lpu_1.paddress_address,
            lpu_1.lputype_id,
            lpu_1.lputype_code,
            lpu_1.lputype_name,
            lpu_1.lpu_regnomc,
            lpu_1.lpu_regnomn,
            lpu_1.lpu_regnomc2,
            lpu_1.lpu_regnomn2,
            lpu_1.lpu_ouz,
            lpu_1.lpu_isoblast,
            lpu_1.lpu_isoms,
            lpu_1.lpu_dognum,
            lpu_1.lpu_dogdate,
            lpu_1.lpu_glvrach,
            lpu_1.lpu_glbuh,
            lpu_1.lpu_otv,
            lpu_1.lpu_isindir,
            lpu_1.lpu_ogrn,
            lpu_1.lpu_amountpeople,
            lpu_1.lpu_omsbegdate,
            lpu_1.lpu_omsenddate,
            lpu_1.lpu_okdp,
            lpu_1.lpu_pensregnum,
            lpu_1.lpu_regdate,
            lpu_1.lpu_regnum,
            lpu_1.lpu_districtrate,
            lpu_1.lpu_fondequip,
            lpu_1.lpu_fondosn,
            lpu_1.lpu_begdate,
            lpu_1.lpu_enddate,
            lpu_1.lpulevel_id,
            lpu_1.lpusubjectionlevel_id,
            lpu_1.lpu_vizitfact,
            lpu_1.lpu_koikifact,
            lpu_1.lpu_farpoint,
            lpu_1.lpu_naselgor,
            lpu_1.lpu_naselsel,
            lpu_1.lpu_naselchild,
            lpu_1.lpu_naselvzr,
            lpu_1.lpu_naselrab,
            lpu_1.lpu_erinfo,
            lpu_1.lpu_dlobegdate,
            lpu_1.lpu_dloenddate,
            lpu_1.lpu_ambulancecount,
            lpu_1.lpu_worktime,
            lpu_1.pmuser_insid,
            lpu_1.pmuser_updid,
            lpu_1.lpu_insdt,
            lpu_1.lpu_upddt,
            lpu_1.lpu_ouzold,
            lpu_1.lpu_f003mcod,
            lpu_1.lpu_isemergencydir,
            lpu_1.lpu_isdms,
            lpu_1.mesagelputype_id,
            lpu_1.lpu_stickaddress,
            lpu_1.lpu_pid,
            lpu_1.lpu_nid,
            lpu_1.org_lid,
            lpu_1.region_id,
            lpu_1.lpu_isallowinternetmoderation,
            lpu_1.lpu_issecret,
            lpu_1.lpu_docreg,
            lpu_1.lpu_intercode,
            lpu_1.lpupmutype_id,
            lpu_1.lpu_okato,
            lpu_1.lpu_kbk,
            lpu_1.org_sticknick,
            lpu_1.org_guid,
            lpu_1.oktmo_id,
            lpu_1.touztype_id,
            lpu_1.org_tid,
            lpu_1.lpupmuclass_id,
            lpu_1.lpulevel_cid,
            lpu_1.lpu_fssregnum,
            lpu_1.org_regname,
            lpu_1.lpu_kpn,
            lpu_1.lpu_islab,
            lpu_1.lpu_istest,
            lpu_1.lpu_hospid,
            lpu_1.lpu_founder,
            lpu_1.lpuownership_id,
            lpu_1.moareafeature_id,
            lpu_1.lpu_isfrmo,
            lpu_1.lpubuildingpass_mid,
            lpu_1.lpu_ismse
           FROM dbo.v_lpu lpu_1
          WHERE (lpu_1.lpu_id = card.lpu_id)
         LIMIT 1) lpu ON (true))
     LEFT JOIN LATERAL ( SELECT j_1.server_id,
            j_1.job_id,
            j_1.org_id,
            j_1.orgunion_id,
            j_1.post_id,
            j_1.personjob_begdate,
            j_1.personjob_enddate,
            j_1.job_nfdata,
            j_1.pmuser_insid,
            j_1.pmuser_updid,
            j_1.job_insdt,
            j_1.job_upddt
           FROM dbo.v_job j_1
          WHERE (j_1.job_id = p.job_id)
         LIMIT 1) j ON (true))
     LEFT JOIN LATERAL ( SELECT org_1.server_id,
            org_1.org_id,
            org_1.org_pid,
            org_1.org_code,
            org_1.org_name,
            org_1.org_nick,
            org_1.okopf_id,
            org_1.okved_id,
            org_1.okogu_id,
            org_1.okonh_id,
            org_1.okfs_id,
            org_1.org_inn,
            org_1.org_ogrn,
            org_1.org_kpp,
            org_1.org_okpo,
            org_1.org_okato,
            org_1.org_okdp,
            org_1.org_rgn,
            org_1.org_phone,
            org_1.org_email,
            org_1.org_www,
            org_1.org_isemailfixed,
            org_1.org_rukovod,
            org_1.org_buhgalt,
            org_1.org_worktime,
            org_1.uaddress_id,
            org_1.paddress_id,
            org_1.pmuser_insid,
            org_1.pmuser_updid,
            org_1.org_insdt,
            org_1.org_upddt,
            org_1.org_kbk,
            org_1.org_sticknick,
            org_1.orgtype_id,
            org_1.region_id,
            org_1.org_begdate,
            org_1.org_enddate,
            org_1.org_description,
            org_1.org_rid,
            org_1.org_isaccess,
            org_1.departaffiltype_id,
            org_1.org_guid,
            org_1.oktmo_id,
            org_1.org_nid,
            org_1.org_regname,
            org_1.okato_id,
            org_1.org_kpn,
            org_1.org_isnotforsystem,
            org_1.org_marking,
            org_1.org_onmszcode,
            org_1.org_f003mcod,
            org_1.org_mdlpplace
           FROM dbo.v_org org_1
          WHERE (org_1.org_id = j.org_id)
         LIMIT 1) org ON (true))
     LEFT JOIN LATERAL ( SELECT orglpus_1.lpuorgserved_id,
            orglpus_1.lpu_id,
            orglpus_1.org_id,
            orglpus_1.lpuorgserved_begdate,
            orglpus_1.lpuorgserved_enddate,
            orglpus_1.pmuser_insid,
            orglpus_1.pmuser_updid,
            orglpus_1.lpuorgserved_insdt,
            orglpus_1.lpuorgserved_upddt,
            orglpus_1.lpuorgservicetype_id
           FROM dbo.lpuorgserved orglpus_1
          WHERE (orglpus_1.org_id = j.org_id)
         LIMIT 1) orglpus ON (true))
     LEFT JOIN LATERAL ( SELECT orglpu_1.server_id,
            orglpu_1.lpu_id,
            orglpu_1.lpu_sysnick,
            orglpu_1.lpu_isenable,
            orglpu_1.org_id,
            orglpu_1.org_code,
            orglpu_1.lpu_name,
            orglpu_1.lpu_nick,
            orglpu_1.org_name,
            orglpu_1.org_nick,
            orglpu_1.lpu_email,
            orglpu_1.org_www,
            orglpu_1.lpu_isemailfixed,
            orglpu_1.lpu_phone,
            orglpu_1.uaddress_id,
            orglpu_1.uaddress_address,
            orglpu_1.paddress_id,
            orglpu_1.paddress_address,
            orglpu_1.lputype_id,
            orglpu_1.lputype_code,
            orglpu_1.lputype_name,
            orglpu_1.lpu_regnomc,
            orglpu_1.lpu_regnomn,
            orglpu_1.lpu_regnomc2,
            orglpu_1.lpu_regnomn2,
            orglpu_1.lpu_ouz,
            orglpu_1.lpu_isoblast,
            orglpu_1.lpu_isoms,
            orglpu_1.lpu_dognum,
            orglpu_1.lpu_dogdate,
            orglpu_1.lpu_glvrach,
            orglpu_1.lpu_glbuh,
            orglpu_1.lpu_otv,
            orglpu_1.lpu_isindir,
            orglpu_1.lpu_ogrn,
            orglpu_1.lpu_amountpeople,
            orglpu_1.lpu_omsbegdate,
            orglpu_1.lpu_omsenddate,
            orglpu_1.lpu_okdp,
            orglpu_1.lpu_pensregnum,
            orglpu_1.lpu_regdate,
            orglpu_1.lpu_regnum,
            orglpu_1.lpu_districtrate,
            orglpu_1.lpu_fondequip,
            orglpu_1.lpu_fondosn,
            orglpu_1.lpu_begdate,
            orglpu_1.lpu_enddate,
            orglpu_1.lpulevel_id,
            orglpu_1.lpusubjectionlevel_id,
            orglpu_1.lpu_vizitfact,
            orglpu_1.lpu_koikifact,
            orglpu_1.lpu_farpoint,
            orglpu_1.lpu_naselgor,
            orglpu_1.lpu_naselsel,
            orglpu_1.lpu_naselchild,
            orglpu_1.lpu_naselvzr,
            orglpu_1.lpu_naselrab,
            orglpu_1.lpu_erinfo,
            orglpu_1.lpu_dlobegdate,
            orglpu_1.lpu_dloenddate,
            orglpu_1.lpu_ambulancecount,
            orglpu_1.lpu_worktime,
            orglpu_1.pmuser_insid,
            orglpu_1.pmuser_updid,
            orglpu_1.lpu_insdt,
            orglpu_1.lpu_upddt,
            orglpu_1.lpu_ouzold,
            orglpu_1.lpu_f003mcod,
            orglpu_1.lpu_isemergencydir,
            orglpu_1.lpu_isdms,
            orglpu_1.mesagelputype_id,
            orglpu_1.lpu_stickaddress,
            orglpu_1.lpu_pid,
            orglpu_1.lpu_nid,
            orglpu_1.org_lid,
            orglpu_1.region_id,
            orglpu_1.lpu_isallowinternetmoderation,
            orglpu_1.lpu_issecret,
            orglpu_1.lpu_docreg,
            orglpu_1.lpu_intercode,
            orglpu_1.lpupmutype_id,
            orglpu_1.lpu_okato,
            orglpu_1.lpu_kbk,
            orglpu_1.org_sticknick,
            orglpu_1.org_guid,
            orglpu_1.oktmo_id,
            orglpu_1.touztype_id,
            orglpu_1.org_tid,
            orglpu_1.lpupmuclass_id,
            orglpu_1.lpulevel_cid,
            orglpu_1.lpu_fssregnum,
            orglpu_1.org_regname,
            orglpu_1.lpu_kpn,
            orglpu_1.lpu_islab,
            orglpu_1.lpu_istest,
            orglpu_1.lpu_hospid,
            orglpu_1.lpu_founder,
            orglpu_1.lpuownership_id,
            orglpu_1.moareafeature_id,
            orglpu_1.lpu_isfrmo,
            orglpu_1.lpubuildingpass_mid,
            orglpu_1.lpu_ismse
           FROM dbo.v_lpu orglpu_1
          WHERE (orglpu_1.lpu_id = orglpus.lpu_id)
         LIMIT 1) orglpu ON (true))
     LEFT JOIN LATERAL ( SELECT rg_1.server_id,
            rg_1.lpuregion_id,
            rg_1.lpu_id,
            rg_1.lpuregiontype_id,
            rg_1.lpuregiontype_name,
            rg_1.lpuregiontype_sysnick,
            rg_1.lpuregion_name,
            rg_1.lpuregion_descr,
            rg_1.lpuregion_guid,
            rg_1.pmuser_insid,
            rg_1.pmuser_updid,
            rg_1.lpuregion_insdt,
            rg_1.lpuregion_upddt,
            rg_1.lpuregion_begdate,
            rg_1.lpuregion_enddate,
            rg_1.lpusection_id,
            rg_1.lpuregion_tfoms
           FROM dbo.v_lpuregion rg_1
          WHERE (card.lpuregion_id = rg_1.lpuregion_id)
         LIMIT 1) rg ON (true));

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_journalaccount AS
	SELECT ac.vacjournalaccount_id,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    COALESCE(pers.uch, '1'::text) AS vacjournalaccount_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS vacjournalaccount_fio,
        CASE
            WHEN (ac.vacjournalaccount_statustype_id = 2) THEN 'Привит по возрасту'::character varying
            ELSE v.vaccine_name
        END AS vaccine_name,
    v.vaccine_id,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    vac.getvactype2inoculation(ac.vacjournalaccount_id, COALESCE(ac.vacjournalaccount_vacother, 0)) AS vacjournalaccount_infection,
    vac.getvactypeid2keylist(ac.vacjournalaccount_id) AS vacjournalaccount_keylist,
    ac.vacjournalaccount_dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS vacjournalaccount_wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    ac.vacjournalaccount_age,
    pers.group_risk AS vac_person_group_risk,
    ac.vacjournalaccount_statustype_id,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    lpu.lpu_name,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    ac.vacjournalaccount_purpose_medpersonal_id,
    ac.vacjournalaccount_vac_medpersonal_id,
    ac.vacjournalaccount_reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription,
    ac.vaccineway_id,
    ac.vaccineplace_id,
    ac.medservice_id,
    pers.org_id,
    pers.organized,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    pers.lpu_id AS lpu_id_attach,
    COALESCE(ac.vacjournalaccount_vacother, 0) AS vacjournalaccount_vacother,
    ac.vacjournalaccount_vac_pmuser_id
   FROM (((((vac.vac_journalaccount ac
     JOIN LATERAL ( SELECT pers_1.person_id,
            pers_1.server_id,
            pers_1.personevn_id,
            pers_1.surname,
            pers_1.firname,
            pers_1.secname,
            pers_1.fio,
            pers_1.birthday,
            pers_1.date_smert,
            pers_1.sex_id,
            pers_1.sex,
            pers_1.paddress_id,
            pers_1.address,
            pers_1.klcountry_id,
            pers_1.klareastat_id,
            pers_1.klareatype_id,
            pers_1.klrgn_id,
            pers_1.klsubrgn_id,
            pers_1.klcity_id,
            pers_1.kltown_id,
            pers_1.klstreet_id,
            pers_1.address_house,
            pers_1.uch,
            pers_1.lpuregion_id,
            pers_1.socstatus_id,
            pers_1.socstatus_name,
            pers_1.lpu_id,
            pers_1.lpu_name,
            pers_1.org_lpu_id,
            pers_1.org_lpu_name,
            pers_1.org_id,
            pers_1.org_name,
            pers_1.organized,
            pers_1.group_risk,
            pers_1.risktubercul,
            pers_1.riskhepetitis,
            pers_1.person_deaddt
           FROM vac.v_vac_person pers_1
          WHERE (ac.person_id = pers_1.person_id)
         LIMIT 1) pers ON (true))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = ac.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = ac.vaccineplace_id)))
     LEFT JOIN LATERAL ( SELECT v_lpu.lpu_name
           FROM dbo.v_lpu
          WHERE (v_lpu.lpu_id = ac.vacjournalaccount_lpu_id)
         LIMIT 1) lpu ON (true))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = ac.vaccine_id)))
  WHERE ((ac.vacjournalaccount_statustype_id = 1) AND (COALESCE(ac.vacjournalaccount_vacother, 0) = 0));

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_inoculation AS
	SELECT i.inoculation_id,
    i.vacjournalaccount_id,
    i.nationalcalendarvac_scheme_id,
    nc.nationalcalendarvac_scheme_num,
    nc.nationalcalendarvac_sequencevac,
    nc.nationalcalendarvac_signpurpose,
    nc.nationalcalendarvac_typename AS typename,
    i.inoculation_signvacclose,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    ac.person_id,
    ac.vacjournalaccount_fio,
    ac.vacjournalaccount_age,
    ac.vacjournalaccount_uch,
    ac.vaccine_name,
    ac.vacjournalaccount_dose,
    ac.vacjournalaccount_wayplace,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    ac.vacjournalaccount_reactlocadescription AS reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription AS reactgeneraldescription,
    ac.vacjournalaccount_statustype_id,
    ac.medservice_id,
    ac.vac_person_sex,
    ac.vac_person_birthday,
    ac.vac_person_group_risk,
    ac.lpu_id,
    ac.lpu_name,
    i.vaccinetype_id,
    vt.vaccinetype_name,
    nc.type_id,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    nc.scheme_id_after,
    i2.vacjournalaccount_datevac AS datevac_old,
        CASE
            WHEN (nc.scheme_id_after IS NULL) THEN NULL::date
            ELSE ( SELECT ac_tmp.vacjournalaccount_datevac
               FROM vac.vac_journalaccount ac_tmp,
                vac.inoculation i_tmp
              WHERE (((i_tmp.nationalcalendarvac_scheme_id)::text = nc.scheme_id_first) AND (ac_tmp.vacjournalaccount_id = i_tmp.vacjournalaccount_id) AND (ac_tmp.person_id = ac.person_id))
             LIMIT 1)
        END AS start_datevac,
    ac.organized,
    i.inoculation_statustype_id
   FROM ((((vac.v_journalaccount ac
     LEFT JOIN vac.inoculation i ON ((i.vacjournalaccount_id = ac.vacjournalaccount_id)))
     LEFT JOIN vac.s_vaccinetype vt ON ((vt.vaccinetype_id = i.vaccinetype_id)))
     LEFT JOIN vac.v_nationalcalendarvac nc ON (((nc.nationalcalendarvac_scheme_id)::text = replace((i.nationalcalendarvac_scheme_id)::text, '_'::text, ''::text))))
     LEFT JOIN LATERAL ( SELECT a.vacjournalaccount_datevac
           FROM vac.inoculation i_1,
            vac.vac_journalaccount a
          WHERE (((i_1.nationalcalendarvac_scheme_id)::text = nc.scheme_id_before) AND (a.vacjournalaccount_id = i_1.vacjournalaccount_id) AND (a.vacjournalaccount_statustype_id = 1) AND (a.person_id = ac.person_id))) i2 ON (true));

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_journalvacfixed AS
	SELECT ac.vacjournalaccount_id AS journalvacfixed_id,
    ac.vacjournalaccount_purpose_medpersonal_id,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    COALESCE(pers.uch, '1'::text) AS vacjournalaccount_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS vacjournalaccount_fio,
    v.vaccine_name,
    v.vaccine_id,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    vac.getvactype2inoculation(ac.vacjournalaccount_id, COALESCE(ac.vacjournalaccount_vacother, 0)) AS vacjournalaccount_infection,
    vac.getvactypeid2keylist(ac.vacjournalaccount_id) AS vacjournalaccount_keylist,
    ac.vacjournalaccount_dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS vacjournalaccount_wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    ac.vacjournalaccount_age,
    pers.group_risk AS vac_person_group_risk,
    ac.vacjournalaccount_statustype_id,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    lpu.lpu_name,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    ac.vacjournalaccount_id,
    ac.vacjournalaccount_vac_medpersonal_id,
    ac.vacjournalaccount_reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription,
    ac.vaccineway_id,
    ac.vaccineplace_id,
    ac.medservice_id,
    pers.org_id,
    pers.organized,
    pers.org_lpu_id,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    ac.vacjournalaccount_vacother
   FROM (((((vac.vac_journalaccount ac
     LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = ac.person_id)))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = ac.vaccine_id)))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = ac.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = ac.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = ac.vacjournalaccount_lpu_id)))
  WHERE (ac.vacjournalaccount_statustype_id = 0);

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_inoculation_fixed AS
	SELECT i.inoculation_id,
    i.vacjournalaccount_id,
    i.nationalcalendarvac_scheme_id,
    nc.nationalcalendarvac_scheme_num,
    nc.nationalcalendarvac_sequencevac,
    nc.nationalcalendarvac_signpurpose,
    nc.nationalcalendarvac_typename AS typename,
    i.inoculation_signvacclose,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    ac.person_id,
    ac.vacjournalaccount_fio,
    ac.vacjournalaccount_age,
    ac.vacjournalaccount_uch,
    ac.vaccine_name,
    ac.vacjournalaccount_dose,
    ac.vacjournalaccount_wayplace,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    ac.vacjournalaccount_reactlocadescription AS reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription AS reactgeneraldescription,
    ac.vacjournalaccount_statustype_id,
    ac.medservice_id,
    ac.vac_person_sex,
    ac.vac_person_birthday,
    ac.vac_person_group_risk,
    ac.lpu_id,
    ac.lpu_name,
    i.vaccinetype_id,
    vt.vaccinetype_name,
    nc.type_id,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    nc.scheme_id_after,
        CASE
            WHEN (nc.scheme_id_after IS NULL) THEN NULL::date
            ELSE ( SELECT ac_tmp.vacjournalaccount_datevac
               FROM vac.v_journalaccount ac_tmp,
                vac.inoculation i_tmp
              WHERE (((i_tmp.nationalcalendarvac_scheme_id)::text = nc.scheme_id_first) AND (ac_tmp.vacjournalaccount_id = i_tmp.vacjournalaccount_id))
             LIMIT 1)
        END AS start_datevac
   FROM (((vac.v_journalvacfixed ac
     LEFT JOIN vac.inoculation i ON ((i.vacjournalaccount_id = ac.journalvacfixed_id)))
     LEFT JOIN vac.s_vaccinetype vt ON ((vt.vaccinetype_id = i.vaccinetype_id)))
     LEFT JOIN vac.v_nationalcalendarvac nc ON (((nc.nationalcalendarvac_scheme_id)::text = (i.nationalcalendarvac_scheme_id)::text)))
  WHERE (ac.journalvacfixed_id = i.vacjournalaccount_id);

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_inoculation_all AS
	SELECT v_inoculation.inoculation_id,
    v_inoculation.vacjournalaccount_id,
    v_inoculation.nationalcalendarvac_scheme_id,
    v_inoculation.nationalcalendarvac_scheme_num,
    v_inoculation.nationalcalendarvac_sequencevac,
    v_inoculation.nationalcalendarvac_signpurpose,
    v_inoculation.typename,
    v_inoculation.inoculation_signvacclose,
    v_inoculation.vacjournalaccount_datepurpose,
    v_inoculation.vacjournalaccount_datevac,
    v_inoculation.person_id,
    v_inoculation.vacjournalaccount_fio,
    v_inoculation.vacjournalaccount_age,
    v_inoculation.vacjournalaccount_uch,
    v_inoculation.vaccine_name,
    v_inoculation.vacjournalaccount_dose,
    v_inoculation.vacjournalaccount_wayplace,
    v_inoculation.vacjournalaccount_seria,
    v_inoculation.vacjournalaccount_period,
    v_inoculation.reactlocadescription,
    v_inoculation.reactgeneraldescription,
    v_inoculation.vacjournalaccount_statustype_id,
    v_inoculation.medservice_id,
    v_inoculation.vac_person_sex,
    v_inoculation.vac_person_birthday,
    v_inoculation.vac_person_group_risk,
    v_inoculation.lpu_id,
    v_inoculation.lpu_name,
    v_inoculation.vaccinetype_id,
    v_inoculation.vaccinetype_name,
    v_inoculation.type_id,
    v_inoculation.vacjournalaccount_datesave,
    v_inoculation.vacjournalaccount_vacdatesave,
    v_inoculation.scheme_id_after,
    v_inoculation.start_datevac,
    v_inoculation.inoculation_statustype_id,
    v_inoculation.datevac_old
   FROM vac.v_inoculation
UNION ALL
 SELECT v_inoculation_fixed.inoculation_id,
    v_inoculation_fixed.vacjournalaccount_id,
    v_inoculation_fixed.nationalcalendarvac_scheme_id,
    v_inoculation_fixed.nationalcalendarvac_scheme_num,
    v_inoculation_fixed.nationalcalendarvac_sequencevac,
    v_inoculation_fixed.nationalcalendarvac_signpurpose,
    v_inoculation_fixed.typename,
    v_inoculation_fixed.inoculation_signvacclose,
    v_inoculation_fixed.vacjournalaccount_datepurpose,
    v_inoculation_fixed.vacjournalaccount_datevac,
    v_inoculation_fixed.person_id,
    v_inoculation_fixed.vacjournalaccount_fio,
    v_inoculation_fixed.vacjournalaccount_age,
    v_inoculation_fixed.vacjournalaccount_uch,
    v_inoculation_fixed.vaccine_name,
    v_inoculation_fixed.vacjournalaccount_dose,
    v_inoculation_fixed.vacjournalaccount_wayplace,
    v_inoculation_fixed.vacjournalaccount_seria,
    v_inoculation_fixed.vacjournalaccount_period,
    v_inoculation_fixed.reactlocadescription,
    v_inoculation_fixed.reactgeneraldescription,
    v_inoculation_fixed.vacjournalaccount_statustype_id,
    v_inoculation_fixed.medservice_id,
    v_inoculation_fixed.vac_person_sex,
    v_inoculation_fixed.vac_person_birthday,
    v_inoculation_fixed.vac_person_group_risk,
    v_inoculation_fixed.lpu_id,
    v_inoculation_fixed.lpu_name,
    v_inoculation_fixed.vaccinetype_id,
    v_inoculation_fixed.vaccinetype_name,
    v_inoculation_fixed.type_id,
    v_inoculation_fixed.vacjournalaccount_datesave,
    v_inoculation_fixed.vacjournalaccount_vacdatesave,
    v_inoculation_fixed.scheme_id_after,
    v_inoculation_fixed.start_datevac,
    NULL::integer AS inoculation_statustype_id,
    NULL::date AS datevac_old
   FROM vac.v_inoculation_fixed;

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_vacpersonplan0

CREATE VIEW vac.v_vacpersonplan0_performed AS
	SELECT nc.nationalcalendarvac_additional,
    i.datevac_old AS d1,
    (i.datevac_old + '1 year'::interval) AS d2,
    i.vacjournalaccount_datevac AS d3,
    i.person_id,
    i.nationalcalendarvac_scheme_id AS scheme_id_old,
    i.vacjournalaccount_datevac AS datevac_old,
    i.start_datevac,
        CASE
            WHEN ((nc.nationalcalendarvac_additional = 1) AND (dbo.dateadd('year'::character varying, 1, (i.datevac_old)::timestamp without time zone) > i.vacjournalaccount_datevac)) THEN NULL::text
            ELSE i.scheme_id_after
        END AS scheme_id,
        CASE
            WHEN (nc.vaccineageborders_periodvactype = 1) THEN dbo.dateadd('day'::character varying, nc.vaccineageborders_periodvac, (i.vacjournalaccount_datevac)::timestamp without time zone)
            WHEN ((nc.vaccineageborders_periodvactype = 2) AND (nc.nationalcalendarvac_additional = 1)) THEN dbo.dateadd('MONTH'::character varying, nc.vaccineageborders_periodvac, (i.vacjournalaccount_datevac)::timestamp without time zone)
            WHEN (nc.vaccineageborders_periodvactype = 2) THEN dbo.dateadd('MONTH'::character varying, nc.vaccineageborders_periodvac, (i.start_datevac)::timestamp without time zone)
            WHEN ((nc.vaccineageborders_periodvactype = 3) AND (nc.nationalcalendarvac_sequencevac = 0)) THEN dbo.dateadd('YEAR'::character varying, nc.vaccineageborders_periodvac, (i.vacjournalaccount_datevac)::timestamp without time zone)
            WHEN (nc.vaccineageborders_periodvactype = 3) THEN dbo.dateadd('YEAR'::character varying, nc.vaccineageborders_periodvac, (i.start_datevac)::timestamp without time zone)
            ELSE NULL::timestamp without time zone
        END AS performed_dates,
        CASE
            WHEN (nc.vaccineageborders_periodvactype = 1) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('day'::character varying, (nc.vaccineageborders_periodvac + 1), (i.vacjournalaccount_datevac)::timestamp without time zone))
            WHEN ((nc.vaccineageborders_periodvactype = 2) AND (nc.nationalcalendarvac_additional = 1)) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('MONTH'::character varying, (nc.vaccineageborders_periodvac + 1), (i.vacjournalaccount_datevac)::timestamp without time zone))
            WHEN (nc.vaccineageborders_periodvactype = 2) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('MONTH'::character varying, (nc.vaccineageborders_periodvac + 1), (i.start_datevac)::timestamp without time zone))
            WHEN ((nc.vaccineageborders_periodvactype = 3) AND (nc.nationalcalendarvac_sequencevac = 0)) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('YEAR'::character varying, (nc.vaccineageborders_periodvac + 1), (i.vacjournalaccount_datevac)::timestamp without time zone))
            WHEN (nc.vaccineageborders_periodvactype = 3) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('YEAR'::character varying, (nc.vaccineageborders_periodvac + 1), (i.start_datevac)::timestamp without time zone))
            ELSE NULL::timestamp without time zone
        END AS performed_datee,
    nc.vaccineageborders_periodvac,
    nc.vaccineageborders_periodvactype,
    nc.nationalcalendarvac_sequencevac
   FROM vac.v_inoculation_all i,
    vac.v_nationalcalendarvac nc
  WHERE (((nc.nationalcalendarvac_scheme_id)::text = i.scheme_id_after) AND (nc.vaccineageborders_periodvac IS NOT NULL));

CREATE VIEW vac.v_vacpersonplan0 AS
	SELECT ((((pers.person_id)::character varying)::text || '_'::text) || (v_nationalcalendarvac.nationalcalendarvac_scheme_id)::text) AS personplan_id,
    pers.person_id,
    v_nationalcalendarvac.nationalcalendarvac_scheme_id,
    v_nationalcalendarvac.nationalcalendarvac_scheme_num,
    v_nationalcalendarvac.type_id,
    v_nationalcalendarvac.vaccinetype_id,
    v_nationalcalendarvac.nationalcalendarvac_vaccinetypename,
    v_nationalcalendarvac.nationalcalendarvac_typename,
    v_nationalcalendarvac.nationalcalendarvac_signpurpose,
    pers.birthday,
        CASE
            WHEN ((v_nationalcalendarvac.nationalcalendarvac_sequencevac = 1) OR (v_nationalcalendarvac.nationalcalendarvac_sequencevac IS NULL)) THEN NULL::timestamp without time zone
            ELSE pers.birthday
        END AS vacpersonplan0_datepreceding,
    COALESCE(r.status_id, 0) AS group_risk,
        CASE
            WHEN (COALESCE(r.status_id, 0) = 0) THEN '2'::text
            WHEN (COALESCE(r.status_id, 0) = 1) THEN '1'::text
            ELSE NULL::text
        END AS group_risk4query,
    b.vaccineageborders_ages,
    b.vaccineageborders_agetypes,
    per_s.periodvac_name AS vacpersonplan0_agenames,
    b.vaccineageborders_agee,
    b.vaccineageborders_agetypee,
    per_e.periodvac_name AS vacpersonplan0_agenamee,
    COALESCE(perf.performed_dates,
        CASE
            WHEN ((date_part('year'::text, pers.birthday))::integer > 3000) THEN pers.birthday
            WHEN (b.vaccineageborders_agetypes = 1) THEN dbo.dateadd('day'::character varying, b.vaccineageborders_ages, pers.birthday)
            WHEN (b.vaccineageborders_agetypes = 2) THEN dbo.dateadd('month'::character varying, b.vaccineageborders_ages, pers.birthday)
            WHEN (b.vaccineageborders_agetypes = 3) THEN dbo.dateadd('year'::character varying, b.vaccineageborders_ages, pers.birthday)
            ELSE NULL::timestamp without time zone
        END) AS vacpersonplan0_dates,
        CASE
            WHEN (perf.performed_dates IS NOT NULL) THEN perf.performed_datee
            ELSE COALESCE(
            CASE
                WHEN ((b.vaccineageborders_agee = 0) OR ((date_part('year'::text, pers.birthday))::integer > 3000)) THEN '3000-01-01 00:00:00'::timestamp without time zone
                WHEN (b.vaccineageborders_agetypee = 1) THEN dbo.dateadd('day'::character varying, b.vaccineageborders_agee, pers.birthday)
                WHEN ((b.vaccineageborders_agetypee = 2) AND (b.vaccineageborders_ages = b.vaccineageborders_agee)) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('month'::character varying, (b.vaccineageborders_agee + 1), pers.birthday))
                WHEN (b.vaccineageborders_agetypee = 2) THEN dbo.dateadd('month'::character varying, b.vaccineageborders_agee, pers.birthday)
                WHEN ((b.vaccineageborders_agetypee = 3) AND (b.vaccineageborders_ages = b.vaccineageborders_agee)) THEN dbo.dateadd('day'::character varying, '-1'::integer, dbo.dateadd('year'::character varying, (b.vaccineageborders_agee + 1), pers.birthday))
                WHEN (b.vaccineageborders_agetypee = 3) THEN dbo.dateadd('year'::character varying, b.vaccineageborders_agee, pers.birthday)
                ELSE NULL::timestamp without time zone
            END,
            CASE
                WHEN ((date_part('year'::text, pers.birthday))::integer > 3000) THEN pers.birthday
                WHEN (b.vaccineageborders_agetypes = 1) THEN dbo.dateadd('day'::character varying, b.vaccineageborders_ages, pers.birthday)
                WHEN (b.vaccineageborders_agetypes = 2) THEN dbo.dateadd('month'::character varying, b.vaccineageborders_ages, pers.birthday)
                WHEN (b.vaccineageborders_agetypes = 3) THEN dbo.dateadd('year'::character varying, b.vaccineageborders_ages, pers.birthday)
                ELSE NULL::timestamp without time zone
            END)
        END AS vacpersonplan0_datee,
    v_nationalcalendarvac.vaccineageborders_periodvac,
    v_nationalcalendarvac.vaccineageborders_periodvactype,
    v_nationalcalendarvac.nationalcalendarvac_periodvacname,
    v_nationalcalendarvac.nationalcalendarvac_sequencevac,
    v_nationalcalendarvac.novaccinations,
    pers.lpu_id,
    pers.org_id,
    pers.organized,
    pers.org_lpu_id,
    v_nationalcalendarvac.nationalcalendarvac_comment,
    perf.performed_dates,
    perf.performed_datee,
    v_nationalcalendarvac.scheme_id_first,
    v_nationalcalendarvac.vaccinetype_signscheme
   FROM (((((((vac.v_vac_person pers
     JOIN vac.v_nationalcalendarvac ON ((v_nationalcalendarvac.vaccinetype_signscheme = 1)))
     LEFT JOIN vac.vaccinerisk r ON (((pers.person_id = r.person_id) AND (v_nationalcalendarvac.vaccinetype_id = r.vaccinetype_id) AND (r.status_id = 1))))
     LEFT JOIN vac.s_vaccineageborders b ON ((b.nationalcalendarvac_id = v_nationalcalendarvac.nationalcalendarvac_id)))
     LEFT JOIN vac.s_periodvac per_s ON ((per_s.periodvac_id = v_nationalcalendarvac.vaccineageborders_agetypes)))
     LEFT JOIN vac.s_periodvac per_e ON ((per_e.periodvac_id = v_nationalcalendarvac.vaccineageborders_agetypee)))
     LEFT JOIN vac.v_vacpersonplan0_performed perf ON (((perf.person_id = pers.person_id) AND (perf.scheme_id = (v_nationalcalendarvac.nationalcalendarvac_scheme_id)::text))))
     LEFT JOIN vac.v_inoculation i ON (((i.scheme_id_after = (v_nationalcalendarvac.nationalcalendarvac_scheme_id)::text) AND (i.person_id = pers.person_id))))
  WHERE ((v_nationalcalendarvac.nationalcalendarvac_additional <> 1) OR (perf.scheme_id IS NOT NULL));

CREATE VIEW vac.v_vacpersonkart AS
	SELECT t.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    pers.birthday,
    (date_part('year'::text, age(dbo.getdate(), pers.birthday)))::integer AS vacpersonkart_age,
    pers.date_smert,
    pers.sex_id AS vac_person_sex_id,
    pers.sex AS vac_person_sex,
    pers.paddress_id,
    pers.address,
    pers.klcountry_id,
    pers.klareastat_id,
    pers.klareatype_id,
    pers.klrgn_id,
    pers.klsubrgn_id,
    pers.klcity_id,
    pers.kltown_id,
    pers.klstreet_id,
    pers.address_house,
    pers.uch AS vac_person_uch,
    pers.lpuregion_id,
    pers.socstatus_id,
    pers.socstatus_name,
    t.lpu_id,
    lpu.lpu_name,
    pers.lpu_id AS lpu_id_attach,
    pers.group_risk,
    t.vacdatesave,
    pers.org_id,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM ((( SELECT t2.person_id,
            max(t2.vacdatesave) AS vacdatesave,
            t2.lpu_id
           FROM ( SELECT pl.person_id,
                    NULL::timestamp without time zone AS vacdatesave,
                    pl.lpu_id
                   FROM vac.vac_personplanfinal pl
                UNION
                 SELECT vac_journalaccount.person_id,
                    vac_journalaccount.vacjournalaccount_vacdatesave AS vacdatesave,
                    vac_journalaccount.vacjournalaccount_lpu_id AS lpu_id
                   FROM vac.vac_journalaccount
                  WHERE (vac_journalaccount.vacjournalaccount_statustype_id = ANY (ARRAY[0, 1]))) t2
          GROUP BY t2.person_id, t2.lpu_id) t
     JOIN LATERAL ( SELECT p.person_id,
            p.server_id,
            p.personevn_id,
            p.surname,
            p.firname,
            p.secname,
            p.fio,
            p.birthday,
            p.date_smert,
            p.sex_id,
            p.sex,
            p.paddress_id,
            p.address,
            p.klcountry_id,
            p.klareastat_id,
            p.klareatype_id,
            p.klrgn_id,
            p.klsubrgn_id,
            p.klcity_id,
            p.kltown_id,
            p.klstreet_id,
            p.address_house,
            p.uch,
            p.lpuregion_id,
            p.socstatus_id,
            p.socstatus_name,
            p.lpu_id,
            p.lpu_name,
            p.org_lpu_id,
            p.org_lpu_name,
            p.org_id,
            p.org_name,
            p.organized,
            p.group_risk,
            p.risktubercul,
            p.riskhepetitis,
            p.person_deaddt
           FROM vac.v_vac_person p
          WHERE (p.person_id = t.person_id)
         LIMIT 1) pers ON (true))
     LEFT JOIN LATERAL ( SELECT v_lpu.server_id,
            v_lpu.lpu_id,
            v_lpu.lpu_sysnick,
            v_lpu.lpu_isenable,
            v_lpu.org_id,
            v_lpu.org_code,
            v_lpu.lpu_name,
            v_lpu.lpu_nick,
            v_lpu.org_name,
            v_lpu.org_nick,
            v_lpu.lpu_email,
            v_lpu.org_www,
            v_lpu.lpu_isemailfixed,
            v_lpu.lpu_phone,
            v_lpu.uaddress_id,
            v_lpu.uaddress_address,
            v_lpu.paddress_id,
            v_lpu.paddress_address,
            v_lpu.lputype_id,
            v_lpu.lputype_code,
            v_lpu.lputype_name,
            v_lpu.lpu_regnomc,
            v_lpu.lpu_regnomn,
            v_lpu.lpu_regnomc2,
            v_lpu.lpu_regnomn2,
            v_lpu.lpu_ouz,
            v_lpu.lpu_isoblast,
            v_lpu.lpu_isoms,
            v_lpu.lpu_dognum,
            v_lpu.lpu_dogdate,
            v_lpu.lpu_glvrach,
            v_lpu.lpu_glbuh,
            v_lpu.lpu_otv,
            v_lpu.lpu_isindir,
            v_lpu.lpu_ogrn,
            v_lpu.lpu_amountpeople,
            v_lpu.lpu_omsbegdate,
            v_lpu.lpu_omsenddate,
            v_lpu.lpu_okdp,
            v_lpu.lpu_pensregnum,
            v_lpu.lpu_regdate,
            v_lpu.lpu_regnum,
            v_lpu.lpu_districtrate,
            v_lpu.lpu_fondequip,
            v_lpu.lpu_fondosn,
            v_lpu.lpu_begdate,
            v_lpu.lpu_enddate,
            v_lpu.lpulevel_id,
            v_lpu.lpusubjectionlevel_id,
            v_lpu.lpu_vizitfact,
            v_lpu.lpu_koikifact,
            v_lpu.lpu_farpoint,
            v_lpu.lpu_naselgor,
            v_lpu.lpu_naselsel,
            v_lpu.lpu_naselchild,
            v_lpu.lpu_naselvzr,
            v_lpu.lpu_naselrab,
            v_lpu.lpu_erinfo,
            v_lpu.lpu_dlobegdate,
            v_lpu.lpu_dloenddate,
            v_lpu.lpu_ambulancecount,
            v_lpu.lpu_worktime,
            v_lpu.pmuser_insid,
            v_lpu.pmuser_updid,
            v_lpu.lpu_insdt,
            v_lpu.lpu_upddt,
            v_lpu.lpu_ouzold,
            v_lpu.lpu_f003mcod,
            v_lpu.lpu_isemergencydir,
            v_lpu.lpu_isdms,
            v_lpu.mesagelputype_id,
            v_lpu.lpu_stickaddress,
            v_lpu.lpu_pid,
            v_lpu.lpu_nid,
            v_lpu.org_lid,
            v_lpu.region_id,
            v_lpu.lpu_isallowinternetmoderation,
            v_lpu.lpu_issecret,
            v_lpu.lpu_docreg,
            v_lpu.lpu_intercode,
            v_lpu.lpupmutype_id,
            v_lpu.lpu_okato,
            v_lpu.lpu_kbk,
            v_lpu.org_sticknick,
            v_lpu.org_guid,
            v_lpu.oktmo_id,
            v_lpu.touztype_id,
            v_lpu.org_tid,
            v_lpu.lpupmuclass_id,
            v_lpu.lpulevel_cid,
            v_lpu.lpu_fssregnum,
            v_lpu.org_regname,
            v_lpu.lpu_kpn,
            v_lpu.lpu_islab,
            v_lpu.lpu_istest,
            v_lpu.lpu_hospid,
            v_lpu.lpu_founder,
            v_lpu.lpuownership_id,
            v_lpu.moareafeature_id,
            v_lpu.lpu_isfrmo,
            v_lpu.lpubuildingpass_mid,
            v_lpu.lpu_ismse
           FROM dbo.v_lpu
          WHERE (v_lpu.lpu_id = t.lpu_id)
         LIMIT 1) lpu ON (true));

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_inoculation4report5

CREATE VIEW vac.v_vac_personregion AS
	SELECT pers.person_id,
    pers.birthday,
    pers.lpu_id,
    pers.lpu_name,
    pers.lpuregion_id,
    reg.lpuregion_name,
    reg.lpuregiontype_name,
    reg.lpubuilding_id,
    reg.lpubuilding_name,
    reg.lpusection_id,
    reg.lpusection_name,
    reg.lpuunit_id,
    reg.lpuunit_name
   FROM (vac.v_vac_person pers
     LEFT JOIN vac.v_region2section reg ON ((reg.lpuregion_id = pers.lpuregion_id)));

CREATE VIEW vac.v_inoculation4report5 AS
	SELECT i.inoculation_id,
    ac.vacjournalaccount_id,
    ac.person_id,
    reg.birthday,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    ac.vacjournalaccount_datevac AS datevac,
    nc.type_id,
    i.vaccinetype_id,
    ac.vaccine_id,
    reg.lpu_id AS lpu_attach,
    reg.lpubuilding_id,
    reg.lpuunit_id,
    reg.lpusection_id,
        CASE
            WHEN (reg.lpu_id <> ac.vacjournalaccount_lpu_id) THEN (0)::bigint
            ELSE COALESCE(reg.lpuregion_id, (0)::bigint)
        END AS lpuregion_id,
    org.org_id,
    org.org_name,
        CASE
            WHEN (org.org_id IS NULL) THEN 0
            ELSE 1
        END AS organized,
        CASE
            WHEN ((ac.vacjournalaccount_datevac IS NULL) OR (reg.birthday IS NULL)) THEN NULL::integer
            WHEN (vac.getage(reg.birthday, (ac.vacjournalaccount_datevac)::timestamp without time zone) < 18) THEN 0
            ELSE 1
        END AS flag_age,
    ac.medservice_id
   FROM ((((((vac.vac_journalaccount ac
     JOIN vac.v_vac_personregion reg ON ((reg.person_id = ac.person_id)))
     JOIN vac.inoculation i ON ((i.vacjournalaccount_id = ac.vacjournalaccount_id)))
     JOIN dbo.personstate p ON ((p.person_id = ac.person_id)))
     JOIN LATERAL ( SELECT a.nationalcalendarvac_scheme_id AS scheme_id,
            a.type_id
           FROM vac.v_nationalcalendarvac a
          WHERE (((a.nationalcalendarvac_scheme_id)::text = (i.nationalcalendarvac_scheme_id)::text) AND ((((a.type_id)::text = '0'::text) AND (a.nationalcalendarvac_sequencevac = ( SELECT max(s_nationalcalendarvac.nationalcalendarvac_sequencevac) AS max
                   FROM vac.s_nationalcalendarvac
                  WHERE ((s_nationalcalendarvac.nationalcalendarvac_scheme_num = a.nationalcalendarvac_scheme_num) AND ((s_nationalcalendarvac.type_id)::text = '0'::text))))) OR (dbo.to_number(a.type_id) > 0)))) nc ON (true))
     LEFT JOIN dbo.v_job j ON ((j.job_id = p.job_id)))
     LEFT JOIN dbo.v_org org ON ((org.org_id = j.org_id)))
  WHERE (ac.vacjournalaccount_statustype_id = 1);

CREATE VIEW vac.v_plantuberkulin AS
	SELECT pl.plantuberkulin_id,
    pl.person_id,
    pers.server_id,
    pers.personevn_id,
    pl.plantuberkulin_dateplan,
    pers.surname,
    pers.firname,
    pers.secname,
    pers.fio,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    pl.plantuberkulin_age,
    pers.group_risk AS vac_person_group_risk,
    COALESCE(pers.uch, '1'::text) AS plantuberkulin_uch,
    pers.lpuregion_id,
    pers.address,
    pers.lpu_id,
    pers.lpu_name,
    pers.org_lpu_id AS vac_person_org_lpu_id,
    pers.org_lpu_name AS vac_person_org_lpu_name,
    0 AS plantuberkulin_typerec,
    'Запланировано'::text AS plantuberkulin_statusname,
    ''::text AS plantuberkulin_result,
    pers.org_id,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM vac.vac_plantuberkulin pl,
    vac.v_vac_person pers
  WHERE ((pers.person_id = pl.person_id) AND (pl.plantuberkulin_fixed = 0));

CREATE VIEW vac.v_personplanfinal AS
	SELECT pl.vac_personplanfinal_id,
    pl.nationalcalendarvac_scheme_id,
    nc.nationalcalendarvac_scheme_num,
    nc.nationalcalendarvac_typename AS typename,
    pl.person_id,
    pers.server_id,
    pers.personevn_id,
    pl.vac_personplanfinal_dateplan,
    pers.surname,
    pers.firname,
    pers.secname,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    pers.group_risk AS vac_person_group_risk,
    pers.uch AS vac_personplanfinal_uch,
    pers.lpuregion_id,
    pers.lpu_id,
    pers.lpu_name,
    pers.org_lpu_id AS vac_person_org_lpu_id,
    pers.org_lpu_name AS vac_person_org_lpu_name,
    pl.vac_personplanfinal_age,
    pl.type_id,
        CASE
            WHEN (((pl.type_id)::text = '0'::text) AND (pl.nationalcalendarvac_sequencevac > 0) AND (pl.nationalcalendarvac_sequencevac <= 4)) THEN (((pl.nationalcalendarvac_sequencevac)::character varying)::text || '-я вакцинация'::text)
            WHEN ((pl.type_id)::text = '0'::text) THEN 'Вакцинация'::text
            WHEN (((pl.type_id)::text = '1'::text) AND (pl.nationalcalendarvac_sequencevac > 0) AND (pl.nationalcalendarvac_sequencevac <= 4)) THEN (((pl.nationalcalendarvac_sequencevac)::character varying)::text || '-я ревакцинация'::text)
            WHEN ((pl.type_id)::text = '1'::text) THEN 'Ревакцинация'::text
            WHEN ((pl.type_id)::text = '2'::text) THEN 'Иммунизация'::text
            ELSE NULL::text
        END AS person_planfinal_typename,
    pl.vaccinetype_id,
    vt.vaccinetype_name,
    pl.nationalcalendarvac_sequencevac,
    pl.nationalcalendarvac_signpurpose,
    pl.vac_personplanfinal_dates,
    pl.vac_personplanfinal_datee,
    pl.vac_personplanfinal_insdt AS datesave,
    pers.address,
    pers.org_id,
    pers.organized,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM (((vac.vac_personplanfinal pl
     JOIN vac.s_vaccinetype vt ON ((vt.vaccinetype_id = pl.vaccinetype_id)))
     JOIN vac.v_nationalcalendarvac nc ON (((nc.nationalcalendarvac_scheme_id)::text = (pl.nationalcalendarvac_scheme_id)::text)))
     JOIN LATERAL ( SELECT p.person_id,
            p.server_id,
            p.personevn_id,
            p.surname,
            p.firname,
            p.secname,
            p.fio,
            p.birthday,
            p.date_smert,
            p.sex_id,
            p.sex,
            p.paddress_id,
            p.address,
            p.klcountry_id,
            p.klareastat_id,
            p.klareatype_id,
            p.klrgn_id,
            p.klsubrgn_id,
            p.klcity_id,
            p.kltown_id,
            p.klstreet_id,
            p.address_house,
            p.uch,
            p.lpuregion_id,
            p.socstatus_id,
            p.socstatus_name,
            p.lpu_id,
            p.lpu_name,
            p.org_lpu_id,
            p.org_lpu_name,
            p.org_id,
            p.org_name,
            p.organized,
            p.group_risk,
            p.risktubercul,
            p.riskhepetitis,
            p.person_deaddt
           FROM vac.v_vac_person p
          WHERE (p.person_id = pl.person_id)
         LIMIT 1) pers ON (true))
  WHERE (pl.vac_personplanfinal_fixed = 0);

CREATE VIEW vac.v_journalvac AS
	SELECT 1 AS type_rec,
    ('1_'::text || ((ac.vacjournalaccount_id)::character varying)::text) AS journalvac_id,
    ac.vacjournalaccount_purpose_medpersonal_id AS purpose_medpersonal_id,
    ac.vacjournalaccount_datepurpose AS datepurpose,
    ac.vacjournalaccount_datevac AS datevac,
    pers.uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS fio,
    v.vaccine_name,
    v.vaccine_id,
    ac.vacjournalaccount_seria AS seria,
    ac.vacjournalaccount_period AS period,
    vac.getvactype2inoculation(ac.vacjournalaccount_id, COALESCE(ac.vacjournalaccount_vacother, 0)) AS infection,
    ac.vacjournalaccount_dose AS dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday,
    ac.vacjournalaccount_age AS age,
    pers.group_risk AS vac_person_group_risk,
    ac.vacjournalaccount_statustype_id AS statustype_id,
        CASE
            WHEN (ac.vacjournalaccount_statustype_id = 0) THEN 'Назначено'::text
            WHEN (ac.vacjournalaccount_statustype_id = 1) THEN 'Исполнено'::text
            ELSE NULL::text
        END AS statustype_name,
        CASE
            WHEN ((ac.vacjournalaccount_statustype_id = 0) AND (ac.vacjournalaccount_datepurpose < (dbo.getdate())::date)) THEN '-1'::integer
            ELSE 0
        END AS statussrok_id,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    lpu.lpu_name,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    ac.vacjournalaccount_id,
    NULL::bigint AS journalmantu_id,
    ac.vacjournalaccount_vac_medpersonal_id AS vacmedpersonal_id,
    ac.vacjournalaccount_reactlocadescription AS reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription AS reactdescription,
    ac.vaccineway_id,
    ac.vaccineplace_id,
    ac.medservice_id,
    ms.medservice_nick,
    pers.org_id,
    pers.organized,
    pers.org_lpu_id
   FROM ((((((vac.vac_journalaccount ac
     LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = ac.person_id)))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = ac.vaccine_id)))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = ac.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = ac.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = ac.vacjournalaccount_lpu_id)))
     LEFT JOIN dbo.v_medservice ms ON ((ms.medservice_id = ac.medservice_id)))
  WHERE (ac.vacjournalaccount_statustype_id = ANY (ARRAY[0, 1]))
UNION
 SELECT 2 AS type_rec,
    ('2_'::text || ((m.journalmantu_id)::character varying)::text) AS journalvac_id,
    m.journalmantu_purpose_medpersonal_id AS purpose_medpersonal_id,
    m.journalmantu_datepurpose AS datepurpose,
    m.journalmantu_datevac AS datevac,
    pers.uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS fio,
    v.vaccine_name,
    v.vaccine_id,
    m.journalmantu_seria AS seria,
    m.journalmantu_period AS period,
    'Манту'::character varying AS infection,
    m.journalmantu_dose AS dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday,
    m.journalmantu_age AS age,
    pers.group_risk AS vac_person_group_risk,
    m.journalmantu_statustype_id AS statustype_id,
        CASE
            WHEN (m.journalmantu_statustype_id = 0) THEN 'Назначено'::text
            WHEN (m.journalmantu_statustype_id = 1) THEN 'Исполнено'::text
            ELSE NULL::text
        END AS statustype_name,
        CASE
            WHEN ((m.journalmantu_statustype_id = 0) AND (m.journalmantu_datepurpose < (dbo.getdate())::date)) THEN '-1'::integer
            ELSE 0
        END AS statussrok_id,
    m.journalmantu_lpu_id AS lpu_id,
    lpu.lpu_name,
    m.journalmantu_purposedatesave AS vacjournalaccount_datesave,
    m.journalmantu_vacdatesave AS vacjournalaccount_vacdatesave,
    NULL::bigint AS vacjournalaccount_id,
    m.journalmantu_id,
    m.journalmantu_vacmedpersonal_id AS vacmedpersonal_id,
    m.journalmantu_localreactdescription AS reactlocadescription,
    m.journalmantu_reactdescription AS reactdescription,
    m.vaccineway_id,
    m.vaccineplace_id,
    m.medservice_id,
    ms.medservice_nick,
    pers.org_id,
    pers.organized,
    pers.org_lpu_id
   FROM ((((((vac.vac_journalmantu m
     LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = m.person_id)))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = 26)))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = m.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = m.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = m.journalmantu_lpu_id)))
     LEFT JOIN dbo.v_medservice ms ON ((ms.medservice_id = m.medservice_id)))
  WHERE (m.journalmantu_statustype_id = ANY (ARRAY[0, 1]));

CREATE VIEW vac.v_journalmedtaprefusal AS
	SELECT tap.vacjournalmedtaprefusal_id,
    tap.person_id,
    pers.server_id,
    pers.personevn_id,
    COALESCE(pers.uch, '1'::text) AS vacjournalmedtaprefusal_uch,
    pers.lpuregion_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS vacjournalmedtaprefusal_fio,
    pers.sex,
    pers.birthday,
    pers.group_risk,
    tap.vaccinetype_id,
    tap.vacjournalmedtaprefusal_vaccinetypeall,
        CASE
            WHEN (tap.vacjournalmedtaprefusal_vaccinetypeall = 1) THEN 'Все прививки'::character varying
            ELSE priv.vaccinetype_name
        END AS vacjournalmedtaprefusal_infection,
    tap.vacjournalmedtaprefusal_datebegin,
    tap.vacjournalmedtaprefusal_dateend,
    tap.vacjournalmedtaprefusal_reason,
    tap.vacjournalmedtaprefusal_typerecord,
        CASE
            WHEN (tap.vacjournalmedtaprefusal_typerecord = 1) THEN 'мед. отвод'::text
            ELSE 'отказ'::text
        END AS vacjournalmedtaprefusal_nametyperec,
    pers.lpu_id,
    pers.lpu_name,
    tap.vacjournalmedtaprefusal_medpersonal_id,
    tap.vacjournalmedtaprefusal__insdt,
    pers.org_id,
    tap.vacjournalmedtaprefusal_upddt,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead
   FROM ((vac.vac_journalmedtaprefusal tap
     JOIN LATERAL ( SELECT v_vac_person.person_id,
            v_vac_person.server_id,
            v_vac_person.personevn_id,
            v_vac_person.surname,
            v_vac_person.firname,
            v_vac_person.secname,
            v_vac_person.fio,
            v_vac_person.birthday,
            v_vac_person.date_smert,
            v_vac_person.sex_id,
            v_vac_person.sex,
            v_vac_person.paddress_id,
            v_vac_person.address,
            v_vac_person.klcountry_id,
            v_vac_person.klareastat_id,
            v_vac_person.klareatype_id,
            v_vac_person.klrgn_id,
            v_vac_person.klsubrgn_id,
            v_vac_person.klcity_id,
            v_vac_person.kltown_id,
            v_vac_person.klstreet_id,
            v_vac_person.address_house,
            v_vac_person.uch,
            v_vac_person.lpuregion_id,
            v_vac_person.socstatus_id,
            v_vac_person.socstatus_name,
            v_vac_person.lpu_id,
            v_vac_person.lpu_name,
            v_vac_person.org_lpu_id,
            v_vac_person.org_lpu_name,
            v_vac_person.org_id,
            v_vac_person.org_name,
            v_vac_person.organized,
            v_vac_person.group_risk,
            v_vac_person.risktubercul,
            v_vac_person.riskhepetitis,
            v_vac_person.person_deaddt
           FROM vac.v_vac_person
          WHERE (v_vac_person.person_id = tap.person_id)
         LIMIT 1) pers ON (true))
     LEFT JOIN vac.s_vaccinetype priv ON ((priv.vaccinetype_id = tap.vaccinetype_id)))
  WHERE (tap.taprefusal_status = 1);

CREATE VIEW vac.v_journalmantufixed AS
	SELECT m.journalmantu_id AS journalmantufixed_id,
    m.journalmantu_purpose_medpersonal_id,
    m.journalmantu_datepurpose,
    m.journalmantu_datevac,
    pers.uch AS journalmantu_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS journalmantu_fio,
    pers.address,
    pr.vacpresence_seria,
    pr.vacpresence_period,
    pr.vacpresence_manufacturer,
    m.journalmantu_dose,
    m.vaccineway_id,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS journalmantu_wayplace,
    pers.sex,
    pers.birthday,
    m.journalmantu_age,
    pers.group_risk,
    m.journalmantu_lpu_id AS lpu_id,
    lpu.lpu_name,
    m.journalmantu_statustype_id,
    pers.org_id,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    m.vaccinewayplace_id
   FROM (((((vac.vac_journalmantu m
     LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = m.person_id)))
     LEFT JOIN vac.vac_presence pr ON ((pr.vacpresence_id = m.vacpresence_id)))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = m.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = m.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = m.journalmantu_lpu_id)))
  WHERE (m.journalmantu_statustype_id = 0);

CREATE VIEW vac.v_journalmantuall AS
	SELECT t.id AS journalmantuall_id,
    t.person_id,
    t.surname,
    t.firname,
    t.secname,
    t.fio,
    t.dateplan AS journalmantuall_dateplan,
    t.purposemedpersonal_id AS journalmantuall_purposemedpersonal_id,
    t.datepurpose AS journalmantuall_datepurpose,
    t.datevac AS journalmantuall_datevac,
    t.uch AS journalmantuall_uch,
    t.lpuregion_id,
    t.seria AS journalmantuall_seria,
    t.period AS journalmantuall_period,
    t.manufacturer AS journalmantuall_manufacturer,
    t.dose AS journalmantuall_dose,
    t.vaccineway_id AS journalmantuall_vaccineway_id,
    t.wayplace AS journalmantuall_wayplace,
    t.mantureactiontype_name,
    t.reactdescription AS journalmantuall_reactdescription,
    t.datereact AS journalmantuall_datereact,
    t.sex AS vac_person_sex,
    t.birthday AS vac_person_birthday,
    t.age AS journalmantuall_age,
    t.group_risk AS vac_person_group_risk,
    t.lpu_id AS vac_person_lpu_id,
    t.lpu_name AS vac_person_lpu_name,
    t.statustype_id AS journalmantuall_statustype_id,
    t.statusname AS journalmantuall_statusname,
    t.idincurrenttable,
    t.sort_id AS journalmantuall_sort_id,
    t.reactionsize,
    t.reaction30min,
    t.tubdiagnosistype_id,
    t.tubdiagnosistype_name,
    t.vaccinewayplace_id
   FROM ( SELECT ((((m.journalmantu_statustype_id)::character varying)::text || '_'::text) || ((m.journalmantu_id)::character varying)::text) AS id,
            pers.person_id,
            pers.surname,
            pers.firname,
            pers.secname,
            pers.fio,
            NULL::date AS dateplan,
            m.journalmantu_purpose_medpersonal_id AS purposemedpersonal_id,
            m.journalmantu_datepurpose AS datepurpose,
            m.journalmantu_datevac AS datevac,
            COALESCE(pers.uch, '1'::text) AS uch,
            pers.lpuregion_id,
            COALESCE(pr.vacpresence_seria, m.journalmantu_seria) AS seria,
            COALESCE(pr.vacpresence_period, m.journalmantu_period) AS period,
            COALESCE(pr.vacpresence_manufacturer, m.journalmantu_manufacturer) AS manufacturer,
            m.journalmantu_dose AS dose,
            m.vaccineway_id,
            (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS wayplace,
            mreact.mantureactiontype_name,
            m.journalmantu_reactdescription AS reactdescription,
            m.journalmantu_datereact AS datereact,
            pers.sex,
            pers.birthday,
            m.journalmantu_age AS age,
            pers.group_risk,
            m.journalmantu_lpu_id AS lpu_id,
            lpu.lpu_name,
            m.journalmantu_statustype_id AS statustype_id,
                CASE
                    WHEN (m.journalmantu_statustype_id = 0) THEN 'Назначено'::text
                    WHEN (m.journalmantu_statustype_id = 1) THEN 'Исполнено'::text
                    ELSE NULL::text
                END AS statusname,
                CASE
                    WHEN (m.journalmantu_statustype_id = 0) THEN m.journalmantu_id
                    WHEN (m.journalmantu_statustype_id = 1) THEN m.journalmantu_id
                    ELSE ('-1'::integer)::bigint
                END AS idincurrenttable,
            m.journalmantu_statustype_id AS sort_id,
            m.journalmantu_reactionsize AS reactionsize,
            m.journalmantu_reaction30min AS reaction30min,
            m.tubdiagnosistype_id,
            d.tubdiagnosistype_name,
            m.vaccinewayplace_id
           FROM (((((((vac.vac_journalmantu m
             LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = m.person_id)))
             LEFT JOIN vac.vac_presence pr ON ((pr.vacpresence_id = m.vacpresence_id)))
             LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = m.vaccineway_id)))
             LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = m.vaccineplace_id)))
             LEFT JOIN vac.s_mantureactiontype mreact ON ((mreact.mantureactiontype_id = m.mantureactiontype_id)))
             LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = m.journalmantu_lpu_id)))
             LEFT JOIN vac.s_tubdiagnosistype d ON ((d.tubdiagnosistype_id = m.tubdiagnosistype_id)))
        UNION
         SELECT ('2_'::text || ((pl.plantuberkulin_id)::character varying)::text) AS id,
            pers.person_id,
            pers.surname,
            pers.firname,
            pers.secname,
            pers.fio,
            pl.plantuberkulin_dateplan AS dateplan,
            NULL::bigint AS purposemedpersonal_id,
            NULL::date AS datepurpose,
            NULL::date AS datevac,
            COALESCE(pers.uch, '1'::text) AS uch,
            pers.lpuregion_id,
            NULL::character varying AS seria,
            NULL::date AS period,
            NULL::character varying AS manufacturer,
            NULL::character varying AS dose,
            NULL::bigint AS vaccineway_id,
            NULL::text AS wayplace,
            NULL::character varying AS mantureactiontype_name,
            NULL::character varying AS reactdescription,
            NULL::date AS datereact,
            pers.sex,
            pers.birthday,
            pl.plantuberkulin_age AS age,
            pers.group_risk,
            pers.lpu_id,
            pers.lpu_name,
            2 AS statustype_id,
            'Запланировано'::text AS statusname,
            pl.plantuberkulin_id AS asidincurrenttable,
            '-1'::integer AS sort_id,
            NULL::integer AS reactionsize,
            NULL::"bit" AS reaction30min,
            NULL::bigint AS tubdiagnosistype_id,
            NULL::character varying AS tubdiagnosistype_name,
            NULL::bigint AS vaccinewayplace_id
           FROM vac.vac_plantuberkulin pl,
            vac.v_vac_person pers
          WHERE ((pers.person_id = pl.person_id) AND ((pl.plantuberkulin_fixed IS NULL) OR (pl.plantuberkulin_fixed = 0)))) t
  WHERE (t.statustype_id <> 100);

CREATE VIEW vac.v_journalmantuaccount AS
	SELECT m.journalmantu_id,
    m.journalmantu_purpose_medpersonal_id,
    m.journalmantu_datepurpose,
    m.journalmantu_datevac,
    pers.uch AS journalmantu_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.surname,
    pers.firname,
    pers.secname,
    pers.server_id,
    pers.personevn_id,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS journalmantu_fio,
    pers.address,
    pr.vacpresence_seria,
    pr.vacpresence_period,
    pr.vacpresence_manufacturer,
    m.journalmantu_dose,
    m.vaccineway_id,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS journalmantu_wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    m.journalmantu_age,
    pers.group_risk AS vac_person_group_risk,
    m.mantureactiontype_id,
    mreact.mantureactiontype_name,
    m.journalmantu_reactdescription,
    m.journalmantu_datereact,
    m.journalmantu_lpu_id AS lpu_id,
    lpu.lpu_name,
    m.journalmantu_statustype_id,
    pers.org_id,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    m.tubdiagnosistype_id,
    d.tubdiagnosistype_name,
    m.vaccinewayplace_id
   FROM (((((((vac.vac_journalmantu m
     LEFT JOIN vac.v_vac_person pers ON ((pers.person_id = m.person_id)))
     LEFT JOIN vac.vac_presence pr ON ((pr.vacpresence_id = m.vacpresence_id)))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = m.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = m.vaccineplace_id)))
     LEFT JOIN vac.s_mantureactiontype mreact ON ((mreact.mantureactiontype_id = m.mantureactiontype_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = m.journalmantu_lpu_id)))
     LEFT JOIN vac.s_tubdiagnosistype d ON ((d.tubdiagnosistype_id = m.tubdiagnosistype_id)))
  WHERE (m.journalmantu_statustype_id = 1);

-- DEPCY: This VIEW is a dependency of VIEW: vac.v_inoculationother

CREATE VIEW vac.v_journalaccountother AS
	SELECT ac.vacjournalaccount_id,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    COALESCE(pers.uch, '1'::text) AS vacjournalaccount_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS vacjournalaccount_fio,
        CASE
            WHEN (ac.vacjournalaccount_statustype_id = 2) THEN 'Привит по возрасту'::character varying
            ELSE v.vaccine_name
        END AS vaccine_name,
    v.vaccine_id,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    vac.getvactype2inoculation(ac.vacjournalaccount_id, COALESCE(ac.vacjournalaccount_vacother, 0)) AS vacjournalaccount_infection,
    vac.getvactypeid2keylist(ac.vacjournalaccount_id) AS vacjournalaccount_keylist,
    ac.vacjournalaccount_dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS vacjournalaccount_wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    ac.vacjournalaccount_age,
    pers.group_risk AS vac_person_group_risk,
    ac.vacjournalaccount_statustype_id,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    lpu.lpu_name,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    ac.vacjournalaccount_purpose_medpersonal_id,
    ac.vacjournalaccount_vac_medpersonal_id,
    ac.vacjournalaccount_reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription,
    ac.vaccineway_id,
    ac.vaccineplace_id,
    ac.medservice_id,
    pers.org_id,
    pers.organized,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    pers.lpu_id AS lpu_id_attach
   FROM (((((vac.vac_journalaccount ac
     JOIN LATERAL ( SELECT pers_1.person_id,
            pers_1.server_id,
            pers_1.personevn_id,
            pers_1.surname,
            pers_1.firname,
            pers_1.secname,
            pers_1.fio,
            pers_1.birthday,
            pers_1.date_smert,
            pers_1.sex_id,
            pers_1.sex,
            pers_1.paddress_id,
            pers_1.address,
            pers_1.klcountry_id,
            pers_1.klareastat_id,
            pers_1.klareatype_id,
            pers_1.klrgn_id,
            pers_1.klsubrgn_id,
            pers_1.klcity_id,
            pers_1.kltown_id,
            pers_1.klstreet_id,
            pers_1.address_house,
            pers_1.uch,
            pers_1.lpuregion_id,
            pers_1.socstatus_id,
            pers_1.socstatus_name,
            pers_1.lpu_id,
            pers_1.lpu_name,
            pers_1.org_lpu_id,
            pers_1.org_lpu_name,
            pers_1.org_id,
            pers_1.org_name,
            pers_1.organized,
            pers_1.group_risk,
            pers_1.risktubercul,
            pers_1.riskhepetitis,
            pers_1.person_deaddt
           FROM vac.v_vac_person pers_1
          WHERE (ac.person_id = pers_1.person_id)
         LIMIT 1) pers ON (true))
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = ac.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = ac.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = ac.vacjournalaccount_lpu_id)))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = ac.vaccine_id)))
  WHERE (((ac.vacjournalaccount_statustype_id = 1) OR (ac.vacjournalaccount_statustype_id = 0)) AND (ac.vacjournalaccount_vacother = 1));

CREATE VIEW vac.v_inoculationother AS
	SELECT i.inoculation_id,
    i.vacjournalaccount_id,
    i.nationalcalendarvac_scheme_id,
    nc.nationalcalendarvac_scheme_num,
    nc.nationalcalendarvac_sequencevac,
    nc.nationalcalendarvac_signpurpose,
    nc.nationalcalendarvac_typename AS typename,
    i.inoculation_signvacclose,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    ac.person_id,
    ac.vacjournalaccount_fio,
    ac.vacjournalaccount_age,
    ac.vacjournalaccount_uch,
    ac.vaccine_name,
    ac.vacjournalaccount_dose,
    ac.vacjournalaccount_wayplace,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    ac.vacjournalaccount_reactlocadescription AS reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription AS reactgeneraldescription,
    ac.vacjournalaccount_statustype_id,
        CASE
            WHEN (ac.vacjournalaccount_statustype_id = 0) THEN 'Назначено'::text
            WHEN (ac.vacjournalaccount_statustype_id = 1) THEN 'Исполнено'::text
            ELSE NULL::text
        END AS vacjournalaccount_statustype_name,
    ac.medservice_id,
    ac.vac_person_sex,
    ac.vac_person_birthday,
    ac.vac_person_group_risk,
    ac.lpu_id,
    ac.lpu_name,
    i.vaccinetype_id,
    vt.vaccinetype_name,
    nc.type_id,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    nc.scheme_id_after,
    i2.vacjournalaccount_datevac AS datevac_old,
        CASE
            WHEN (nc.scheme_id_after IS NULL) THEN NULL::date
            ELSE ( SELECT ac_tmp.vacjournalaccount_datevac
               FROM vac.v_journalaccount ac_tmp,
                vac.inoculation i_tmp
              WHERE (((i_tmp.nationalcalendarvac_scheme_id)::text = nc.scheme_id_first) AND (ac_tmp.vacjournalaccount_id = i_tmp.vacjournalaccount_id) AND (ac_tmp.person_id = ac.person_id))
             LIMIT 1)
        END AS start_datevac,
    ac.organized,
    i.inoculation_statustype_id
   FROM ((((vac.v_journalaccountother ac
     LEFT JOIN vac.inoculation i ON ((i.vacjournalaccount_id = ac.vacjournalaccount_id)))
     LEFT JOIN vac.s_vaccinetype vt ON ((vt.vaccinetype_id = i.vaccinetype_id)))
     LEFT JOIN vac.v_nationalcalendarvac nc ON (((nc.nationalcalendarvac_scheme_id)::text = replace((i.nationalcalendarvac_scheme_id)::text, '_'::text, ''::text))))
     LEFT JOIN LATERAL ( SELECT a.vacjournalaccount_datevac
           FROM vac.inoculation i_1,
            vac.vac_journalaccount a
          WHERE (((i_1.nationalcalendarvac_scheme_id)::text = nc.scheme_id_before) AND (a.vacjournalaccount_id = i_1.vacjournalaccount_id) AND (a.vacjournalaccount_statustype_id = 1) AND (a.person_id = ac.person_id))) i2 ON (true));

CREATE VIEW vac.v_journalaccountall AS
	SELECT ac.vacjournalaccount_id,
    ac.vacjournalaccount_datepurpose,
    ac.vacjournalaccount_datevac,
    COALESCE(pers.uch, '1'::text) AS vacjournalaccount_uch,
    pers.lpuregion_id,
    pers.person_id,
    pers.server_id,
    pers.personevn_id,
    pers.surname,
    pers.firname,
    pers.secname,
    (((((pers.surname)::text || ' '::text) || COALESCE(("substring"((pers.firname)::text, 1, 1) || '.'::text), '__'::text)) || ' '::text) || COALESCE(("substring"((pers.secname)::text, 1, 1) || '.'::text), '__'::text)) AS vacjournalaccount_fio,
        CASE
            WHEN (ac.vacjournalaccount_statustype_id = 2) THEN 'Привит по возрасту'::character varying
            ELSE v.vaccine_name
        END AS vaccine_name,
    v.vaccine_id,
    ac.vacjournalaccount_seria,
    ac.vacjournalaccount_period,
    vac.getvactype2inoculation(ac.vacjournalaccount_id, COALESCE(ac.vacjournalaccount_vacother, 0)) AS vacjournalaccount_infection,
    vac.getvactypeid2keylist(ac.vacjournalaccount_id) AS vacjournalaccount_keylist,
    ac.vacjournalaccount_dose,
    (((way.vaccineway_name)::text || ': '::text) || pl.vaccineplace_name) AS vacjournalaccount_wayplace,
    pers.sex AS vac_person_sex,
    pers.birthday AS vac_person_birthday,
    ac.vacjournalaccount_age,
    pers.group_risk AS vac_person_group_risk,
    ac.vacjournalaccount_statustype_id,
    ac.vacjournalaccount_lpu_id AS lpu_id,
    lpu.lpu_name,
    ac.vacjournalaccount_datesave,
    ac.vacjournalaccount_vacdatesave,
    ac.vacjournalaccount_purpose_medpersonal_id,
    ac.vacjournalaccount_vac_medpersonal_id,
    ac.vacjournalaccount_reactlocadescription,
    ac.vacjournalaccount_reactgeneraldescription,
    ac.vaccineway_id,
    ac.vaccineplace_id,
    ac.medservice_id,
    pers.org_id,
    pers.organized,
    pers.person_deaddt,
        CASE
            WHEN (pers.person_deaddt IS NULL) THEN 0
            ELSE 1
        END AS person_dead,
    pers.lpu_id AS lpu_id_attach,
    COALESCE(ac.vacjournalaccount_vacother, 0) AS vacjournalaccount_vacother
   FROM vac.v_vac_person pers,
    ((((vac.vac_journalaccount ac
     LEFT JOIN vac.s_vaccineway way ON ((way.vaccineway_id = ac.vaccineway_id)))
     LEFT JOIN vac.v_vaccineplace pl ON ((pl.vaccineplace_id = ac.vaccineplace_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((lpu.lpu_id = ac.vacjournalaccount_lpu_id)))
     LEFT JOIN vac.s_vaccine v ON ((v.vaccine_id = ac.vaccine_id)))
  WHERE ((ac.vacjournalaccount_statustype_id = 1) AND (pers.person_id = ac.person_id));

CREATE VIEW vac.v_fl_workplace AS
	SELECT fl_direction.fl_direction_id,
    fl_direction.person_id,
    fl_direction.fl_direction_datedir,
    v_vac_person.surname,
    v_vac_person.firname,
    v_vac_person.secname,
    v_vac_person.birthday,
    v_vac_person.address,
    fl_direction.lpu_id,
    fl_direction.fl_direction_servise AS med_serv,
    fl_fluor.fl_fluor_id AS fluor_id
   FROM ((vac.fl_direction
     JOIN vac.v_vac_person ON ((fl_direction.person_id = v_vac_person.person_id)))
     LEFT JOIN vac.fl_fluor ON ((fl_direction.fl_direction_id = fl_fluor.fl_direction_id)));

CREATE VIEW vac.v_fl_plan AS
	SELECT t.person_id,
    t.grouprisk,
    t.plan_period,
    (t.date_passing + (((t.plan_period)::text || ' month'::text))::interval) AS date_plan,
    pers.surname,
    pers.firname,
    pers.secname,
    pers.birthday,
    pers.sex_id,
    pers.sex,
    t.date_passing,
    pers.lpu_id,
    pers.lpu_name AS lpu
   FROM (( SELECT fl.person_id,
            fl.date_passing,
            COALESCE(per.grouprisk, 1) AS grouprisk,
                CASE
                    WHEN (per.grouprisk IS NULL) THEN 12
                    ELSE per.plan_period
                END AS plan_period
           FROM (( SELECT fl_1.person_id,
                    max(fl_1.fl_fluor_date_passing) AS date_passing
                   FROM vac.fl_fluor fl_1
                  GROUP BY fl_1.person_id) fl
             LEFT JOIN vac.v_fl_planperiod per ON ((per.person_id = fl.person_id)))) t
     JOIN vac.v_vac_person pers ON ((t.person_id = pers.person_id)));

CREATE VIEW dbo.v_job_er AS
	SELECT j.job_id,
    COALESCE(j.job_nfdata, o.org_name) AS job_name,
    j.post_id
   FROM (dbo.v_job j
     LEFT JOIN dbo.v_org o ON ((j.org_id = o.org_id)));

CREATE VIEW dbo.v_medstafffactcache AS
	SELECT medstafffactcache.server_id,
    medstafffactcache.medstafffact_id,
    medstafffactcache.medpersonal_id,
    medstafffactcache.person_id,
    medstafffactcache.staff_id,
    medstafffactcache.lpu_id,
    medstafffactcache.lpuunit_id,
    medstafffactcache.lpusection_id,
    medstafffactcache.medpersonal_code,
    medstafffactcache.medpersonal_tabcode,
    medstafffactcache.person_surname,
    medstafffactcache.person_firname,
    medstafffactcache.person_secname,
    medstafffactcache.person_fio,
    medstafffactcache.person_fin,
    medstafffactcache.person_birthday,
    medstafffactcache.medstafffact_stavka,
    medstafffactcache.medstafffact_isoms,
    medstafffactcache.medstafffact_isdlo,
    medstafffactcache.medspecoms_id,
    medstafffactcache.post_id,
    medstafffactcache.medicalcarekind_id,
    medstafffactcache.postkind_id,
    medstafffactcache.rectype_id,
    medstafffactcache.medstafffact_priemtime,
    medstafffactcache.medstafffact_isdirrec,
    medstafffactcache.medstafffact_isqueueonfree,
    medstafffactcache.medstafffact_descr,
    medstafffactcache.medstafffact_contacts,
    medstafffactcache.pmuser_insid,
    medstafffactcache.pmuser_updid,
    medstafffactcache.medstafffact_insdt,
    medstafffactcache.medstafffact_upddt,
    medstafffactcache.workdata_begdate,
    medstafffactcache.workdata_enddate,
    medstafffactcache.workdata_dlobegdate,
    medstafffactcache.workdata_dloenddate,
    medstafffactcache.postoccupationtype_id,
    medstafffactcache.population,
    medstafffactcache.arriveordernumber,
    medstafffactcache.comments,
    medstafffactcache.leaverecordtype_id,
    medstafffactcache.lpubuilding_id,
    medstafffactcache.medstafffactcache_isdisableindoc,
    medstafffactcache.medstafffactcache_isnotreception,
    medstafffactcache.lpusectionprofile_id,
    medstafffactcache.medstafffact_roomnum,
    medstafffactcache.medstafffactcache_ishomevisit,
    medstafffactcache.medstafffactouter_id,
    medstafffactcache.medstafffactcache_phonenum,
    medstafffactcache.dismissalreasontype_id,
    medstafffactcache.medstafffactcache_issenttofrmr,
    medstafffactcache.medstafffactcache_isnotshown,
    medstafffactcache.frmrcardkey_positiontypeid,
    medstafffactcache.frmrcardkey_postid,
    medstafffactcache.frmrcardkey_begindate,
    medstafffactcache.frmrcardkey_organizationid,
    medstafffactcache.frmrcardkey_nrpmudepartid,
    medstafffactcache.frmrcardkey_nrpmudeparthospitalsubdivisionid
   FROM dbo.medstafffactcache
  WHERE (1 = 1);

CREATE VIEW dbo.v_person_er AS
	SELECT personstate.person_id,
    person.server_id AS server_pid,
    personstate.server_id,
    personstate.personevn_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personbirthday_birthday AS person_birthday,
    (date_part('year'::text, age(now(), (personstate.personbirthday_birthday)::timestamp with time zone)))::integer AS person_age,
    personstate.sex_id,
    personstate.polis_id,
        CASE
            WHEN (polis.polistype_id <> 4) THEN personstate.polis_ser
            ELSE NULL::character varying
        END AS polis_ser,
        CASE
            WHEN (polis.polistype_id <> 4) THEN personstate.polis_num
            ELSE personstate.personpolisednum_ednum
        END AS polis_num,
    personstate.uaddress_id,
    personstate.paddress_id,
    personstate.personjob_id,
    personstate.job_id,
    personstate.personpolisednum_ednum AS person_ednum,
    personstate.personphone_phone AS person_phone,
    personstate.personsnils_snils AS person_snils,
    personstate.personinn_inn AS person_inn,
    personstate.lpu_id,
    lpu.lpu_nick,
    personstate.pmuser_insid,
    personstate.pmuser_updid,
    personstate.personstate_insdt,
    personstate.personstate_upddt,
    priv.privilegetype_id,
    polis.orgsmo_id,
    polis.omssprterr_id,
    polis.polis_begdate,
    polis.polis_enddate,
    personstate.socstatus_id,
    personstate.document_id,
    personinfo.personinfo_internetphone
   FROM (((((dbo.personstate
     JOIN dbo.person ON (((personstate.person_id = person.person_id) AND (COALESCE(person.person_deleted, (1)::bigint) = 1))))
     LEFT JOIN LATERAL ( SELECT personinfo_1.server_id,
            personinfo_1.personinfo_id,
            personinfo_1.person_id,
            personinfo_1.upersonsprterrdop_id,
            personinfo_1.ppersonsprterrdop_id,
            personinfo_1.pmuser_insid,
            personinfo_1.pmuser_updid,
            personinfo_1.personinfo_insdt,
            personinfo_1.personinfo_upddt,
            personinfo_1.personinfo_internetphone,
            personinfo_1.nationality_id,
            personinfo_1.ethnos_id,
            personinfo_1.bpersonsprterrdop_id,
            personinfo_1.personinfo_issetdeath,
            personinfo_1.personinfo_isparsdeath,
            personinfo_1.person_bdzcode,
            personinfo_1.personinfo_email
           FROM dbo.personinfo personinfo_1
          WHERE ((personstate.person_id = personinfo_1.person_id) AND (personinfo_1.personinfo_internetphone IS NOT NULL))
          ORDER BY personinfo_1.personinfo_upddt DESC
         LIMIT 1) personinfo ON (true))
     LEFT JOIN dbo.polis ON ((personstate.polis_id = polis.polis_id)))
     LEFT JOIN dbo.v_lpu lpu ON ((personstate.lpu_id = lpu.lpu_id)))
     LEFT JOIN LATERAL ( SELECT personprivilege.privilegetype_id
           FROM dbo.personprivilege
          WHERE ((personprivilege.person_id = personstate.person_id) AND ((personprivilege.personprivilege_enddate IS NULL) OR (personprivilege.personprivilege_enddate > dbo.getdate())) AND (personprivilege.privilegetype_id = ANY (ARRAY[(11)::bigint, (20)::bigint, (40)::bigint, (50)::bigint, (140)::bigint, (150)::bigint])))
          ORDER BY personprivilege.privilegetype_id
         LIMIT 1) priv ON (true));

CREATE VIEW dbo.v_person_er2 AS
	SELECT personstate.person_id,
    person.server_id AS server_pid,
    personstate.server_id,
    personstate.personevn_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personbirthday_birthday AS person_birthday,
    (date_part('year'::text, age(now(), (personstate.personbirthday_birthday)::timestamp with time zone)))::integer AS person_age,
    personstate.sex_id,
    personstate.polis_id,
        CASE
            WHEN (polis.polistype_id <> 4) THEN personstate.polis_ser
            ELSE NULL::character varying
        END AS polis_ser,
        CASE
            WHEN (polis.polistype_id <> 4) THEN personstate.polis_num
            ELSE personstate.personpolisednum_ednum
        END AS polis_num,
    personstate.uaddress_id,
    personstate.paddress_id,
    personstate.personjob_id,
    personstate.job_id,
    personstate.personpolisednum_ednum AS person_ednum,
    personstate.personphone_phone AS person_phone,
    personstate.personsnils_snils AS person_snils,
    personstate.personinn_inn AS person_inn,
    personstate.lpu_id,
    lpu.lpu_nick,
    personstate.pmuser_insid,
    personstate.pmuser_updid,
    personstate.personstate_insdt,
    personstate.personstate_upddt,
    priv.privilegetype_id,
    polis.orgsmo_id,
    polis.omssprterr_id,
    polis.polis_begdate,
    polis.polis_enddate,
    personstate.socstatus_id,
    personstate.document_id,
    personinfo.personinfo_internetphone
   FROM (((((dbo.personstate
     JOIN dbo.person ON (((person.person_id = personstate.person_id) AND (person.person_deleted = 1))))
     LEFT JOIN LATERAL ( SELECT personinfo_1.server_id,
            personinfo_1.personinfo_id,
            personinfo_1.person_id,
            personinfo_1.upersonsprterrdop_id,
            personinfo_1.ppersonsprterrdop_id,
            personinfo_1.pmuser_insid,
            personinfo_1.pmuser_updid,
            personinfo_1.personinfo_insdt,
            personinfo_1.personinfo_upddt,
            personinfo_1.personinfo_internetphone,
            personinfo_1.nationality_id,
            personinfo_1.ethnos_id,
            personinfo_1.bpersonsprterrdop_id,
            personinfo_1.personinfo_issetdeath,
            personinfo_1.personinfo_isparsdeath,
            personinfo_1.person_bdzcode,
            personinfo_1.personinfo_email
           FROM dbo.personinfo personinfo_1
          WHERE ((personinfo_1.person_id = personstate.person_id) AND (personinfo_1.personinfo_internetphone IS NOT NULL))
          ORDER BY personinfo_1.personinfo_upddt DESC
         LIMIT 1) personinfo ON (true))
     LEFT JOIN LATERAL ( SELECT polis_1.server_id,
            polis_1.polis_id,
            polis_1.polistype_id,
            polis_1.orgsmo_id,
            polis_1.omssprterr_id,
            polis_1.polis_ser,
            polis_1.polis_num,
            polis_1.polis_begdate,
            polis_1.polis_enddate,
            polis_1.polisclosecause_id,
            polis_1.pmuser_insid,
            polis_1.pmuser_updid,
            polis_1.polis_insdt,
            polis_1.polis_upddt,
            polis_1.bdz_id,
            polis_1.polis_plandate,
            polis_1.polis_changedate,
            polis_1.dogstrah_num,
            polis_1.polis_guid,
            polis_1.polisformtype_id,
            polis_1.polis_numint
           FROM dbo.polis polis_1
          WHERE (polis_1.polis_id = personstate.polis_id)
         LIMIT 1) polis ON (true))
     LEFT JOIN LATERAL ( SELECT lpu_1.server_id,
            lpu_1.lpu_id,
            lpu_1.lpu_sysnick,
            lpu_1.lpu_isenable,
            lpu_1.org_id,
            lpu_1.org_code,
            lpu_1.lpu_name,
            lpu_1.lpu_nick,
            lpu_1.org_name,
            lpu_1.org_nick,
            lpu_1.lpu_email,
            lpu_1.org_www,
            lpu_1.lpu_isemailfixed,
            lpu_1.lpu_phone,
            lpu_1.uaddress_id,
            lpu_1.uaddress_address,
            lpu_1.paddress_id,
            lpu_1.paddress_address,
            lpu_1.lputype_id,
            lpu_1.lputype_code,
            lpu_1.lputype_name,
            lpu_1.lpu_regnomc,
            lpu_1.lpu_regnomn,
            lpu_1.lpu_regnomc2,
            lpu_1.lpu_regnomn2,
            lpu_1.lpu_ouz,
            lpu_1.lpu_isoblast,
            lpu_1.lpu_isoms,
            lpu_1.lpu_dognum,
            lpu_1.lpu_dogdate,
            lpu_1.lpu_glvrach,
            lpu_1.lpu_glbuh,
            lpu_1.lpu_otv,
            lpu_1.lpu_isindir,
            lpu_1.lpu_ogrn,
            lpu_1.lpu_amountpeople,
            lpu_1.lpu_omsbegdate,
            lpu_1.lpu_omsenddate,
            lpu_1.lpu_okdp,
            lpu_1.lpu_pensregnum,
            lpu_1.lpu_regdate,
            lpu_1.lpu_regnum,
            lpu_1.lpu_districtrate,
            lpu_1.lpu_fondequip,
            lpu_1.lpu_fondosn,
            lpu_1.lpu_begdate,
            lpu_1.lpu_enddate,
            lpu_1.lpulevel_id,
            lpu_1.lpusubjectionlevel_id,
            lpu_1.lpu_vizitfact,
            lpu_1.lpu_koikifact,
            lpu_1.lpu_farpoint,
            lpu_1.lpu_naselgor,
            lpu_1.lpu_naselsel,
            lpu_1.lpu_naselchild,
            lpu_1.lpu_naselvzr,
            lpu_1.lpu_naselrab,
            lpu_1.lpu_erinfo,
            lpu_1.lpu_dlobegdate,
            lpu_1.lpu_dloenddate,
            lpu_1.lpu_ambulancecount,
            lpu_1.lpu_worktime,
            lpu_1.pmuser_insid,
            lpu_1.pmuser_updid,
            lpu_1.lpu_insdt,
            lpu_1.lpu_upddt,
            lpu_1.lpu_ouzold,
            lpu_1.lpu_f003mcod,
            lpu_1.lpu_isemergencydir,
            lpu_1.lpu_isdms,
            lpu_1.mesagelputype_id,
            lpu_1.lpu_stickaddress,
            lpu_1.lpu_pid,
            lpu_1.lpu_nid,
            lpu_1.org_lid,
            lpu_1.region_id,
            lpu_1.lpu_isallowinternetmoderation,
            lpu_1.lpu_issecret,
            lpu_1.lpu_docreg,
            lpu_1.lpu_intercode,
            lpu_1.lpupmutype_id,
            lpu_1.lpu_okato,
            lpu_1.lpu_kbk,
            lpu_1.org_sticknick,
            lpu_1.org_guid,
            lpu_1.oktmo_id,
            lpu_1.touztype_id,
            lpu_1.org_tid,
            lpu_1.lpupmuclass_id,
            lpu_1.lpulevel_cid,
            lpu_1.lpu_fssregnum,
            lpu_1.org_regname,
            lpu_1.lpu_kpn,
            lpu_1.lpu_islab,
            lpu_1.lpu_istest,
            lpu_1.lpu_hospid,
            lpu_1.lpu_founder,
            lpu_1.lpuownership_id,
            lpu_1.moareafeature_id,
            lpu_1.lpu_isfrmo,
            lpu_1.lpubuildingpass_mid,
            lpu_1.lpu_ismse
           FROM dbo.v_lpu lpu_1
          WHERE (lpu_1.lpu_id = personstate.lpu_id)
         LIMIT 1) lpu ON (true))
     LEFT JOIN LATERAL ( SELECT personprivilege.privilegetype_id
           FROM dbo.personprivilege
          WHERE ((personprivilege.person_id = personstate.person_id) AND ((personprivilege.personprivilege_enddate IS NULL) OR (personprivilege.personprivilege_enddate > dbo.getdate())) AND (personprivilege.privilegetype_id = ANY (ARRAY[(11)::bigint, (20)::bigint, (40)::bigint, (50)::bigint, (140)::bigint, (150)::bigint])))
          ORDER BY personprivilege.privilegetype_id
         LIMIT 1) priv ON (true))
  WHERE (person.person_deleted = 1);

CREATE VIEW dbo.v_personcard AS
	SELECT personcardstate.server_id,
    personstate.server_id AS personserver_id,
    personcardstate.personcardstate_id,
    personcardstate.personcard_id,
    personcardstate.person_id,
    personcardstate.lpu_id,
    personcardstate.lpuattachtype_id,
    lpuattachtype.lpuattachtype_name,
    COALESCE(lpuregiontype.lpuregiontype_id, lpuregiontypecard.lpuregiontype_id) AS lpuregiontype_id,
    COALESCE(lpuregiontype.lpuregiontype_name, lpuregiontypecard.lpuregiontype_name) AS lpuregiontype_name,
    personcardstate.lpuregion_id,
    lpuregion.lpuregion_name,
    personcardstate.personcardstate_code AS personcard_code,
    personcardstate.personcardstate_begdate AS personcard_begdate,
    personcardstate.personcardstate_enddate AS personcard_enddate,
    personcardstate.cardclosecause_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personbirthday_birthday AS person_birthday,
    personcardstate.personcard_isattachcondit,
    personcardstate.pmuser_insid,
    personcardstate.pmuser_updid,
    personcardstate.personcardstate_insdt AS personcard_insdt,
    personcardstate.personcardstate_upddt AS personcard_upddt,
    personcard.personcard_begdate AS personcard_lpubegdate,
    personcard.personcard_dmspolisnum,
    personcard.personcard_dmsbegdate,
    personcard.personcard_dmsenddate,
    personcard.orgsmo_id,
    personcardstate.personcardattach_id,
    personcardstate.lpuregion_fapid,
    lpuregionfap.lpuregion_name AS lpuregion_fapname,
    personcardstate.medstafffact_id
   FROM (((((((dbo.personcardstate
     JOIN LATERAL ( SELECT personstate_1.person_id,
            personstate_1.server_id,
            personstate_1.personevn_id,
            personstate_1.personsurname_id,
            personstate_1.personsurname_surname,
            personstate_1.personfirname_id,
            personstate_1.personfirname_firname,
            personstate_1.personsecname_id,
            personstate_1.personsecname_secname,
            personstate_1.personbirthday_id,
            personstate_1.personbirthday_birthday,
            personstate_1.personsex_id,
            personstate_1.sex_id,
            personstate_1.personsnils_id,
            personstate_1.personsnils_snils,
            personstate_1.personsocstatus_id,
            personstate_1.socstatus_id,
            personstate_1.personpolis_id,
            personstate_1.polis_id,
            personstate_1.polis_ser,
            personstate_1.polis_num,
            personstate_1.persondocument_id,
            personstate_1.document_id,
            personstate_1.document_ser,
            personstate_1.document_num,
            personstate_1.personuaddress_id,
            personstate_1.uaddress_id,
            personstate_1.personpaddress_id,
            personstate_1.paddress_id,
            personstate_1.personjob_id,
            personstate_1.job_id,
            personstate_1.personpolisednum_id,
            personstate_1.personpolisednum_ednum,
            personstate_1.personphone_id,
            personstate_1.personphone_phone,
            personstate_1.personinn_inn,
            personstate_1.pmuser_insid,
            personstate_1.pmuser_updid,
            personstate_1.personstate_insdt,
            personstate_1.personstate_upddt,
            personstate_1.personinn_id,
            personstate_1.personsoccardnum_id,
            personstate_1.personsoccardnum_soccardnum,
            personstate_1.lpu_id,
            personstate_1.personfamilystatus_id,
            personstate_1.familystatus_id,
            personstate_1.personfamilystatus_ismarried,
            personstate_1.personsurname_surnamer,
            personstate_1.personfirname_firnamer,
            personstate_1.personsecname_secnamer,
            personstate_1.polistype_id,
            personstate_1.personphone_comment,
            personstate_1.nationalitystatus_id,
            personstate_1.klcountry_id,
            personstate_1.nationalitystatus_istwonation,
            personstate_1.personnationalitystatus_id,
            personstate_1.legalstatusvzn_id,
            personstate_1.personstate_issnils
           FROM dbo.personstate personstate_1
          WHERE (personstate_1.person_id = personcardstate.person_id)
         LIMIT 1) personstate ON (true))
     LEFT JOIN dbo.lpuregiontype lpuregiontypecard ON ((lpuregiontypecard.lpuregiontype_id = personcardstate.lpuregiontype_id)))
     LEFT JOIN dbo.lpuregion ON ((personcardstate.lpuregion_id = lpuregion.lpuregion_id)))
     LEFT JOIN dbo.lpuregion lpuregionfap ON ((personcardstate.lpuregion_fapid = lpuregionfap.lpuregion_id)))
     LEFT JOIN dbo.lpuregiontype ON ((lpuregion.lpuregiontype_id = lpuregiontype.lpuregiontype_id)))
     LEFT JOIN dbo.lpuattachtype ON ((personcardstate.lpuattachtype_id = lpuattachtype.lpuattachtype_id)))
     LEFT JOIN LATERAL ( SELECT personcard_1.personcard_begdate,
            personcard_1.personcard_dmspolisnum,
            personcard_1.personcard_dmsbegdate,
            personcard_1.personcard_dmsenddate,
            personcard_1.orgsmo_id,
            personcard_1.personcardattach_id
           FROM dbo.personcard personcard_1
          WHERE ((personcard_1.person_id = personcardstate.person_id) AND (personcard_1.lpuattachtype_id = personcardstate.lpuattachtype_id) AND (personcard_1.lpu_id = personcardstate.lpu_id) AND ((personcard_1.cardclosecause_id <> 1) OR (personcard_1.cardclosecause_id IS NULL)))
          ORDER BY personcard_1.personcard_begdate
         LIMIT 1) personcard ON (true));

CREATE VIEW dbo.v_personcard_all AS
	SELECT personcard.server_id,
    personstate.server_id AS personserver_id,
    personcard.personcard_id,
    personcard.person_id,
    personcard.lpu_id,
    personcard.lpuattachtype_id,
    lpuattachtype.lpuattachtype_name,
    personcard.lpuregion_id,
    lpuregion.lpuregion_name,
    COALESCE(lpuregiontype.lpuregiontype_id, lpuregiontypecard.lpuregiontype_id) AS lpuregiontype_id,
    COALESCE(lpuregiontype.lpuregiontype_name, lpuregiontypecard.lpuregiontype_name) AS lpuregiontype_name,
    personcard.personcard_code,
    personcard.personcard_begdate,
    personcard.pmuser_insid AS pmuserbeg_insid,
    personcard.personcard_insdt AS personcardbeg_insdt,
    personcardend.personcard_enddate,
    personcardend.pmuser_insid AS pmuserend_insid,
    personcardend.personcard_insdt AS personcardend_insdt,
    personcardend.cardclosecause_id,
    personcard.personcardattach_id,
    personcard.personcard_isattachcondit,
    personcard.personcard_dmspolisnum,
    personcard.personcard_dmsbegdate,
    personcard.personcard_dmsenddate,
    personcard.orgsmo_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personbirthday_birthday AS person_birthday,
    personcard.pmuser_updid AS pmuserbeg_updid,
    personcard.personcard_upddt AS personcardbeg_upddt,
    personcardend.pmuser_updid AS pmuserend_updid,
    personcardend.personcard_upddt AS personcardend_upddt,
    personcard.lpuregion_fapid,
    lpuregionfap.lpuregion_name AS lpuregion_fapname,
    personcard.medstafffact_id,
    personcard.personcard_isattachauto
   FROM (((((((dbo.personcard
     JOIN LATERAL ( SELECT personstate_1.person_id,
            personstate_1.server_id,
            personstate_1.personevn_id,
            personstate_1.personsurname_id,
            personstate_1.personsurname_surname,
            personstate_1.personfirname_id,
            personstate_1.personfirname_firname,
            personstate_1.personsecname_id,
            personstate_1.personsecname_secname,
            personstate_1.personbirthday_id,
            personstate_1.personbirthday_birthday,
            personstate_1.personsex_id,
            personstate_1.sex_id,
            personstate_1.personsnils_id,
            personstate_1.personsnils_snils,
            personstate_1.personsocstatus_id,
            personstate_1.socstatus_id,
            personstate_1.personpolis_id,
            personstate_1.polis_id,
            personstate_1.polis_ser,
            personstate_1.polis_num,
            personstate_1.persondocument_id,
            personstate_1.document_id,
            personstate_1.document_ser,
            personstate_1.document_num,
            personstate_1.personuaddress_id,
            personstate_1.uaddress_id,
            personstate_1.personpaddress_id,
            personstate_1.paddress_id,
            personstate_1.personjob_id,
            personstate_1.job_id,
            personstate_1.personpolisednum_id,
            personstate_1.personpolisednum_ednum,
            personstate_1.personphone_id,
            personstate_1.personphone_phone,
            personstate_1.personinn_inn,
            personstate_1.pmuser_insid,
            personstate_1.pmuser_updid,
            personstate_1.personstate_insdt,
            personstate_1.personstate_upddt,
            personstate_1.personinn_id,
            personstate_1.personsoccardnum_id,
            personstate_1.personsoccardnum_soccardnum,
            personstate_1.lpu_id,
            personstate_1.personfamilystatus_id,
            personstate_1.familystatus_id,
            personstate_1.personfamilystatus_ismarried,
            personstate_1.personsurname_surnamer,
            personstate_1.personfirname_firnamer,
            personstate_1.personsecname_secnamer,
            personstate_1.polistype_id,
            personstate_1.personphone_comment,
            personstate_1.nationalitystatus_id,
            personstate_1.klcountry_id,
            personstate_1.nationalitystatus_istwonation,
            personstate_1.personnationalitystatus_id,
            personstate_1.legalstatusvzn_id,
            personstate_1.personstate_issnils
           FROM dbo.personstate personstate_1
          WHERE (personcard.person_id = personstate_1.person_id)
         LIMIT 1) personstate ON (true))
     LEFT JOIN dbo.personcard personcardend ON (((personcard.person_id = personcardend.person_id) AND (personcard.lpu_id = personcardend.lpu_id) AND ((COALESCE(personcard.personcard_code, ''::character varying))::text = (COALESCE(personcardend.personcard_code, ''::character varying))::text) AND (personcard.lpuattachtype_id = personcardend.lpuattachtype_id) AND ((personcard.personcard_begdate)::date = (personcardend.personcard_begdate)::date) AND ((personcard.personcard_begdate)::date <= (personcardend.personcard_enddate)::date) AND (COALESCE(personcardend.orgsmo_id, (0)::bigint) = COALESCE(personcard.orgsmo_id, (0)::bigint)) AND (personcardend.personcard_enddate IS NOT NULL) AND (COALESCE(personcard.lpuregion_id, (0)::bigint) = COALESCE(personcardend.lpuregion_id, (0)::bigint)) AND (COALESCE(personcard.personcardattach_id, (0)::bigint) = COALESCE(personcardend.personcardattach_id, (0)::bigint)))))
     LEFT JOIN dbo.lpuregion ON ((personcard.lpuregion_id = lpuregion.lpuregion_id)))
     LEFT JOIN dbo.lpuregion lpuregionfap ON ((personcard.lpuregion_fapid = lpuregionfap.lpuregion_id)))
     LEFT JOIN dbo.lpuregiontype ON ((lpuregion.lpuregiontype_id = lpuregiontype.lpuregiontype_id)))
     LEFT JOIN dbo.lpuattachtype ON ((personcard.lpuattachtype_id = lpuattachtype.lpuattachtype_id)))
     LEFT JOIN dbo.lpuregiontype lpuregiontypecard ON ((personcard.lpuregiontype_id = lpuregiontypecard.lpuregiontype_id)))
  WHERE (personcard.personcard_enddate IS NULL);

CREATE VIEW dbo.v_personcard_rpt AS
	SELECT personcard.server_id,
    personcard.personcard_id,
    personcard.person_id,
    personcard.lpu_id,
    personcard.lpuregion_id,
    personcard.lpuattachtype_id,
    personcard.personcard_code,
    personcard.personcard_begdate,
    personcard.personcard_enddate,
    personcard.cardclosecause_id,
    personcard.personcard_isattachcondit,
    personcard.personcard_isattachauto,
    personcard.personcard_attachautodt,
    personcard.pmuser_insid,
    personcard.pmuser_updid,
    personcard.personcard_insdt,
    personcard.personcard_upddt,
    personcard.personcard_dmspolisnum,
    personcard.personcard_dmsbegdate,
    personcard.personcard_dmsenddate,
    personcard.orgsmo_id,
    personcard.personcardattach_id,
    personcard.lpuregion_fapid,
    personcard.lpuregiontype_id,
    personcard.medstafffact_id
   FROM (dbo.personcard
     LEFT JOIN dbo.personcardstate ON ((personcard.personcard_id = personcardstate.personcard_id)))
  WHERE (((personcard.personcard_enddate IS NOT NULL) OR (personcardstate.personcard_id IS NOT NULL)) AND (COALESCE(personcard.personcard_deleted, (1)::bigint) = 1));

CREATE VIEW dbo.v_persondeputy AS
	SELECT persondeputy.server_id,
    persondeputy.persondeputy_id,
    persondeputy.person_id,
    persondeputy.person_pid,
    persondeputy.deputykind_id,
    persondeputy.pmuser_insid,
    persondeputy.pmuser_updid,
    persondeputy.persondeputy_insdt,
    persondeputy.persondeputy_upddt,
    persondeputy.persondeputy_begdt,
    persondeputy.documentdeputy_id
   FROM dbo.persondeputy
  WHERE (1 = 1);

COMMENT ON VIEW dbo.v_persondeputy IS 'Autogen';

-- DEPCY: This VIEW is a dependency of VIEW: dbo.v_personstate_all

CREATE VIEW dbo.v_persondisp AS
	SELECT persondisp.server_id,
    persondisp.persondisp_id,
    persondisp.person_id,
    persondisp.lpu_id,
    persondisp.lpusection_id,
    persondisp.medpersonal_id,
    persondisp.lpuregion_id,
    persondisp.diag_id,
    persondisp.diag_pid,
    persondisp.diag_nid,
    persondisp.persondisp_begdate,
    persondisp.persondisp_enddate,
    persondisp.persondisp_nextdate,
    persondisp.dispouttype_id,
    persondisp.persondisp_isdop,
    persondisp.sickness_id,
    persondisp.personprivilege_id,
    persondisp.pmuser_insid,
    persondisp.pmuser_updid,
    persondisp.persondisp_insdt,
    persondisp.persondisp_upddt,
    persondisp.persondisp_diagdate,
    persondisp.diagdetecttype_id,
    persondisp.persondisp_isautoclose,
    persondisp.persondisp_istfoms,
    persondisp.deseasedisptype_id,
    persondisp.persondisp_numcard,
    persondisp.persondisp_issignedep,
    persondisp.persondisp_signdate,
    persondisp.pmuser_signid,
    persondisp.medstafffact_id
   FROM dbo.persondisp
  WHERE ((1 = 1) AND ((persondisp.persondisp_deleted = 1) OR (persondisp.persondisp_deleted IS NULL)));

CREATE VIEW dbo.v_personstate_all AS
	SELECT personstate.person_id,
    person.server_id AS server_pid,
    person.person_isinerz,
    personstate.server_id,
    personstate.personevn_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personbirthday_birthday AS person_birthday,
    (date_part('year'::text, age(now(), (personstate.personbirthday_birthday)::timestamp with time zone)))::integer AS person_age,
    personstate.sex_id,
    personstate.personsnils_snils AS person_snils,
    personstate.socstatus_id,
    personstate.polis_id,
    personstate.polis_ser,
    personstate.polis_num,
    personstate.polistype_id,
    personstate.document_id,
    personstate.document_ser,
    personstate.document_num,
    personstate.uaddress_id,
    personstate.paddress_id,
    personstate.job_id,
    personstate.personpolisednum_ednum AS person_ednum,
    personstate.personphone_phone AS person_phone,
    personstate.personsoccardnum_soccardnum AS person_soccardnum,
    personstate.lpu_id,
    personstate.familystatus_id,
    personstate.personfamilystatus_ismarried,
    lpu.lpu_nick,
        CASE
            WHEN (personrefuse.personrefuse_isrefuse = 2) THEN 1
            ELSE 0
        END AS person_isrefuse,
    personrefuse.personrefuse_isrefuse AS person_isrefuse2,
    personrefuse.personrefuse_year,
        CASE
            WHEN (EXISTS ( SELECT personprivilege.person_id
               FROM (dbo.personprivilege
                 JOIN dbo.privilegetype ON ((personprivilege.privilegetype_id = privilegetype.privilegetype_id)))
              WHERE ((personprivilege.person_id = personstate.person_id) AND (personprivilege.personprivilege_begdate <= now()) AND ((personprivilege.personprivilege_enddate IS NULL) OR (personprivilege.personprivilege_enddate >= (now())::date)) AND (privilegetype.receptfinance_id = 1))
             LIMIT 1)) THEN 1
            ELSE 0
        END AS person_isfedlgot,
        CASE
            WHEN (EXISTS ( SELECT personprivilege.person_id
               FROM (dbo.personprivilege
                 JOIN dbo.privilegetype ON ((personprivilege.privilegetype_id = privilegetype.privilegetype_id)))
              WHERE ((personprivilege.person_id = personstate.person_id) AND (personprivilege.personprivilege_begdate <= now()) AND ((personprivilege.personprivilege_enddate IS NULL) OR (personprivilege.personprivilege_enddate >= (now())::date)) AND (privilegetype.receptfinance_id = 2))
             LIMIT 1)) THEN 1
            ELSE 0
        END AS person_isreglgot,
        CASE
            WHEN (person_is7noz1.id IS NOT NULL) THEN 1
            WHEN (person_is7noz2.id IS NOT NULL) THEN 1
            ELSE 0
        END AS person_is7noz,
        CASE
            WHEN (person.server_id = 0) THEN 1
            ELSE 0
        END AS person_isbdz,
        CASE
            WHEN (person.person_deaddt IS NOT NULL) THEN 1
            ELSE 0
        END AS person_isdead,
    person.person_deaddt,
    person.person_closedt,
    person.personclosecause_id,
    personstate.pmuser_insid,
    personstate.pmuser_updid,
    personstate.personstate_insdt,
    personstate.personstate_upddt,
    personstate.personsurname_surnamer AS person_surnamer,
    personstate.personfirname_firnamer AS person_firnamer,
    personstate.personsecname_secnamer AS person_secnamer,
    personstate.nationalitystatus_id,
    personstate.klcountry_id,
    personstate.nationalitystatus_istwonation,
    personstate.legalstatusvzn_id,
    person.person_isunknown,
    personstate.personinfo_internetphone
   FROM (((((dbo.personstate
     JOIN dbo.person ON (((personstate.person_id = person.person_id) AND (person.person_deleted = 1))))
     LEFT JOIN LATERAL ( SELECT lpu_1.lpu_nick
           FROM dbo.v_lpu lpu_1
          WHERE (lpu_1.lpu_id = personstate.lpu_id)
         LIMIT 1) lpu ON (true))
     LEFT JOIN dbo.v_personrefuse personrefuse ON (((personrefuse.person_id = personstate.person_id) AND (personrefuse.personrefuse_isrefuse = 2) AND ((personrefuse.personrefuse_year)::double precision = date_part('year'::text, now())))))
     LEFT JOIN LATERAL ( SELECT v_persondisp.persondisp_id AS id
           FROM ((dbo.v_personregistertype personregistertype
             JOIN dbo.v_personregisterdiag ON ((v_personregisterdiag.personregistertype_id = personregistertype.personregistertype_id)))
             JOIN dbo.v_persondisp ON (((v_persondisp.diag_id = v_personregisterdiag.diag_id) AND (v_persondisp.person_id = personstate.person_id))))
          WHERE ((personregistertype.personregistertype_sysnick)::text = 'nolos'::text)
         LIMIT 1) person_is7noz1 ON (true))
     LEFT JOIN LATERAL ( SELECT v_personregister.personregister_id AS id
           FROM (dbo.v_personregistertype personregistertype
             JOIN dbo.v_personregister ON (((v_personregister.personregistertype_id = personregistertype.personregistertype_id) AND (v_personregister.person_id = personstate.person_id) AND (v_personregister.personregister_disdate IS NULL) AND (v_personregister.personregisteroutcause_id IS NULL))))
          WHERE ((personregistertype.personregistertype_sysnick)::text = 'nolos'::text)
         LIMIT 1) person_is7noz2 ON (true));

CREATE VIEW dbo.v_personfirname AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personfirname_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personfirname_insdate,
    (personevn.personevn_insdt)::time without time zone AS personfirname_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personfirname_timestamp,
    personevn.personevn_index AS personfirname_index,
    personevn.personevn_count AS personfirname_count,
    personevn.personevn_insdt AS personfirname_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personfirname_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personfirname_begdt,
    personevn.personevn_frmrlastdt AS personfirname_frmrlastdt,
    personfirname.personfirname_firname
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 2))))
     JOIN dbo.personfirname ON (((personfirname.personfirname_id = personevn.personevn_id) AND (personfirname.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personinn AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personinn_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personinn_insdate,
    (personevn.personevn_insdt)::time without time zone AS personinn_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personinn_timestamp,
    personevn.personevn_index AS personinn_index,
    personevn.personevn_count AS personinn_count,
    personevn.personevn_insdt AS personinn_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personinn_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personinn_begdt,
    personevn.personevn_frmrlastdt AS personinn_frmrlastdt,
    personinn.personinn_inn
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 20))))
     JOIN dbo.personinn ON (((personinn.personinn_id = personevn.personevn_id) AND (personinn.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personjob AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personjob_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personjob_insdate,
    (personevn.personevn_insdt)::time without time zone AS personjob_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personjob_timestamp,
    personevn.personevn_index AS personjob_index,
    personevn.personevn_count AS personjob_count,
    personevn.personevn_insdt AS personjob_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personjob_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personjob_begdt,
    personevn.personevn_frmrlastdt AS personjob_frmrlastdt,
    job.job_id,
    job.org_id,
    job.orgunion_id,
    job.post_id,
    job.personjob_begdate,
    job.personjob_enddate,
    job.job_nfdata
   FROM (((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 12))))
     JOIN dbo.personjob ON (((personjob.personjob_id = personevn.personevn_id) AND (personjob.server_id = personevn.server_id))))
     LEFT JOIN dbo.job ON ((personjob.job_id = job.job_id)));

CREATE VIEW dbo.v_personnationalitystatus AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personnationalitystatus_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personnationalitystatus_insdate,
    (personevn.personevn_insdt)::time without time zone AS personnationalitystatus_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personnationalitystatus_timestamp,
    personevn.personevn_index AS personnationalitystatus_index,
    personevn.personevn_count AS personnationalitystatus_count,
    personevn.personevn_insdt AS personnationalitystatus_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personnationalitystatus_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personnationalitystatus_begdt,
    personevn.personevn_frmrlastdt AS personnationalitystatus_frmrlastdt,
    nationalitystatus.nationalitystatus_id,
    nationalitystatus.klcountry_id,
    nationalitystatus.nationalitystatus_istwonation,
    nationalitystatus.legalstatusvzn_id
   FROM (((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 23))))
     JOIN dbo.personnationalitystatus ON (((personnationalitystatus.personnationalitystatus_id = personevn.personevn_id) AND (personnationalitystatus.server_id = personevn.server_id))))
     LEFT JOIN dbo.nationalitystatus ON ((personnationalitystatus.nationalitystatus_id = nationalitystatus.nationalitystatus_id)));

CREATE VIEW dbo.v_personpaddress AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personpaddress_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personpaddress_insdate,
    (personevn.personevn_insdt)::time without time zone AS personpaddress_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personpaddress_timestamp,
    personevn.personevn_index AS personpaddress_index,
    personevn.personevn_count AS personpaddress_count,
    personevn.personevn_insdt AS personpaddress_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personpaddress_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personpaddress_begdt,
    personevn.personevn_frmrlastdt AS personpaddress_frmrlastdt,
    address.address_id,
    address.klareatype_id,
    address.klcountry_id,
    address.klrgn_id,
    address.klsubrgn_id,
    address.klcity_id,
    address.kltown_id,
    address.klstreet_id,
    address.address_zip,
    address.address_house,
    address.address_corpus,
    address.address_flat,
    address.address_address,
    address.klareastat_id,
    address.address_begdate,
    address.address_nick,
    address.personsprterrdop_id,
    address.addressspecobject_id
   FROM (((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 11))))
     JOIN dbo.personpaddress ON (((personpaddress.personpaddress_id = personevn.personevn_id) AND (personpaddress.server_id = personevn.server_id))))
     LEFT JOIN dbo.address ON ((personpaddress.paddress_id = address.address_id)));

CREATE VIEW dbo.v_personphone AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personphone_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personphone_insdate,
    (personevn.personevn_insdt)::time without time zone AS personphone_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personphone_timestamp,
    personevn.personevn_index AS personphone_index,
    personevn.personevn_count AS personphone_count,
    personevn.personevn_insdt AS personphone_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personphone_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personphone_begdt,
    personevn.personevn_frmrlastdt AS personphone_frmrlastdt,
    personphone.personphone_phone,
    personphone.personphone_comment
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 18))))
     JOIN dbo.personphone ON (((personphone.personphone_id = personevn.personevn_id) AND (personphone.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personpolis AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personpolis_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personpolis_insdate,
    (personevn.personevn_insdt)::time without time zone AS personpolis_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personpolis_timestamp,
    personevn.personevn_index AS personpolis_index,
    personevn.personevn_count AS personpolis_count,
    personevn.personevn_insdt AS personpolis_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personpolis_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personpolis_begdt,
    personevn.personevn_frmrlastdt AS personpolis_frmrlastdt,
    polis.polis_id,
    polis.polistype_id,
    polis.orgsmo_id,
    polis.omssprterr_id,
    polis.polis_ser,
    polis.polis_num,
    polis.polis_begdate,
    polis.polis_enddate,
    polis.polisclosecause_id,
    polis.bdz_id,
    polis.polis_plandate,
    polis.polis_changedate,
    polis.dogstrah_num,
    polis.polis_guid,
    polis.polisformtype_id,
    polis.polis_numint
   FROM (((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 8))))
     JOIN dbo.personpolis ON (((personpolis.personpolis_id = personevn.personevn_id) AND (personpolis.server_id = personevn.server_id))))
     LEFT JOIN dbo.polis ON ((personpolis.polis_id = polis.polis_id)));

CREATE VIEW dbo.v_personsecname AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsecname_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsecname_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsecname_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsecname_timestamp,
    personevn.personevn_index AS personsecname_index,
    personevn.personevn_count AS personsecname_count,
    personevn.personevn_insdt AS personsecname_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsecname_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsecname_begdt,
    personevn.personevn_frmrlastdt AS personsecname_frmrlastdt,
    personsecname.personsecname_secname
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 3))))
     JOIN dbo.personsecname ON (((personsecname.personsecname_id = personevn.personevn_id) AND (personsecname.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personsex AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsex_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsex_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsex_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsex_timestamp,
    personevn.personevn_index AS personsex_index,
    personevn.personevn_count AS personsex_count,
    personevn.personevn_insdt AS personsex_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsex_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsex_begdt,
    personevn.personevn_frmrlastdt AS personsex_frmrlastdt,
    personsex.sex_id
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 5))))
     JOIN dbo.personsex ON (((personsex.personsex_id = personevn.personevn_id) AND (personsex.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personsnils AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsnils_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsnils_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsnils_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsnils_timestamp,
    personevn.personevn_index AS personsnils_index,
    personevn.personevn_count AS personsnils_count,
    personevn.personevn_insdt AS personsnils_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsnils_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsnils_begdt,
    personevn.personevn_frmrlastdt AS personsnils_frmrlastdt,
    personsnils.personsnils_snils
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 6))))
     JOIN dbo.personsnils ON (((personsnils.personsnils_id = personevn.personevn_id) AND (personsnils.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personsoccardnum AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsoccardnum_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsoccardnum_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsoccardnum_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsoccardnum_timestamp,
    personevn.personevn_index AS personsoccardnum_index,
    personevn.personevn_count AS personsoccardnum_count,
    personevn.personevn_insdt AS personsoccardnum_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsoccardnum_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsoccardnum_begdt,
    personevn.personevn_frmrlastdt AS personsoccardnum_frmrlastdt,
    personsoccardnum.personsoccardnum_soccardnum
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 21))))
     JOIN dbo.personsoccardnum ON (((personsoccardnum.personsoccardnum_id = personevn.personevn_id) AND (personsoccardnum.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personsocstatus AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsocstatus_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsocstatus_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsocstatus_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsocstatus_timestamp,
    personevn.personevn_index AS personsocstatus_index,
    personevn.personevn_count AS personsocstatus_count,
    personevn.personevn_insdt AS personsocstatus_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsocstatus_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsocstatus_begdt,
    personevn.personevn_frmrlastdt AS personsocstatus_frmrlastdt,
    personsocstatus.socstatus_id
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 7))))
     JOIN dbo.personsocstatus ON (((personsocstatus.personsocstatus_id = personevn.personevn_id) AND (personsocstatus.server_id = personevn.server_id))));

-- DEPCY: This VIEW is a dependency of VIEW: dbo.v_personstate_dop

CREATE VIEW dbo.v_timetablemedservice AS
	SELECT timetablemedservice.timetablemedservice_id,
    timetablemedservice.person_id,
    timetablemedservice.medservice_id,
    timetablemedservice.timetablemedservice_day,
    timetablemedservice.timetablemedservice_begtime,
    timetablemedservice.timetablemedservice_time,
    timetablemedservice.timetabletype_id,
    timetablemedservice.timetablemedservice_isdop,
    timetablemedservice.recclass_id,
    timetablemedservice.evn_id,
    timetablemedservice.pmuser_insid,
    timetablemedservice.pmuser_updid,
    timetablemedservice.timetablemedservice_insdt,
    timetablemedservice.timetablemedservice_upddt,
    timetablemedservice.uslugacomplexmedservice_id,
    timetablemedservice.evndirection_id,
    timetablemedservice.timetablemedservice_facttime,
    timetablemedservice.recmethodtype_id,
    timetableextend.timetableextend_descr,
    timetableextend.timetableextend_upddt,
    timetableextend.pmuser_updid AS timetableextend_pmuser_updid
   FROM (dbo.timetablemedservice
     LEFT JOIN dbo.timetableextend ON ((timetablemedservice.timetablemedservice_id = timetableextend.timetablemedservice_id)))
  WHERE ((timetablemedservice.timetablemedservice_deleted = 1) OR (timetablemedservice.timetablemedservice_deleted IS NULL));

CREATE VIEW dbo.v_personstate_dop AS
	SELECT personstate.person_id,
    person.server_id AS server_pid,
    person.person_isinerz,
    personstate.server_id,
    personstate.personevn_id,
    personstate.personsurname_surname AS person_surname,
    personstate.personfirname_firname AS person_firname,
    personstate.personsecname_secname AS person_secname,
    personstate.personsurname_surnamer AS person_surnamer,
    personstate.personfirname_firnamer AS person_firnamer,
    personstate.personsecname_secnamer AS person_secnamer,
    personstate.personbirthday_birthday AS person_birthday,
    personstate.sex_id,
    personstate.personsnils_snils AS person_snils,
    personstate.socstatus_id,
    personstate.polis_id,
    personstate.polis_ser,
    personstate.polis_num,
    personstate.polistype_id,
    personstate.document_id,
    personstate.document_ser,
    personstate.document_num,
    personstate.uaddress_id,
    personstate.paddress_id,
    personstate.job_id,
    personstate.personpolisednum_ednum AS person_ednum,
    personstate.personphone_phone AS person_phone,
    personstate.personinn_inn AS person_inn,
    personstate.personsoccardnum_id,
    personstate.personsoccardnum_soccardnum AS person_soccardnum,
    personstate.lpu_id,
    personstate.personfamilystatus_id,
    personstate.familystatus_id,
    personstate.personfamilystatus_ismarried,
    person.person_isunknown,
    person.person_isdead,
    person.personclosecause_id,
    person.person_deaddt,
    person.person_closedt,
    person.personidentstate_id,
    person.person_identdt,
    person.person_isencryphiv,
    personstate.personphone_comment,
    personstate.personnationalitystatus_id,
    personstate.nationalitystatus_id,
    personstate.klcountry_id,
    personstate.nationalitystatus_istwonation,
    personstate.legalstatusvzn_id,
    person.person_isnotinn,
    personstate.pmuser_insid,
    personstate.pmuser_updid,
    personstate.personstate_insdt,
    personstate.personstate_upddt,
    lpuunit.lpuunit_id
   FROM (((dbo.personstate personstate
     JOIN dbo.person person ON (((personstate.person_id = person.person_id) AND (COALESCE(person.person_deleted, (1)::bigint) = 1))))
     LEFT JOIN dbo.personcardstate personcardstate ON (((personcardstate.person_id = personstate.person_id) AND (personcardstate.lpuattachtype_id = 1))))
     LEFT JOIN LATERAL ( SELECT DISTINCT COALESCE(mslu.lpuunit_id, msbu.lpuunit_id, msl.lpuunit_id, NULL::bigint) AS lpuunit_id
           FROM (((((dbo.v_lpuregion lpuregion
             JOIN dbo.v_lpusection lpusection ON ((lpusection.lpusection_id = lpuregion.lpusection_id)))
             JOIN dbo.v_lpuunit lpuunit_1 ON ((lpuunit_1.lpuunit_id = lpusection.lpuunit_id)))
             LEFT JOIN LATERAL ( SELECT m.lpuunit_id
                   FROM (dbo.v_medservice m
                     JOIN dbo.v_lpuunit luenddt1 ON ((luenddt1.lpuunit_id = m.lpuunit_id)))
                  WHERE ((m.medservicetype_id = 70) AND (m.lpuunit_id = lpuunit_1.lpuunit_id) AND (EXISTS ( SELECT ttms.timetablemedservice_id,
                            ttms.person_id,
                            ttms.medservice_id,
                            ttms.timetablemedservice_day,
                            ttms.timetablemedservice_begtime,
                            ttms.timetablemedservice_time,
                            ttms.timetabletype_id,
                            ttms.timetablemedservice_isdop,
                            ttms.recclass_id,
                            ttms.evn_id,
                            ttms.pmuser_insid,
                            ttms.pmuser_updid,
                            ttms.timetablemedservice_insdt,
                            ttms.timetablemedservice_upddt,
                            ttms.uslugacomplexmedservice_id,
                            ttms.evndirection_id,
                            ttms.timetablemedservice_facttime,
                            ttms.recmethodtype_id,
                            ttms.timetableextend_descr,
                            ttms.timetableextend_upddt,
                            ttms.timetableextend_pmuser_updid
                           FROM dbo.v_timetablemedservice ttms
                          WHERE ((ttms.medservice_id = m.medservice_id) AND (ttms.person_id IS NULL) AND ((ttms.timetablemedservice_day >= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = (dbo.tzgetdate())::date))) AND (ttms.timetablemedservice_day <= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = ((dbo.tzgetdate())::date + 14))))))
                         LIMIT 1)) AND (luenddt1.lpuunit_enddate IS NULL))) mslu ON (true))
             LEFT JOIN LATERAL ( SELECT m2.lpuunit_id
                   FROM (dbo.v_medservice m2
                     JOIN dbo.v_lpuunit luenddt2 ON ((luenddt2.lpuunit_id = m2.lpuunit_id)))
                  WHERE ((m2.medservicetype_id = 70) AND (m2.lpubuilding_id = lpuunit_1.lpubuilding_id) AND (EXISTS ( SELECT ttms2.timetablemedservice_id,
                            ttms2.person_id,
                            ttms2.medservice_id,
                            ttms2.timetablemedservice_day,
                            ttms2.timetablemedservice_begtime,
                            ttms2.timetablemedservice_time,
                            ttms2.timetabletype_id,
                            ttms2.timetablemedservice_isdop,
                            ttms2.recclass_id,
                            ttms2.evn_id,
                            ttms2.pmuser_insid,
                            ttms2.pmuser_updid,
                            ttms2.timetablemedservice_insdt,
                            ttms2.timetablemedservice_upddt,
                            ttms2.uslugacomplexmedservice_id,
                            ttms2.evndirection_id,
                            ttms2.timetablemedservice_facttime,
                            ttms2.recmethodtype_id,
                            ttms2.timetableextend_descr,
                            ttms2.timetableextend_upddt,
                            ttms2.timetableextend_pmuser_updid
                           FROM dbo.v_timetablemedservice ttms2
                          WHERE ((ttms2.medservice_id = m2.medservice_id) AND (ttms2.person_id IS NULL) AND ((ttms2.timetablemedservice_day >= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = (dbo.tzgetdate())::date))) AND (ttms2.timetablemedservice_day <= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = ((dbo.tzgetdate())::date + 14))))))
                         LIMIT 1)) AND (luenddt2.lpuunit_enddate IS NULL))) msbu ON (true))
             LEFT JOIN LATERAL ( SELECT m3.lpuunit_id
                   FROM (dbo.v_medservice m3
                     JOIN dbo.v_lpuunit luenddt3 ON ((luenddt3.lpuunit_id = m3.lpuunit_id)))
                  WHERE ((m3.medservicetype_id = 70) AND (m3.lpu_id = lpuregion.lpu_id) AND (EXISTS ( SELECT ttms3.timetablemedservice_id,
                            ttms3.person_id,
                            ttms3.medservice_id,
                            ttms3.timetablemedservice_day,
                            ttms3.timetablemedservice_begtime,
                            ttms3.timetablemedservice_time,
                            ttms3.timetabletype_id,
                            ttms3.timetablemedservice_isdop,
                            ttms3.recclass_id,
                            ttms3.evn_id,
                            ttms3.pmuser_insid,
                            ttms3.pmuser_updid,
                            ttms3.timetablemedservice_insdt,
                            ttms3.timetablemedservice_upddt,
                            ttms3.uslugacomplexmedservice_id,
                            ttms3.evndirection_id,
                            ttms3.timetablemedservice_facttime,
                            ttms3.recmethodtype_id,
                            ttms3.timetableextend_descr,
                            ttms3.timetableextend_upddt,
                            ttms3.timetableextend_pmuser_updid
                           FROM dbo.v_timetablemedservice ttms3
                          WHERE ((ttms3.medservice_id = m3.medservice_id) AND (ttms3.person_id IS NULL) AND ((ttms3.timetablemedservice_day >= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = (dbo.tzgetdate())::date))) AND (ttms3.timetablemedservice_day <= ( SELECT v_day.day_id
                                   FROM dbo.v_day
                                  WHERE (v_day.day_date = ((dbo.tzgetdate())::date + 14))))))
                         LIMIT 1)) AND (luenddt3.lpuunit_enddate IS NULL))) msl ON (true))
          WHERE (lpuregion.lpuregion_id = personcardstate.lpuregion_id)) lpuunit ON (true));

CREATE VIEW dbo.v_personsurname AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personsurname_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personsurname_insdate,
    (personevn.personevn_insdt)::time without time zone AS personsurname_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personsurname_timestamp,
    personevn.personevn_index AS personsurname_index,
    personevn.personevn_count AS personsurname_count,
    personevn.personevn_insdt AS personsurname_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personsurname_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personsurname_begdt,
    personevn.personevn_frmrlastdt AS personsurname_frmrlastdt,
    personsurname.personsurname_surname
   FROM ((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 1))))
     JOIN dbo.personsurname ON (((personsurname.personsurname_id = personevn.personevn_id) AND (personsurname.server_id = personevn.server_id))));

CREATE VIEW dbo.v_personuaddress AS
	SELECT personevnclass.personevnclass_id,
    personevnclass.personevnclass_name,
    personevn.server_id,
    personevn.personevn_id AS personuaddress_id,
    ((personevn.personevn_insdt)::date)::timestamp without time zone AS personuaddress_insdate,
    (personevn.personevn_insdt)::time without time zone AS personuaddress_instime,
    personevn.person_id,
    personevn.personevn_timestamp AS personuaddress_timestamp,
    personevn.personevn_index AS personuaddress_index,
    personevn.personevn_count AS personuaddress_count,
    personevn.personevn_insdt AS personuaddress_insdt,
    personevn.pmuser_insid,
    personevn.personevn_upddt AS personuaddress_upddt,
    personevn.pmuser_updid,
    personevn.personevn_begdt AS personuaddress_begdt,
    personevn.personevn_frmrlastdt AS personuaddress_frmrlastdt,
    address.address_id,
    address.klareatype_id,
    address.klcountry_id,
    address.klrgn_id,
    address.klsubrgn_id,
    address.klcity_id,
    address.kltown_id,
    address.klstreet_id,
    address.address_zip,
    address.address_house,
    address.address_corpus,
    address.address_flat,
    address.address_address,
    address.klareastat_id,
    address.address_begdate,
    address.address_nick,
    address.personsprterrdop_id,
    address.addressspecobject_id
   FROM (((dbo.personevnclass
     JOIN dbo.v_personevn personevn ON (((personevn.personevnclass_id = personevnclass.personevnclass_id) AND (personevn.personevnclass_id = 10))))
     JOIN dbo.personuaddress ON (((personuaddress.personuaddress_id = personevn.personevn_id) AND (personuaddress.server_id = personevn.server_id))))
     LEFT JOIN dbo.address ON ((personuaddress.uaddress_id = address.address_id)));

CREATE VIEW dbo.v_prehospdirect AS
	SELECT prehospdirect.prehospdirect_id,
    prehospdirect.prehospdirect_code,
    prehospdirect.prehospdirect_name,
    prehospdirect.prehospdirect_sysnick,
    prehospdirect.pmuser_insid,
    prehospdirect.pmuser_updid,
    prehospdirect.prehospdirect_insdt,
    prehospdirect.prehospdirect_upddt,
    prehospdirect.klcountry_id,
    prehospdirect.prehospdirect_begdate,
    prehospdirect.prehospdirect_enddate
   FROM dbo.prehospdirect
  WHERE (1 = 1);

COMMENT ON VIEW dbo.v_prehospdirect IS 'Autogen';


CREATE VIEW lis.v_analyzerrack AS
	SELECT analyzerrack.analyzerrack_id,
    analyzerrack.analyzermodel_id,
    analyzerrack.analyzerrack_dimensionx,
    analyzerrack.analyzerrack_dimensiony,
    analyzerrack.analyzerrack_isdefault,
    analyzerrack.pmuser_insid,
    analyzerrack.pmuser_updid,
    analyzerrack.analyzerrack_insdt,
    analyzerrack.analyzerrack_upddt,
    analyzerrack.analyzerrack_deleted
   FROM lis.analyzerrack
  WHERE ((1 = 1) AND ((analyzerrack.analyzerrack_deleted = 1) OR (analyzerrack.analyzerrack_deleted IS NULL)));

CREATE VIEW rls.v_drugmnncode AS
	SELECT drugmnncode.drugmnncode_id,
    drugmnncode.actmatters_id,
    drugmnncode.drugmnncode_code,
    drugmnncode.pmuser_insid,
    drugmnncode.pmuser_updid,
    drugmnncode.drugmnncode_insdt,
    drugmnncode.drugmnncode_upddt,
    drugmnncode.region_id
   FROM rls.drugmnncode
  WHERE ((1 = 1) AND ((drugmnncode.region_id = dbo.getregion()) OR (drugmnncode.region_id IS NULL)));
 
alter table r1.registryerror add registryerror_name varchar(500) null; 
 CREATE OR REPLACE VIEW r1.v_registryerror
AS SELECT registryerror.registry_id,
    person.person_id,
    evnvizitpl.server_id,
    evnvizitpl.personevn_id,
    registryerror.evn_id,
    evnvizitpl.evnclass_id,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    evnvizitpl.medpersonal_id,
    (((rtrim(COALESCE(person.person_surname, ''::character varying)::text) || ' '::text) || rtrim(COALESCE(person.person_firname, ''::character varying)::text)) || ' '::text) || rtrim(COALESCE(person.person_secname, ''::character varying)::text) AS person_fio,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    person.person_birthday,
    NULL::bigint AS person_isbdz,
    evnvizitpl.evnvizitpl_setdate::date::timestamp without time zone AS evn_setdate,
    evnvizitpl.evnvizitpl_disdate::date::timestamp without time zone AS evn_disdate,
    (rtrim(lpusection.lpusection_code::text) || '. '::text) || lpusection.lpusection_name::text AS lpusection_name,
    registryerrortype.registryerrortype_code,
    COALESCE(registryerror.registryerror_name, registryerrortype.registryerrortype_name) AS registryerrortype_name,
    COALESCE(registryerror.registryerror_desc, registryerrortype.registryerrortype_descr) AS registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evnvizitpl.evnvizitpl_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    registryerror.registryerror_desc
   FROM r1.registryerror
     JOIN dbo.v_evnvizitpl evnvizitpl ON evnvizitpl.evnvizitpl_id = registryerror.evn_id
     JOIN dbo.v_person_reg person ON person.personevn_id = evnvizitpl.personevn_id AND person.server_id = evnvizitpl.server_id
     JOIN r1.registryerrortype ON registryerrortype.registryerrortype_id = registryerror.registryerrortype_id
     JOIN dbo.registryerrorclass ON registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id
     JOIN dbo.lpusection ON lpusection.lpusection_id = registryerror.lpusection_id
     LEFT JOIN dbo.lpusectionprofile ON lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id
UNION ALL
 SELECT registryerror.registry_id,
    person.person_id,
    evnsection.server_id,
    evnsection.personevn_id,
    registryerror.evn_id,
    evnsection.evnclass_id,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    evnsection.medpersonal_id,
    (((rtrim(COALESCE(person.person_surname, ''::character varying)::text) || ' '::text) || rtrim(COALESCE(person.person_firname, ''::character varying)::text)) || ' '::text) || rtrim(COALESCE(person.person_secname, ''::character varying)::text) AS person_fio,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    person.person_birthday,
    NULL::bigint AS person_isbdz,
    evnsection.evnsection_setdate::date::timestamp without time zone AS evn_setdate,
    evnsection.evnsection_disdate::date::timestamp without time zone AS evn_disdate,
    (rtrim(lpusection.lpusection_code::text) || '. '::text) || lpusection.lpusection_name::text AS lpusection_name,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evnsection.evnsection_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    registryerror.registryerror_desc
   FROM r1.registryerror
     JOIN dbo.v_evnsection evnsection ON evnsection.evnsection_id = registryerror.evn_id
     JOIN dbo.v_person_reg person ON person.personevn_id = evnsection.personevn_id AND person.server_id = evnsection.server_id
     JOIN r1.registryerrortype ON registryerrortype.registryerrortype_id = registryerror.registryerrortype_id
     JOIN dbo.registryerrorclass ON registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id
     JOIN dbo.lpusection ON lpusection.lpusection_id = registryerror.lpusection_id
     LEFT JOIN dbo.lpusectionprofile ON lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id
UNION ALL
 SELECT registryerror.registry_id,
    person.person_id,
    evnus.server_id,
    evnus.personevn_id,
    registryerror.evn_id,
    evnus.evnclass_id,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    evnus.medpersonal_id,
    (((rtrim(COALESCE(person.person_surname, ''::character varying)::text) || ' '::text) || rtrim(COALESCE(person.person_firname, ''::character varying)::text)) || ' '::text) || rtrim(COALESCE(person.person_secname, ''::character varying)::text) AS person_fio,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    person.person_birthday,
    NULL::bigint AS person_isbdz,
    evnus.evnuslugapar_setdate::date::timestamp without time zone AS evn_setdate,
    evnus.evnuslugapar_disdate::date::timestamp without time zone AS evn_disdate,
    (rtrim(lpusection.lpusection_code::text) || '. '::text) || lpusection.lpusection_name::text AS lpusection_name,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evnus.evnuslugapar_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    registryerror.registryerror_desc
   FROM r1.registryerror
     JOIN dbo.v_evnuslugapar evnus ON evnus.evnuslugapar_id = registryerror.evn_id
     JOIN dbo.v_person_reg person ON person.personevn_id = evnus.personevn_id AND person.server_id = evnus.server_id
     JOIN r1.registryerrortype ON registryerrortype.registryerrortype_id = registryerror.registryerrortype_id
     JOIN dbo.registryerrorclass ON registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id
     JOIN dbo.lpusection ON lpusection.lpusection_id = registryerror.lpusection_id
     LEFT JOIN dbo.lpusectionprofile ON lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id
UNION ALL
 SELECT registryerror.registry_id,
    person.person_id,
    evnpld.server_id,
    evnpld.personevn_id,
    registryerror.evn_id,
    evnpld.evnclass_id,
    registryerror.registryerrortype_id,
    registryerror.lpusection_id,
    medsfc.medpersonal_id,
    (((rtrim(COALESCE(person.person_surname, ''::character varying)::text) || ' '::text) || rtrim(COALESCE(person.person_firname, ''::character varying)::text)) || ' '::text) || rtrim(COALESCE(person.person_secname, ''::character varying)::text) AS person_fio,
    person.person_surname,
    person.person_firname,
    person.person_secname,
    person.person_birthday,
    NULL::bigint AS person_isbdz,
    evnpld.evnpldisp_setdt::date::timestamp without time zone AS evn_setdate,
    evnpld.evnpldisp_disdt::date::timestamp without time zone AS evn_disdate,
    (rtrim(lpusection.lpusection_code::text) || '. '::text) || lpusection.lpusection_name::text AS lpusection_name,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    evnpld.evnpldisp_rid AS evn_rid,
    registryerror.pmuser_insid,
    registryerror.pmuser_updid,
    registryerror.registryerror_insdt,
    registryerror.registryerror_upddt,
    lpusectionprofile.lpusectionprofile_code,
    registryerror.registryerror_desc
   FROM r1.registryerror
     JOIN dbo.v_evnpldisp evnpld ON evnpld.evnpldisp_id = registryerror.evn_id
     JOIN dbo.v_person_reg person ON person.personevn_id = evnpld.personevn_id AND person.server_id = evnpld.server_id
     JOIN r1.registryerrortype ON registryerrortype.registryerrortype_id = registryerror.registryerrortype_id
     JOIN dbo.registryerrorclass ON registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id
     JOIN dbo.lpusection ON lpusection.lpusection_id = registryerror.lpusection_id
     LEFT JOIN dbo.lpusectionprofile ON lpusectionprofile.lpusectionprofile_id = lpusection.lpusectionprofile_id
     LEFT JOIN dbo.medstafffactcache medsfc ON evnpld.medstafffact_id = medsfc.medstafffact_id;

CREATE OR REPLACE VIEW dbo.v_drug7noz
AS SELECT drug.drug_id,
    drug.drug_code,
    drug.drug_codeg,
    drug.drug_name,
    drugmnn.drugmnn_id,
    drugmnn.drugmnn_code,
    drugmnn.drugmnn_name,
    drugmnn.drugmnn_namelat,
    drug.drugtorg_id,
    drugtorg.drugtorg_code,
    drugtorg.drugtorg_name,
    drugtorg.drugtorg_namelat,
    drug.drugform_id,
    drugform.drugform_name,
    drug.drugformvip_id,
    COALESCE(drug.drug_doseq, (COALESCE(' '::text || NULLIF(drug.drug_vol, 0::double precision)::character varying(10)::text, ''::text) || COALESCE(' '::text || NULLIF(drug.drug_mass, 0::double precision)::character varying(10)::text, ''::text))::character varying) AS drug_dose,
    NULLIF((((COALESCE(drug.drug_doseq, ''::character varying)::text || COALESCE(drug.drug_doseei, ''::character varying)::text) || COALESCE((' '::text || NULLIF(drug.drug_vol, 0::double precision)::character varying(10)::text) || NULLIF(drugedvol.drugedvol_name::text, '~'::text), ''::text)) || COALESCE((' '::text || NULLIF(drug.drug_mass, 0::double precision)::character varying(10)::text) || NULLIF(drugedmass.drugedmass_name::text, '~'::text), ''::text)) || COALESCE((' '::text || NULLIF(drug.drug_dosecount, 0)::character varying(10)::text) || 'доз'::text, ''::text), ''::text) AS drug_dosefull,
    drug.drugunit_id,
    drug.drugclass_id,
    drug.drug_fas,
    drug.drug_islive,
    drug.drug_isdel,
    drug.drug_isnotrecept,
    drug.drug_isnotactive,
    drug.drug_iskek,
    drug.drug_p9,
    drug.drug_p10,
    '2009-01-01'::date AS drug_begdate,
    NULL::text AS drug_enddate,
    drug.pmuser_insid,
    drug.pmuser_updid,
    drug.drug_insdt,
    drug.drug_upddt
   FROM dbo.drug
     JOIN dbo.drugmnn ON COALESCE(drug.drugmnn_id, 1::bigint) = drugmnn.drugmnn_id
     LEFT JOIN dbo.drugtorg ON drug.drugtorg_id = drugtorg.drugtorg_id
     LEFT JOIN dbo.drugform ON drug.drugform_id = drugform.drugform_id
     LEFT JOIN dbo.drugformvip ON drug.drugformvip_id = drugformvip.drugformvip_id
     LEFT JOIN dbo.drugedvol ON drug.drugedvol_id = drugedvol.drugedvol_id
     LEFT JOIN dbo.drugedmass ON drug.drugedmass_id = drugedmass.drugedmass_id
     JOIN LATERAL ( SELECT DISTINCT ddmnn.drugmnn_id
           FROM dbo.v_drugnormativelist list
             JOIN dbo.v_personregistertype rt ON rt.personregistertype_id = list.personregistertype_id
             JOIN dbo.v_drugnormativelistspec mnn ON list.drugnormativelist_id = mnn.drugnormativelist_id
             JOIN rls.actmatters ac ON ac.actmatters_id = mnn.drugnormativelistspecmnn_id
             JOIN rls.v_drugmnncode mnc ON mnc.actmatters_id = mnn.drugnormativelistspecmnn_id
             JOIN dbo.drugmnn ddmnn ON ddmnn.drugmnn_code::character varying::text = mnc.drugmnncode_code::text
          WHERE 1 = 1 AND (ddmnn.region_id IS NULL OR ddmnn.region_id = dbo.getregion())
         AND rt.personregistertype_sysnick::text = 'nolos'::text 
        AND (COALESCE(list.drugnormativelist_begdt, '1900-01-01'::date::timestamp without time zone)::date <= dbo.getdate()::date
        AND COALESCE(list.drugnormativelist_enddt, '2099-01-01 00:00:00'::timestamp without time zone)::date >= dbo.getdate()::date 
        	OR COALESCE(mnn.drugnormativelistspec_begdt, '1900-01-01'::date::timestamp without time zone)::date <= dbo.getdate()::date
       AND COALESCE(mnn.drugnormativelistspec_enddt, '2099-01-01 00:00:00'::timestamp without time zone)::date >= dbo.getdate()::date) 
      AND drugmnn.drugmnn_id = ddmnn.drugmnn_id) dnl ON true;
