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

CREATE FUNCTION r477.p_registry_exp_z_sl(p_registry_id bigint, p_iszno integer DEFAULT NULL::integer) RETURNS TABLE(evn_id bigint, maxevn_id bigint, person_id bigint, "N_ZAP" integer, "PR_NOV" integer, "VPOLIS" integer, "SPOLIS" text, "NPOLIS" text, "ST_OKATO" text, "SMO" text, "SMO_OGRN" text, "SMO_OK" text, "SMO_NAM" text, "INV" integer, "MSE" integer, "NOVOR" text, "VNOV_D" integer, "VNOV_M" integer, "IDCASE" bigint, "USL_OK" integer, "VIDPOM" integer, "FOR_POM" integer, "NPR_MO" text, "NPR_DATE" text, "LPU" text, "DATE_Z_1" text, "DATE_Z_2" text, "KD_Z" integer, "RSLT" integer, "ISHOD" integer, "VB_P" integer, "IDSP" integer, "SUMV" numeric, "OPLATA" integer, "SUMP" numeric, "SANK_IT" numeric)
    LANGUAGE plpgsql
    AS $$
	DECLARE
    	_registry_id_arr 	bigint[] = r477.p_registry_get_registry_id_arr(p_registry_id);  
        _lpu_code 			text;         
	BEGIN
    
_lpu_code = (select l.lpu_f003mcod from r477.registry r join lpu l on r.lpu_id = l.lpu_id where r.registry_id = p_registry_id);      
    
return query (
	
	select 
        rd.evn_id,
        rd.evn_id as maxevn_id,
        rd.person_id,
        --rd.registrydata_rownum::integer as N_ZAP,
        (row_number() over(order by rd.evn_id))::integer as N_ZAP,
        case when r.registry_isrepeated = 2 then 1 else 0 end as PR_NOV,
        --rd.person_id::text as ID_PAC,
        (rd.region_data -> 'polis' ->> 'vpolis')::integer as VPOLIS,
        nullif(rd.region_data -> 'polis' ->> 'spolis','') as SPOLIS,
        nullif(rd.region_data -> 'polis' ->> 'npolis','') as NPOLIS,
        case when rd.region_data -> 'polis' ->> 'vpolis' = '1' then nullif(OmsSprTerr.omssprterr_okato,'') else null end as ST_OKATO,
        nullif(OrgSmo.orgsmo_f002smocod,'') AS SMO,
        nullif(Org.org_ogrn,'') AS SMO_OGRN,
        left(coalesce(nullif(Org.org_okato,''),nullif(KLArea.kladr_ocatd,'')),5) as SMO_OK, 
        --nullif(Org.org_nick,'') as SMO_NAM,
        NULLIF((SELECT cod FROM r477.terr005 WHERE cod_f002 = OrgSmo.orgsmo_f002smocod LIMIT 1)::TEXT, '')  as SMO_NAM,
        null::integer as INV,
        null::integer as MSE,
        case 
            when rd.region_data -> 'deputy' is null then '0' 
            else concat(
                rd.region_data -> 'person' ->> 'sex_id',
                to_char((rd.region_data -> 'person' ->> 'birthday')::date,'DD'),
                to_char((rd.region_data -> 'person' ->> 'birthday')::date,'MM'),
                to_char((rd.region_data -> 'person' ->> 'birthday')::date,'YY'),'1'
                )
        end::text as NOVOR,
        case when rd.region_data -> 'deputy' is null then pcw.PersonWeight_Weight::integer else null::integer end as VNOV_D,
        case when rd.region_data -> 'deputy' is not null then pcw.PersonWeight_Weight::integer else null::integer end as VNOV_M,
        --rd.evn_id as IDCASE,
        --rd.registrydata_rownum::bigint as IDCASE,
        (row_number() over(order by rd.evn_id))::bigint as IDCASE,
        case 
            when rd.region_data ->> 'evnclass_sysnick' in ('EvnVizitPL','EvnVizitPLStom','EvnUslugaPar') then 3 
            when rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' then case when rd.lpuunittype_id = 1 then 1 else 2 end 
            else null 
        end as USL_OK,
        (rd.region_data ->> 'vidpom')::integer as VIDPOM,
        (rd.region_data ->> 'for_pom')::integer as FOR_POM,
        case 
        	when rd.region_data ->> 'item_type' = 'stac' and rd.lpuunittype_id = 1 and (rd.region_data ->> 'for_pom')::integer = 1 then null
        	when coalesce(lpud.lpu_id, orgd.org_id) is not null then coalesce(lpud.lpu_f003mcod::text, orgd.org_f003mcod::text, '000000')
            --else coalesce(lpud.lpu_f003mcod::text, orgd.org_f003mcod::text) 
            else null 
        end as NPR_MO,
        case 
        	--when coalesce(lpud.lpu_f003mcod::text, orgd.org_f003mcod::text) is null then null 
        	when coalesce(lpud.lpu_id, orgd.org_id) is null then null 
            when rd.region_data ->> 'item_type' = 'stac' and rd.lpuunittype_id = 1 and (rd.region_data ->> 'for_pom')::integer = 1 then null 
            else to_char(coalesce(dir.evndirection_setdate::date,(rd.region_data -> 'direction' ->> 'direction_date')::date),'YYYY-MM-DD')::text 
        end as NPR_DATE,
        _lpu_code as LPU,
        to_char(rd.evn_setdate::date,'YYYY-MM-DD') as DATE_Z_1,
        to_char(rd.evn_disdate::date,'YYYY-MM-DD') as DATE_Z_2,
        case 
        	when rd.region_data ->> 'evnclass_sysnick' = 'EvnSection' then rd.registrydata_kdpay::integer 
            else null 
        end as KD_Z,
        coalesce(flt.leavetype_code,lt.leavetype_code,res.resultclass_code) as RSLT,
        case 
        	when coalesce(flt.leavetype_code,lt.leavetype_code) in (105,106) then 104
            when coalesce(flt.leavetype_code,lt.leavetype_code) in (205,206) then 204
        	else frdst.resultdeseasetype_code 
        end as ISHOD,
        coalesce(rd.region_data ->> 'vb_p')::integer as VB_P,
        PayMedType.paymedtype_code as IDSP,
        coalesce(rd.registrydata_itogsum,0)::numeric as SUMV,
        null::integer as OPLATA,
        null::numeric as SUMP,
        null::numeric as SANK_IT
    from 
        r477.registrydata rd 
         join r477.registry r on rd.registry_id = r.registry_id
         left join OmsSprTerr on rd.omssprterr_id = OmsSprTerr.omssprterr_id
         left join OrgSmo on rd.orgsmo_id = OrgSmo.orgsmo_id 
         left join Org on Org.org_id = OrgSmo.org_id
         left join lateral (select ost.klrgn_id from v_OrgServiceTerr ost where ost.org_id = OrgSmo.org_id order by ost.orgserviceterr_id limit 1) as ost on true --окато по территории обслуживания
         left join KLArea on KLArea.klarea_id = coalesce(OrgSmo.klrgn_id,ost.klrgn_id) 
         left join v_EvnDirection dir on dir.evndirection_id = (rd.region_data -> 'direction' ->> 'direction_id')::bigint 
         left join Lpu lpud on lpud.lpu_id = coalesce(dir.lpu_did,(rd.region_data -> 'direction' ->> 'lpu_did')::bigint)
         left join Org orgd on orgd.org_id = (rd.region_data -> 'direction' ->> 'org_did')::bigint
         
         left join ResultClass res on res.resultclass_id = rd.resultclass_id 
         left join LeaveType lt on rd.leavetype_id = lt.leavetype_id 
         left join fed.LeaveType flt on flt.leavetype_id = coalesce(lt.leavetype_fedid,res.leavetype_fedid)
         
         left join ResultDesease rds on rds.resultdesease_id = rd.resultdesease_id
         left join ResultDeseaseType rdst on rdst.resultdeseasetype_id = rd.resultdesease_id 
         left join fed.ResultDeseaseType frdst on frdst.resultdeseasetype_id = case rd.region_data ->> 'evnclass_sysnick' when 'EvnSection' then rds.resultdesease_fedid else rdst.resultdeseasetype_fedid end  
                  
         left join PayMedType on PayMedType.paymedtype_id = rd.paymedtype_id 
         
         left join lateral (
            select 
            	case when PersonWeight.Okei_id = 37 then PersonWeight_Weight * 1000 else PersonWeight_Weight end as PersonWeight_Weight
            from v_PersonNewborn PChild 
             join PersonWeight on PersonWeight.Person_id = PChild.person_id and PersonWeight.WeightMeasureType_id = 1  --select*From WeightMeasureType
            where 
            	PChild.Person_id = rd.person_id
            	and (
                	(
                    	datediff('day',(rd.region_data -> 'person' ->> 'birthday')::date,rd.Evn_setDate) <= 28 
                        and case when PersonWeight.Okei_id = 37 then PersonWeight_Weight * 1000 else PersonWeight_Weight end < 3000
                    ) 
                    or ChildTermType_id=2
                )
            order by WeightMeasureType_id,PersonWeight_setDT
            limit 1
		 ) pcw on true     
		left join lateral ( select re.evn_id
					from r477.registryerror re
					where rd.evn_id=re.evn_id and rd.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
        rd.registry_id = any(_registry_id_arr)
        and case p_iszno when 0 then coalesce(rd.registrydata_iszno,0) = 0 when 1 then rd.registrydata_iszno = 1 else true end 
        and rd.registrydata_deleted is distinct from 2 --кроме помеченных удаленными
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
    order by rd.evn_id    
    
);
	END;
$$;


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

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

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

_export_code = 
	case _registry_type_code 
    	--when 'omspol' 		then 'A'
        --when 'resemdent' 	then 'I' 
        --when 'omsstac' 		then 'H'
        when 'htm'	       then 'T'
        when 'disp_1'      then 'D'
        when 'disp_2'      then 'D'
        --when 'pdn'			then 'P'
        --else 
        --	case when p_iszno = 1 then 'C' else 'H' end
    end
;

return query (
 select
    p_registry_id as registry_id,
    '3.1'::text as VERSION,
    to_char(current_date,'YYYY-MM-DD') as DATA,
    concat(
    	_export_code,'M',Lpu.lpu_f003mcod,
        case when KatNasel.katnasel_sysnick = 'oblast' and r.OrgSmo_id is not null then 'S' else 'T' end,
        case when KatNasel.katnasel_sysnick = 'oblast' and r.OrgSmo_id is not null then OrgSMO.orgsmo_f002smocod else '68000' end,
        '_',to_char(r.registry_enddate,'YY'),to_char(r.registry_enddate,'MM')--,
       -- case when _registry_type_code not in ('htm', 'disp_1', 'disp_2') then _export_code else null end 
    ) as FILENAME,
    coalesce(rd.sd_z,0) as SD_Z,
    --r.Registry_id as CODE,
    LTRIM(RIGHT(r.Registry_id::TEXT, 8), '0')::BIGINT AS CODE,
    --regexp_replace(regexp_replace(r.registry_id::text,'^\d{1,2}0101',''),'^0+','')::bigint as CODE,
    Lpu.Lpu_f003mcod::text as CODE_MO,
    date_part('YEAR', r.Registry_endDate)::integer as YEAR,
    date_part('MONTH', r.Registry_endDate)::integer as MONTH,
    r.Registry_Num as NSCHET,
    to_char(r.Registry_accDate::date,'YYYY-MM-DD') as DSCHET,
    case when KatNasel.katnasel_sysnick = 'oblast'and r.OrgSmo_id is not null then orgSMO.orgsmo_f002smocod else '68000' end::text as PLAT,
    coalesce(rd.summav,0)::numeric(15,2)::text as SUMMAV,
    --case when _registry_type_code = 'pdn' then 'Счёт по ПДН' else null end as COMENTS,
    case 
    	when _registry_type_code = 'htm' then '7'
    	when _registry_type_code = 'omsks' then 
    		case p_iszno when 0 then '1' when 1 then '101' else '' end
    	when _registry_type_code = 'omsds' then 
    		case p_iszno when 0 then '8' when 1 then '108' else '' end
    	when _registry_type_code IN ('ambulatory', 'per_capita_other') then 
    		case p_iszno when 0 then '2' when 1 then '102' else '' end    
    	when _registry_type_code = 'per_capita_own' then 
    		case p_iszno when 0 then '21' when 1 then '121' else '' end  
    	when _registry_type_code = 'per_capita_alien' then 
    		case p_iszno when 0 then '22' when 1 then '122' else '' end  
    	when _registry_type_code = 'ambulatory_dialysis' then '9'   
    	when _registry_type_code = 'stom' then 
    		case p_iszno when 0 then '3' when 1 then '103' else '' end  
		when _registry_type_code = 'parusl' then '5'    		
		when _registry_type_code = 'mucalc' then '51'  
 
    end as COMENTS,
    null as SUMMAP,
    null as SUMMAP_R,
    null as SUMMAP_F,
    null as SANK_MEK,
    null as SANK_MEE,
    null as SANK_EKMP
from r477.Registry r  
 join Lpu on Lpu.Lpu_id = r.Lpu_id
 left join OrgSMO on OrgSMO.OrgSMO_id = r.OrgSmo_id
 left join KatNasel on r.katnasel_id = KatNasel.katnasel_id 
 left join lateral (
 	select sum(d.registrydata_itogsum) as summav,count(*) as sd_z from r477.registrydata d 
 			left join lateral ( select re.evn_id
					from r477.registryerror re
					where d.evn_id=re.evn_id and d.registry_id=re.registry_id
					limit 1
					) r_err on true	
    where 
    	d.registry_id = any(_registry_id_arr)
        and case p_iszno when 0 then coalesce(d.registrydata_iszno,0) = 0 when 1 then d.registrydata_iszno = 1 else true end
        and d.registrydata_deleted is distinct from 2 --кроме помеченных удаенными 
        and r_err.evn_id is null  -- и нет ошибок  PROMEDWEB-48335
 ) rd on true 
  left join lateral (
  	select lpuunit_id
    from r477.registrylpuunit lu
    where 
    	lu.registry_id = any(_registry_id_arr)
  ) lpuunit on true
  left join lateral (
  	select r.registrytype_id
    from r477.registry registry  
    left  join r477.registrygrouplink Rlink on RLink.Registry_pid = registry.Registry_id
    left join r477.registry r on  r.Registry_id =case when registry.RegistryType_id =13 then Rlink.Registry_id else registry.Registry_id end
    where registry.Registry_id = p_Registry_id
  ) reg on true
 where 
	r.Registry_id = p_Registry_id
);
END;
$$;


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

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

CREATE FUNCTION r477.p_registry_get_long_id(p_id bigint) RETURNS bigint
    LANGUAGE plpgsql
    AS $$
DECLARE
	_reg_prfx 	text 	 = concat(getregion(),'0101');
    _zero_count integer;
BEGIN
	
	_zero_count = case length(_reg_prfx) when 6 then 15 when 5 then 14 else 15 end - length(p_id::text) - length(_reg_prfx);
    return (rpad(_reg_prfx,length(_reg_prfx) + _zero_count,'0')||p_id::text)::bigint;  
  
END;
$$;


ALTER FUNCTION r477.p_registry_get_long_id(p_id bigint) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_get_registry_id_arr(p_registry_id bigint) RETURNS bigint[]
    LANGUAGE plpgsql
    AS $$
DECLARE
 	_p_registry_id_arr bigint[]; 
BEGIN
 
	_p_registry_id_arr = array(select registry_id from r477.registrygrouplink where registry_pid = p_registry_id)
    ;
    
    if _p_registry_id_arr = '{}'::bigint[] then 
    	return array[p_registry_id];
    else 
    	return _p_registry_id_arr;
    end if;  

END;
$$;


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

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

CREATE FUNCTION r477.p_registry_get_registry_type_code(p_registry_id bigint) RETURNS text
    LANGUAGE plpgsql
    AS $$
DECLARE
  
BEGIN
  
	return (
    
    	select 
        	case 
            	when gt.registrygrouptype_code = 36 then 'pdn'
                else t.registrytype_sysnick 
            end
        from r477.registry r 
 		 join dbo.registrytype t on r.registrytype_id = t.registrytype_id
         left join dbo.registrygrouptype gt on r.registrygrouptype_id = gt.registrygrouptype_id 
		where r.registry_id = p_registry_id
    
    );

END;
$$;


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

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

CREATE FUNCTION r477.p_registry_get_repeated_evn_id_arr(p_registry_id bigint, OUT registry_rid bigint, OUT evn_id_arr bigint[]) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE
	
    p_lpu_id bigint;
    p_lpubuilding_id bigint;
    p_orgsmo_id bigint;
    p_paytype_id bigint;
    p_katnasel_id bigint;
    p_registry_begdate timestamp;
    p_registry_enddate timestamp;
    p_pmuser_id bigint;    
    p_lpubuilding_id_arr bigint[]; 
    p_registry_isrepeated bigint; 
    p_registrytype_id bigint;
BEGIN
  
	registry_rid = null;
    evn_id_arr   = '{}'::bigint[];
    
    --получаем параметры счета 
    select 
        r.lpu_id,r.lpubuilding_id,r.orgsmo_id,r.paytype_id,r.katnasel_id,r.registry_begdate,r.registry_enddate,r.registry_isrepeated,r.registrytype_id
    into
        p_lpu_id,p_lpubuilding_id,p_orgsmo_id,p_paytype_id,p_katnasel_id,p_registry_begdate,p_registry_enddate,p_registry_isrepeated,p_registrytype_id
    from r477.registry r 
    where 
        r.registry_id = p_registry_id
    ;
    
    if p_registry_isrepeated = 2 then 
    
        --перечень подразделений для реестра 
        p_lpubuilding_id_arr = array(select rl.lpubuilding_id from r477.registrylpubuilding rl where rl.registry_id = p_registry_id order by 1)
        ;
        

        
        --находим реестр повтороной подачи
        registry_rid = (
            select registry_id from r477.registry r  
            where
                r.lpu_id = p_lpu_id and r.registrytype_id = p_registrytype_id 
                and r.registrystatus_id = 4 --оплаченный
                and r.paytype_id = p_paytype_id and r.katnasel_id = p_katnasel_id
                and coalesce(r.orgsmo_id,0) = coalesce(p_orgsmo_id,0)
                and r.registry_begdate = p_registry_begdate and r.registry_enddate = p_registry_enddate
                and p_lpubuilding_id_arr = array(select rl.lpubuilding_id from r477.registrylpubuilding rl where rl.registry_id = r.registry_id order by 1)
                and coalesce(r.registry_isrepeated,1) = 1 
            order by registry_id desc  
            limit 1 
        )
        ;
        
        --если основной реестр не найден то выходим
        if registry_rid is null then return; end if;
        
        evn_id_arr =  
            array(
              select coalesce((rd.region_data ->> 'real_evn_id')::bigint,rd.evn_id) from r477.registrydata rd
              where
                  rd.registry_id = registry_rid and rd.registrydata_ispaid is distinct from 2 
                  and exists (select 1 from r477.registryerrortfoms tf where tf.registry_id = rd.registry_id and rd.evn_id = tf.evn_id) 
            );
            
    else 
    
    	return;
    
    end if;

END;
$$;


ALTER FUNCTION r477.p_registry_get_repeated_evn_id_arr(p_registry_id bigint, OUT registry_rid bigint, OUT evn_id_arr bigint[]) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_get_vidpom(p_case_type text, p1_medicalcarekind_code text, p2_usl_ok text, p3_lpuunittype_id bigint, p4_spec_id bigint, p5_profile_id bigint) RETURNS text
    LANGUAGE plpgsql
    AS $_$
DECLARE
	_spec_code text;
    _profile_code text;
BEGIN

	--паллиативная/вмп 
    if p1_medicalcarekind_code in ('4','32') then return p1_medicalcarekind_code; end if;
    
    _spec_code = (select ms.medspecclass_code::text from fed.MedSpecClass ms where ms.medspecclass_id = p4_spec_id)
    ;
    
    --случаи поликлиники, неотложки, исследований, стоматологии 
    if p_case_type = 'EvnPL' then 
    
        _profile_code = (
            select coalesce(flsp.lpusectionprofile_code::text,lsp.lpusectionprofile_code::text) from LpuSectionProfile lsp 
             left join fed.LpuSectionProfile flsp on lsp.lpusectionprofile_fedid = flsp.lpusectionprofile_id
            where lsp.lpusectionprofile_id = p5_profile_id 
        );    
        
        if p2_usl_ok = '3' and (_spec_code ~ '^2\d\d$' or _profile_code = '87') then return '11'; end if; --первичная доврачебная
        
        if p2_usl_ok = '3' or (p2_usl_ok = '2' and p3_lpuunittype_id in (7,9)) then 
        
            if _spec_code in ('39','49','76') then 
                return '12';							--первичная врачебная 
            else 
                return '13';							--первичная специализированная
            end if;
        
        end if;
        
    
    --случаи диспансеризации
    elsif p_case_type = 'EvnPLDisp' then 
    
    	if _spec_code ~ '^2' then return '11'; else return '12'; end if; 
    
    --случаи стационара
    elseif p_case_type = 'EvnPS' then 
    
    
    end if;
    
    return p1_medicalcarekind_code;

END;
$_$;


ALTER FUNCTION r477.p_registry_get_vidpom(p_case_type text, p1_medicalcarekind_code text, p2_usl_ok text, p3_lpuunittype_id bigint, p4_spec_id bigint, p5_profile_id bigint) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_ins(INOUT p_registry_id bigint DEFAULT NULL::bigint, p_registrytype_id bigint DEFAULT NULL::bigint, p_lpu_id bigint DEFAULT NULL::bigint, p_registry_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_orgsmo_id bigint DEFAULT NULL::bigint, p_lpuunitset_id bigint DEFAULT NULL::bigint, p_registry_num character varying DEFAULT NULL::character varying, p_registry_accdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registrystatus_id bigint DEFAULT NULL::bigint, p_registry_sum numeric DEFAULT NULL::numeric, p_registry_isactive bigint DEFAULT NULL::bigint, p_registry_errorcount integer DEFAULT NULL::integer, p_registry_errorcommoncount integer DEFAULT NULL::integer, p_registry_recordcount integer DEFAULT NULL::integer, p_registry_exportpath character varying DEFAULT NULL::character varying, p_registry_expdt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_xmlexportpath character varying DEFAULT NULL::character varying, p_registry_xmlexpdt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_sumr numeric DEFAULT NULL::numeric, p_registry_sumf numeric DEFAULT NULL::numeric, p_registry_downdt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_pmuser_downid bigint DEFAULT NULL::bigint, p_registry_isneedreform bigint DEFAULT NULL::bigint, p_katnasel_id bigint DEFAULT NULL::bigint, p_orgrschet_id bigint DEFAULT NULL::bigint, p_registrystactype_id bigint DEFAULT NULL::bigint, p_registry_recordpaidcount integer DEFAULT NULL::integer, p_registry_kdcount integer DEFAULT NULL::integer, p_registry_kdpaidcount integer DEFAULT NULL::integer, p_registrycheckstatus_id bigint DEFAULT NULL::bigint, p_registry_task character varying DEFAULT NULL::character varying, p_lpubuilding_id bigint DEFAULT NULL::bigint, p_paytype_id bigint DEFAULT NULL::bigint, p_registry_sumpaid numeric DEFAULT NULL::numeric, p_registry_checkstatusdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_checkstatustfomsdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_senddt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_drugfinance_id bigint DEFAULT NULL::bigint, p_whsdocumentcostitemtype_id bigint DEFAULT NULL::bigint, p_org_mid bigint DEFAULT NULL::bigint, p_orgrschet_mid bigint DEFAULT NULL::bigint, p_registry_filenum integer DEFAULT NULL::integer, p_org_id bigint DEFAULT NULL::bigint, p_dispclass_id bigint DEFAULT NULL::bigint, p_registrygrouptype_id bigint DEFAULT NULL::bigint, p_registry_xmlexppatherr character varying DEFAULT NULL::character varying, p_registry_isrepeated bigint DEFAULT NULL::bigint, p_registry_rid bigint DEFAULT NULL::bigint, p_registry_persfincount integer DEFAULT NULL::integer, p_registry_persfinpaycount integer DEFAULT NULL::integer, p_registry_persfinsum numeric DEFAULT NULL::numeric, p_registry_iszno bigint DEFAULT NULL::bigint, p_lpu_cid bigint DEFAULT NULL::bigint, p_registry_isfap bigint DEFAULT NULL::bigint, p_registryqueue_id bigint DEFAULT NULL::bigint, p_pmuser_id bigint DEFAULT NULL::bigint, p_debug bigint DEFAULT (1)::bigint, INOUT p_error_code character varying DEFAULT NULL::character varying, INOUT p_error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
	object_log varchar(50);
	p_Log_id bigint;
  	_registry_type_code	VARCHAR(20)	= (SELECT registrytype_sysnick FROM dbo.registrytype WHERE registrytype_id = p_registrytype_id);
    _pay_type_code		VARCHAR(20) = (SELECT paytype_sysnick FROM dbo.paytype WHERE paytype_id = p_paytype_id); 	
begin
	

  if p_pmuser_id = 0
    then p_pmuser_id := null; end if;

  if coalesce(p_registry_id, 0) = 0
  then 
    insert into r477.registry(registrytype_id, lpu_id, registry_begdate, registry_enddate, orgsmo_id, lpuunitset_id, registry_num, registry_accdate, registrystatus_id, registry_sum, registry_isactive, registry_errorcount, registry_errorcommoncount, registry_recordcount, registry_exportpath, registry_expdt, registry_xmlexportpath, registry_xmlexpdt, registry_sumr, registry_sumf, registry_downdt, pmuser_downid, registry_isneedreform, katnasel_id, orgrschet_id, registrystactype_id, registry_recordpaidcount, registry_kdcount, registry_kdpaidcount, registrycheckstatus_id, registry_task, lpubuilding_id, paytype_id, registry_sumpaid, registry_checkstatusdate, registry_checkstatustfomsdate, registry_senddt, drugfinance_id, whsdocumentcostitemtype_id, org_id, org_mid, orgrschet_mid, registry_filenum, dispclass_id, registrygrouptype_id, registry_xmlexppatherr, registry_isrepeated, registry_rid, registry_persfincount, registry_persfinpaycount, registry_persfinsum, registry_iszno, pmuser_insid, pmuser_updid, registry_insdt, registry_upddt, lpu_cid, registry_isfap)
    values (p_registrytype_id, p_lpu_id, p_registry_begdate, p_registry_enddate, p_orgsmo_id, p_lpuunitset_id, p_registry_num, p_registry_accdate, p_registrystatus_id, p_registry_sum, p_registry_isactive, p_registry_errorcount, p_registry_errorcommoncount, p_registry_recordcount, p_registry_exportpath, p_registry_expdt, p_registry_xmlexportpath, p_registry_xmlexpdt, p_registry_sumr, p_registry_sumf, p_registry_downdt, p_pmuser_downid, p_registry_isneedreform, p_katnasel_id, p_orgrschet_id, p_registrystactype_id, p_registry_recordpaidcount, p_registry_kdcount, p_registry_kdpaidcount, p_registrycheckstatus_id, p_registry_task, p_lpubuilding_id, p_paytype_id, p_registry_sumpaid, p_registry_checkstatusdate, p_registry_checkstatustfomsdate, p_registry_senddt, p_drugfinance_id, p_whsdocumentcostitemtype_id, p_org_id, p_org_mid, p_orgrschet_mid, p_registry_filenum, p_dispclass_id, p_registrygrouptype_id, p_registry_xmlexppatherr, p_registry_isrepeated, p_registry_rid, p_registry_persfincount, p_registry_persfinpaycount, p_registry_persfinsum, p_registry_iszno, p_pmuser_id, p_pmuser_id, now(), now(), p_lpu_cid, p_registry_isfap)
    returning registry.registry_id into p_registry_ins.p_registry_id;
  else
    insert into r477.registry(registry_id, registrytype_id, lpu_id, registry_begdate, registry_enddate, orgsmo_id, lpuunitset_id, registry_num, registry_accdate, registrystatus_id, registry_sum, registry_isactive, registry_errorcount, registry_errorcommoncount, registry_recordcount, registry_exportpath, registry_expdt, registry_xmlexportpath, registry_xmlexpdt, registry_sumr, registry_sumf, registry_downdt, pmuser_downid, registry_isneedreform, katnasel_id, orgrschet_id, registrystactype_id, registry_recordpaidcount, registry_kdcount, registry_kdpaidcount, registrycheckstatus_id, registry_task, lpubuilding_id, paytype_id, registry_sumpaid, registry_checkstatusdate, registry_checkstatustfomsdate, registry_senddt, drugfinance_id, whsdocumentcostitemtype_id, org_id, org_mid, orgrschet_mid, registry_filenum, dispclass_id, registrygrouptype_id, registry_xmlexppatherr, registry_isrepeated, registry_rid, registry_persfincount, registry_persfinpaycount, registry_persfinsum, registry_iszno, pmuser_insid, pmuser_updid, registry_insdt, registry_upddt, lpu_cid, registry_isfap)
    values (p_registry_id, p_registrytype_id, p_lpu_id, p_registry_begdate, p_registry_enddate, p_orgsmo_id, p_lpuunitset_id, p_registry_num, p_registry_accdate, p_registrystatus_id, p_registry_sum, p_registry_isactive, p_registry_errorcount, p_registry_errorcommoncount, p_registry_recordcount, p_registry_exportpath, p_registry_expdt, p_registry_xmlexportpath, p_registry_xmlexpdt, p_registry_sumr, p_registry_sumf, p_registry_downdt, p_pmuser_downid, p_registry_isneedreform, p_katnasel_id, p_orgrschet_id, p_registrystactype_id, p_registry_recordpaidcount, p_registry_kdcount, p_registry_kdpaidcount, p_registrycheckstatus_id, p_registry_task, p_lpubuilding_id, p_paytype_id, p_registry_sumpaid, p_registry_checkstatusdate, p_registry_checkstatustfomsdate, p_registry_senddt, p_drugfinance_id, p_whsdocumentcostitemtype_id, p_org_id, p_org_mid, p_orgrschet_mid, p_registry_filenum, p_dispclass_id, p_registrygrouptype_id, p_registry_xmlexppatherr, p_registry_isrepeated, p_registry_rid, p_registry_persfincount, p_registry_persfinpaycount, p_registry_persfinsum, p_registry_iszno, p_pmuser_id, p_pmuser_id, now(), now(), p_lpu_cid, p_registry_isfap);
  end if;
  

 perform p_Log_set (object_log, 'r477.p_Registry_ins');
 
 --проставляем registry_id в registrylpubuilding 
 update r477.registrylpubuilding rb 
 set 
 	registry_id = p_registry_id 
 where 
 	rb.registryqueue_id = p_registryqueue_id
    and rb.registry_id is distinct from p_registry_id
 ;
  

-- omspol - Поликлиника (на Тамбове общая только в связке с бюджетом regional)
-- omsstac - Стационар (на Тамбове не исп)
-- emergency - Неотложная помощь (на Тамбове не исп)
-- resemdent - Исследования, неотложная помощь, стоматология (на Тамбове не исп)
-- ambulatory_dialysis - Диализы
-- ambulatory - Поликлиника (иногородние)
-- per_capita_own - Поликлиника (подушевое свои)	
-- per_capita_alien - Поликлиника (подушевое чужие)	
-- per_capita_other - Поликлиника (вне подушевого)	
-- parusl - Параклинические услуги
-- stom - Стоматология
-- disp_1 - Диспансеризация и медосмотры	
-- disp_2 - Диспансеризация 2 этап	
-- htm - Высокотехнологичная медицинская помощь (на Тамбове ОМС и бюджет)
-- 0901 - Круглосуточный стационар (узкие специалисты)	
-- 0901_1 - Паллиативная помощь 1 уровня	
-- 0901_2 - Паллиативная помощь 2 уровня
if _pay_type_code = 'regional' and _registry_type_code = 'htm' then 

		call r477.p_registry_evnhtm_generate_bud (p_registry_id);
	
elsif _pay_type_code = 'regional' and _registry_type_code in ('omspol', 'pol_bug_palliativ', 'parakl_budg' ) then 

		call r477.p_registry_evnpl_generate_bud (p_registry_id);	

elsif _pay_type_code = 'regional' and _registry_type_code in ('omsks','0901','omsds', '0901_1','0901_2') then  -- Круглосуточный стационар , Дневной стационар Бюджет

		call r477.p_registry_evnps_generate_bud (p_registry_id);		
	
elsif _registry_type_code in ('ambulatory_dialysis', 'ambulatory', 'per_capita_own', 'per_capita_alien', 'per_capita_other', 'parusl', 'stom', 'mucalc') then	
	
    	call r477.p_registry_evnpl_generate (p_registry_id);
	
elsif _registry_type_code in ('omsks', 'omsds', 'htm') then	--стационар, вмп 

		call r477.p_registry_evnps_generate (p_registry_id);
    	 
elsif _registry_type_code in ('disp_1','disp_2') then --диспансеризация 
--raise notice 'ff';
		call r477.p_registry_evnpldisp_generate (p_registry_id);

end if;
 

EXCEPTION
    when others then p_error_code:=SQLSTATE; p_error_message:=SQLERRM;

END;
$$;


ALTER FUNCTION r477.p_registry_ins(INOUT p_registry_id bigint, p_registrytype_id bigint, p_lpu_id bigint, p_registry_begdate timestamp without time zone, p_registry_enddate timestamp without time zone, p_orgsmo_id bigint, p_lpuunitset_id bigint, p_registry_num character varying, p_registry_accdate timestamp without time zone, p_registrystatus_id bigint, p_registry_sum numeric, p_registry_isactive bigint, p_registry_errorcount integer, p_registry_errorcommoncount integer, p_registry_recordcount integer, p_registry_exportpath character varying, p_registry_expdt timestamp without time zone, p_registry_xmlexportpath character varying, p_registry_xmlexpdt timestamp without time zone, p_registry_sumr numeric, p_registry_sumf numeric, p_registry_downdt timestamp without time zone, p_pmuser_downid bigint, p_registry_isneedreform bigint, p_katnasel_id bigint, p_orgrschet_id bigint, p_registrystactype_id bigint, p_registry_recordpaidcount integer, p_registry_kdcount integer, p_registry_kdpaidcount integer, p_registrycheckstatus_id bigint, p_registry_task character varying, p_lpubuilding_id bigint, p_paytype_id bigint, p_registry_sumpaid numeric, p_registry_checkstatusdate timestamp without time zone, p_registry_checkstatustfomsdate timestamp without time zone, p_registry_senddt timestamp without time zone, p_drugfinance_id bigint, p_whsdocumentcostitemtype_id bigint, p_org_mid bigint, p_orgrschet_mid bigint, p_registry_filenum integer, p_org_id bigint, p_dispclass_id bigint, p_registrygrouptype_id bigint, p_registry_xmlexppatherr character varying, p_registry_isrepeated bigint, p_registry_rid bigint, p_registry_persfincount integer, p_registry_persfinpaycount integer, p_registry_persfinsum numeric, p_registry_iszno bigint, p_lpu_cid bigint, p_registry_isfap bigint, p_registryqueue_id bigint, p_pmuser_id bigint, p_debug bigint, INOUT p_error_code character varying, INOUT p_error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_setpaid(p_registry_id bigint, p_pmuser_id bigint DEFAULT 1, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
object_log varchar(50);
p_Log_id bigint;

_registry_type_code text = r477.p_registry_get_registry_type_code(p_registry_id);

_paid_evn_id_arr bigint[];
_no_paid_evn_id_arr bigint[];

begin
	object_log:= 'Registry/'||RTrim(cast(p_registry_id as varchar(20)));
	perform p_Log_set (object_log, 'p_Registry_setPaid');


    if p_pmUser_id = 0 then 
         p_pmUser_id := null;
    end if;
    

	
	update r477.Registry 
	set 
    	Registry_updDT = current_date ,
		pmUser_updID = p_pmUser_id 
	where 
    	Registry_id=p_Registry_id
    ;
    
    
    --отмечаем оплачено те, для которых нет ошибок ТФОМС 
    update r477.registrydata rd 
    set 
        paid_id = 2 
    where 
        rd.registry_id = p_registry_id 
        and not exists (select 1 from r477.registryerrortfoms ret where ret.registry_id = rd.registry_id and rd.evn_id = ret.evn_id)
        and paid_id is distinct from 2 
    ;
    
    --снимаем признак оплачено, для тех у кого есть ошибки 
    update r477.registrydata rd 
    set 
        paid_id = 1
    where 
        rd.registry_id = p_registry_id 
        and exists (select 1 from r477.registryerrortfoms ret where ret.registry_id = rd.registry_id and rd.evn_id = ret.evn_id)
        and paid_id is distinct from 1 
    ;
    
    
    _paid_evn_id_arr 	= array(select evn_id from r477.registrydata where registry_id = p_registry_id and paid_id = 2)
    ;
    
    _no_paid_evn_id_arr	= array(select evn_id from r477.registrydata where registry_id = p_registry_id and paid_id = 1)
    ; 
    
	
	--Простановка реально оплаченной суммы реестра 
    UPDATE r477.Registry 
    SET 
    	Registry_SumPaid=(SELECT SUM(COALESCE(RegistryData_ItogSum,0)) FROM r477.Registrydata WHERE Registry_id = p_Registry_id and evn_id = any(_paid_evn_id_arr)),
    	Registry_PersFinPayCount =(SELECT SUM(COALESCE(RegistryData_ItogSum,0)) FROM r477.Registrydata WHERE Registry_id = p_Registry_id and evn_id = any(_paid_evn_id_arr) and (RegistryData_isPersFin=2))
    WHERE 
    	Registry_id = p_Registry_id
    ;
	
        
	
 if _registry_type_code in ('omsstac','htm') then    
    
	--снимаем признак вхождения в реестр у оплаченных случаев
    update EvnSection
    set
		EvnSection_IsInReg = 1, 
        EvnSection_IsPaid = 1
    where 
    	evn_id = any(_no_paid_evn_id_arr) 
        and (EvnSection_IsInReg is distinct from 1 or EvnSection_IsPaid is distinct from 1)
    ;
    
    --проставляем признак вхождения в реестр у оплаченных случаев
	update EvnSection  
    set
		EvnSection_IsInReg = 2, 
        EvnSection_IsPaid = 2
    where 
    	evn_id = any(_paid_evn_id_arr) 
        and (EvnSection_IsInReg is distinct from 2 or EvnSection_IsPaid is distinct from 2)
    ;
           
elsif _registry_type_code in ('omspol','emergency','resemdent') then    
	
	--снимаем признак вхождения в реестр у оплаченных случаев
    update only EvnVizitPL  
    set
		EvnVizit_IsInReg = 1, 
        EvnVizit_IsPaid = 1
    where 
    	evn_id = any(_no_paid_evn_id_arr)
        and (EvnVizit_IsInReg is distinct from 1 or EvnVizit_IsPaid is distinct from 1)
    ;
    
    update only EvnVizitPLStom  
    set
		EvnVizit_IsInReg = 1, 
        EvnVizit_IsPaid = 1
    where 
    	evn_id = any(_no_paid_evn_id_arr)
        and (EvnVizit_IsInReg is distinct from 1 or EvnVizit_IsPaid is distinct from 1)
    ;
    
    
    --проставляем признак вхождения в реестр у оплаченных случаев
    update only EvnVizitPL  
    set
		EvnVizit_IsInReg = 2, 
        EvnVizit_IsPaid = 2
    where 
    	evn_id = any(_paid_evn_id_arr)
        and (EvnVizit_IsInReg is distinct from 2 or EvnVizit_IsPaid is distinct from 2)
    ;
       
    update only EvnVizitPLStom  
    set
		EvnVizit_IsInReg = 2, 
        EvnVizit_IsPaid = 2
    where 
    	evn_id = any(_paid_evn_id_arr)
        and (EvnVizit_IsInReg is distinct from 2 or EvnVizit_IsPaid is distinct from 2)
    ;
    
    
    if _registry_type_code = 'resemdent' then 
    
    	--снимаем признак вхождения в реестр у оплаченных случаев
        update EvnUslugaPar 
        set
            EvnUsluga_IsInReg = 1,
            EvnUsluga_IsPaid=1
        where 
            evn_id = any(_no_paid_evn_id_arr) 
            and (EvnUsluga_IsInReg is distinct from 1 or EvnUsluga_IsPaid is distinct from 1)
        ;
        
        --проставляем признак вхождения в реестр у оплаченных случаев
        update EvnUslugaPar 
        set
            EvnUsluga_IsInReg = 2,
            EvnUsluga_IsPaid=2
        where 
            evn_id = any(_paid_evn_id_arr) 
            and (EvnUsluga_IsInReg is distinct from 2 or EvnUsluga_IsPaid is distinct from 2)
        ;
        
    end if;
    
elsif _registry_type_code = 'medexam' then  
   	
	--снимаем признак вхождения в реестр у оплаченных случаев
    update EvnPLDispDop13 
    set
        EvnPLDisp_IsInReg = 1,
        EvnPLDisp_IsPaid = 1
    where 
        evn_id = any(_no_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 1 or EvnPLDisp_IsPaid is distinct from 1)
    ;
    
    update EvnPLDispTeenInspection 
    set
        EvnPLDisp_IsInReg = 1,
        EvnPLDisp_IsPaid = 1
    where 
        evn_id = any(_no_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 1 or EvnPLDisp_IsPaid is distinct from 1)
    ;
    
    update EvnPLDispProf 
    set
        EvnPLDisp_IsInReg = 1,
        EvnPLDisp_IsPaid = 1
    where 
        evn_id = any(_no_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 1 or EvnPLDisp_IsPaid is distinct from 1)
    ;
    
    update EvnPLDispOrp 
    set
        EvnPLDisp_IsInReg = 1,
        EvnPLDisp_IsPaid = 1
    where 
        evn_id = any(_no_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 1 or EvnPLDisp_IsPaid is distinct from 1)
    ;
    
    
    -- проставляем признак вхождения в реестр у оплаченных случаев, если не было
    update EvnPLDispDop13 
    set
        EvnPLDisp_IsInReg = 2,
        EvnPLDisp_IsPaid = 2
    where 
        evn_id = any(_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 2 or EvnPLDisp_IsPaid is distinct from 2)
    ;
    
    update EvnPLDispTeenInspection 
    set
        EvnPLDisp_IsInReg = 2,
        EvnPLDisp_IsPaid = 2
    where 
        evn_id = any(_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 2 or EvnPLDisp_IsPaid is distinct from 2)
    ;
    
    update EvnPLDispProf 
    set
        EvnPLDisp_IsInReg = 2,
        EvnPLDisp_IsPaid = 2
    where 
        evn_id = any(_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 2 or EvnPLDisp_IsPaid is distinct from 2)
    ;
    
    update EvnPLDispOrp 
    set
        EvnPLDisp_IsInReg = 2,
        EvnPLDisp_IsPaid = 2
    where 
        evn_id = any(_paid_evn_id_arr) 
        and (EvnPLDisp_IsInReg is distinct from 2 or EvnPLDisp_IsPaid is distinct from 2)
    ;
	
end if;

perform p_Log_set (object_log, 'p_Registry_setPaid_end');

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

end;
$$;


ALTER FUNCTION r477.p_registry_setpaid(p_registry_id bigint, p_pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_setunpaid(p_registry_id bigint, p_pmuser_id bigint DEFAULT 1, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
object_log varchar(50);
p_Log_id bigint;
_registry_type_code text = r477.p_registry_get_registry_type_code(p_registry_id);

_evn_id_arr bigint[];

begin
	object_log:= 'Registry/'||RTrim(cast(p_registry_id as varchar(20)));
	perform p_Log_set (object_log, 'p_Registry_setUnPaid');


    if p_pmUser_id = 0 then 
         p_pmUser_id = null;
    end if;
    
   update r477.Registry 
    set 
    	Registry_updDT = now(),
        pmUser_updID = p_pmUser_id,
        RegistryStatus_id = 2,
        Registry_SumPaid = null
    where 
    	Registry_id = p_Registry_id
    ;

	update r477.RegistryData set Paid_id = 1 where Registry_id = p_Registry_id and paid_id is distinct from 1 
    ;
    
    _evn_id_arr = array(select evn_id from r477.registrydata where registry_id = p_registry_id)
    ;

    if _registry_type_code in ('omsstac','htm') then 
    
        update EvnSection  
        set
            EvnSection_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnSection_IsPaid is distinct from 1 
        ;
        
    elsif _registry_type_code in ('omspol','emergency','resemdent') then 
    
        update only EvnVizitPL  
        set
            EvnVizit_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnVizit_IsPaid is distinct from 1
        ;
        
        update only EvnVizitPLStom  
        set
            EvnVizit_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnVizit_IsPaid is distinct from 1
        ;
        
        if _registry_type_code = 'resemdent' then 
    
            update dbo.EvnUslugaPar  
            set
                EvnUsluga_IsPaid = 1
            where 
            	evn_id = any(_evn_id_arr) and EvnUsluga_IsPaid is distinct from 1 
            ;
            
      end if;
        
    elsif _registry_type_code = 'medexam' then 

        update EvnPLDispDop13  
        set
            EvnPLDisp_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnPLDisp_IsPaid is distinct from 1
        ;
        
        update EvnPLDispTeenInspection  
        set
            EvnPLDisp_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnPLDisp_IsPaid is distinct from 1
        ;
        
        update EvnPLDispProf  
        set
            EvnPLDisp_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnPLDisp_IsPaid is distinct from 1
        ;
        
        update EvnPLDispOrp  
        set
            EvnPLDisp_IsPaid = 1
        where 
        	evn_id = any(_evn_id_arr) and EvnPLDisp_IsPaid is distinct from 1
        ;
        
    end if;
    
    
	
    perform p_Log_set (object_log, 'p_Registry_setUnPaid_end');


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

end;
$$;


ALTER FUNCTION r477.p_registry_setunpaid(p_registry_id bigint, p_pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registry_upd(INOUT p_registry_id bigint DEFAULT NULL::bigint, p_registrytype_id bigint DEFAULT NULL::bigint, p_lpu_id bigint DEFAULT NULL::bigint, p_registry_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_orgsmo_id bigint DEFAULT NULL::bigint, p_lpuunitset_id bigint DEFAULT NULL::bigint, p_registry_num character varying DEFAULT NULL::character varying, p_registry_accdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registrystatus_id bigint DEFAULT NULL::bigint, p_registry_sum numeric DEFAULT NULL::numeric, p_registry_isactive bigint DEFAULT NULL::bigint, p_registry_errorcount integer DEFAULT NULL::integer, p_registry_errorcommoncount integer DEFAULT NULL::integer, p_registry_recordcount integer DEFAULT NULL::integer, p_registry_exportpath character varying DEFAULT NULL::character varying, p_registry_expdt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_sumr numeric DEFAULT NULL::numeric, p_registry_sumf numeric DEFAULT NULL::numeric, p_registry_downdt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_pmuser_downid bigint DEFAULT NULL::bigint, p_registry_isneedreform bigint DEFAULT NULL::bigint, p_katnasel_id bigint DEFAULT NULL::bigint, p_orgrschet_id bigint DEFAULT NULL::bigint, p_registrystactype_id bigint DEFAULT NULL::bigint, p_registry_recordpaidcount integer DEFAULT NULL::integer, p_registry_kdcount integer DEFAULT NULL::integer, p_registry_kdpaidcount integer DEFAULT NULL::integer, p_registrycheckstatus_id bigint DEFAULT NULL::bigint, p_registry_task character varying DEFAULT NULL::character varying, p_lpubuilding_id bigint DEFAULT NULL::bigint, p_paytype_id bigint DEFAULT NULL::bigint, p_registry_sumpaid numeric DEFAULT NULL::numeric, p_registry_checkstatusdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_checkstatustfomsdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_senddt timestamp without time zone DEFAULT NULL::timestamp without time zone, p_drugfinance_id bigint DEFAULT NULL::bigint, p_whsdocumentcostitemtype_id bigint DEFAULT NULL::bigint, p_org_mid bigint DEFAULT NULL::bigint, p_orgrschet_mid bigint DEFAULT NULL::bigint, p_org_id bigint DEFAULT NULL::bigint, p_registry_filenum integer DEFAULT NULL::integer, p_dispclass_id bigint DEFAULT NULL::bigint, p_registrygrouptype_id bigint DEFAULT NULL::bigint, p_registry_xmlexppatherr character varying DEFAULT NULL::character varying, p_registry_isrepeated bigint DEFAULT NULL::bigint, p_registry_rid bigint DEFAULT NULL::bigint, p_registry_persfincount integer DEFAULT NULL::integer, p_registry_persfinpaycount integer DEFAULT NULL::integer, p_registry_persfinsum numeric DEFAULT NULL::numeric, p_registry_iszno bigint DEFAULT NULL::bigint, p_lpu_cid bigint DEFAULT NULL::bigint, p_registry_isfap bigint DEFAULT NULL::bigint, p_pmuser_id bigint DEFAULT NULL::bigint, p_debug bigint DEFAULT (1)::bigint, INOUT p_error_code character varying DEFAULT NULL::character varying, INOUT p_error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare 
	_registry_type_code	VARCHAR(20)	= (SELECT registrytype_sysnick FROM dbo.registrytype WHERE registrytype_id = p_registrytype_id);
    _pay_type_code		VARCHAR(20) = (SELECT paytype_sysnick FROM dbo.paytype WHERE paytype_id = p_paytype_id); 	
begin

--project ProMed
--update r477.registry
if p_pmuser_id = 0 then p_pmuser_id := null; end if;

update r477.registry
set 
	registrytype_id = p_registry_upd.p_registrytype_id,
    lpu_id = p_registry_upd.p_lpu_id,
    registry_begdate = p_registry_upd.p_registry_begdate,
    registry_enddate = p_registry_upd.p_registry_enddate,
    orgsmo_id = p_registry_upd.p_orgsmo_id,
    lpuunitset_id = p_registry_upd.p_lpuunitset_id,
    registry_num = p_registry_upd.p_registry_num,
    registry_accdate = p_registry_upd.p_registry_accdate,
    registrystatus_id = p_registry_upd.p_registrystatus_id,
    registry_sum = p_registry_upd.p_registry_sum,
    registry_isactive = p_registry_upd.p_registry_isactive,
    registry_errorcount = p_registry_upd.p_registry_errorcount,
    registry_errorcommoncount = p_registry_upd.p_registry_errorcommoncount,
    registry_recordcount = p_registry_upd.p_registry_recordcount,
    registry_exportpath = p_registry_upd.p_registry_exportpath,
    registry_expdt = p_registry_upd.p_registry_expdt,
    registry_xmlexportpath = null,
    registry_xmlexpdt = null,
    registry_sumr = p_registry_upd.p_registry_sumr,
    registry_sumf = p_registry_upd.p_registry_sumf,
    registry_downdt = p_registry_upd.p_registry_downdt,
    pmuser_downid = p_registry_upd.p_pmuser_downid,
    registry_isneedreform = p_registry_upd.p_registry_isneedreform,
    katnasel_id = p_registry_upd.p_katnasel_id,
    orgrschet_id = p_registry_upd.p_orgrschet_id,
    registrystactype_id = p_registry_upd.p_registrystactype_id,
    registry_recordpaidcount = p_registry_upd.p_registry_recordpaidcount,
    registry_kdcount = p_registry_upd.p_registry_kdcount,
    registry_kdpaidcount = p_registry_upd.p_registry_kdpaidcount,
    registrycheckstatus_id = p_registry_upd.p_registrycheckstatus_id,
    registry_task = p_registry_upd.p_registry_task,
    lpubuilding_id = p_registry_upd.p_lpubuilding_id,
    paytype_id = p_registry_upd.p_paytype_id,
    registry_sumpaid = p_registry_upd.p_registry_sumpaid,
    registry_checkstatusdate = p_registry_upd.p_registry_checkstatusdate,
    registry_checkstatustfomsdate = p_registry_upd.p_registry_checkstatustfomsdate,
    registry_senddt = p_registry_upd.p_registry_senddt,
    drugfinance_id = p_registry_upd.p_drugfinance_id,
    whsdocumentcostitemtype_id = p_registry_upd.p_whsdocumentcostitemtype_id,
    org_id = p_registry_upd.p_org_id,
    org_mid = p_registry_upd.p_org_mid,
    orgrschet_mid = p_registry_upd.p_orgrschet_mid,
    registry_filenum = p_registry_upd.p_registry_filenum,
    dispclass_id = p_registry_upd.p_dispclass_id,
    registrygrouptype_id = p_registry_upd.p_registrygrouptype_id,
    registry_xmlexppatherr = p_registry_upd.p_registry_xmlexppatherr,
    registry_isrepeated = p_registry_upd.p_registry_isrepeated,
    registry_rid = p_registry_upd.p_registry_rid,
    registry_persfincount = p_registry_upd.p_registry_persfincount,
    registry_persfinpaycount = p_registry_upd.p_registry_persfinpaycount,
    registry_persfinsum = p_registry_upd.p_registry_persfinsum,
    registry_iszno = p_registry_upd.p_registry_iszno,
    pmuser_updid = p_pmuser_id,
    registry_upddt = now(),
    lpu_cid = p_lpu_cid,
    registry_isfap = p_registry_isfap
where 
	registry.registry_id = p_registry_upd.p_registry_id
;

-- omspol - Поликлиника (на Тамбове общая только в связке с бюджетом regional)
-- omsstac - Стационар (на Тамбове не исп)
-- emergency - Неотложная помощь (на Тамбове не исп)
-- resemdent - Исследования, неотложная помощь, стоматология (на Тамбове не исп)
-- ambulatory_dialysis - Диализы
-- ambulatory - Поликлиника (иногородние)
-- per_capita_own - Поликлиника (подушевое свои)	
-- per_capita_alien - Поликлиника (подушевое чужие)	
-- per_capita_other - Поликлиника (вне подушевого)	
-- parusl - Параклинические услуги
-- stom - Стоматология
-- disp_1 - Диспансеризация и медосмотры	
-- disp_2 - Диспансеризация 2 этап	
-- htm - Высокотехнологичная медицинская помощь (на Тамбове ОМС и бюджет)
-- 0901 - Круглосуточный стационар (узкие специалисты)	
-- 0901_1 - Паллиативная помощь 1 уровня	
-- 0901_2 - Паллиативная помощь 2 уровня	
if _pay_type_code ='regional' and _registry_type_code = 'htm' then --ВМП.бюджет

		call r477.p_registry_evnhtm_generate_bud (p_registry_id);
		
elsif _pay_type_code = 'regional' and _registry_type_code in ('omspol', 'pol_bug_palliativ', 'parakl_budg' ) then 

		call r477.p_registry_evnpl_generate_bud (p_registry_id);			
	
elsif _pay_type_code = 'regional' and _registry_type_code in ('omsks','0901','omsds', '0901_1','0901_2') then  -- Круглосуточный стационар , Дневной стационар Бюджет

		call r477.p_registry_evnps_generate_bud (p_registry_id);		

elsif _registry_type_code in ('ambulatory_dialysis', 'ambulatory', 'per_capita_own', 'per_capita_alien', 'per_capita_other', 'parusl', 'stom', 'mucalc') then	
	
    	call r477.p_registry_evnpl_generate (p_registry_id);
	    
elsif _registry_type_code in ('omsks', 'omsds', 'htm') then --стационар,вмп

		call r477.p_registry_evnps_generate (p_registry_id);
    
elsif _registry_type_code in ('disp_1','disp_2') then --диспансеризация 

		call r477.p_registry_evnpldisp_generate (p_registry_id);

end if;



EXCEPTION
	when others then p_error_code:=SQLSTATE; p_error_message:=SQLERRM;

END;
$$;


ALTER FUNCTION r477.p_registry_upd(INOUT p_registry_id bigint, p_registrytype_id bigint, p_lpu_id bigint, p_registry_begdate timestamp without time zone, p_registry_enddate timestamp without time zone, p_orgsmo_id bigint, p_lpuunitset_id bigint, p_registry_num character varying, p_registry_accdate timestamp without time zone, p_registrystatus_id bigint, p_registry_sum numeric, p_registry_isactive bigint, p_registry_errorcount integer, p_registry_errorcommoncount integer, p_registry_recordcount integer, p_registry_exportpath character varying, p_registry_expdt timestamp without time zone, p_registry_sumr numeric, p_registry_sumf numeric, p_registry_downdt timestamp without time zone, p_pmuser_downid bigint, p_registry_isneedreform bigint, p_katnasel_id bigint, p_orgrschet_id bigint, p_registrystactype_id bigint, p_registry_recordpaidcount integer, p_registry_kdcount integer, p_registry_kdpaidcount integer, p_registrycheckstatus_id bigint, p_registry_task character varying, p_lpubuilding_id bigint, p_paytype_id bigint, p_registry_sumpaid numeric, p_registry_checkstatusdate timestamp without time zone, p_registry_checkstatustfomsdate timestamp without time zone, p_registry_senddt timestamp without time zone, p_drugfinance_id bigint, p_whsdocumentcostitemtype_id bigint, p_org_mid bigint, p_orgrschet_mid bigint, p_org_id bigint, p_registry_filenum integer, p_dispclass_id bigint, p_registrygrouptype_id bigint, p_registry_xmlexppatherr character varying, p_registry_isrepeated bigint, p_registry_rid bigint, p_registry_persfincount integer, p_registry_persfinpaycount integer, p_registry_persfinsum numeric, p_registry_iszno bigint, p_lpu_cid bigint, p_registry_isfap bigint, p_pmuser_id bigint, p_debug bigint, INOUT p_error_code character varying, INOUT p_error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registrycmpnopolis
delete from r477.registrycmpnopolis
where registrycmpnopolis.registry_id = p_registrycmpnopolis_del.registry_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registrycmpnopolis_ins(INOUT registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, evn_code character varying DEFAULT NULL::character varying, person_surname character varying DEFAULT NULL::character varying, person_firname character varying DEFAULT NULL::character varying, person_secname character varying DEFAULT NULL::character varying, person_birthday timestamp without time zone DEFAULT NULL::timestamp without time zone, registrynopolis_insdt timestamp without time zone DEFAULT NULL::timestamp without time zone, registrynopolis_upddt timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registry_id, 0) = 0
then 
	insert into r477.registrycmpnopolis(evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, registrynopolis_insdt, registrynopolis_upddt, pmuser_insid, pmuser_updid)
	values ( evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, registrynopolis_insdt, registrynopolis_upddt, pmuser_id, pmuser_id)
	returning registrycmpnopolis.registry_id into p_registrycmpnopolis_ins.registry_id;
else
	insert into r477.registrycmpnopolis(registry_id, evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, registrynopolis_insdt, registrynopolis_upddt, pmuser_insid, pmuser_updid)
	values (registry_id, evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, registrynopolis_insdt, registrynopolis_upddt, pmuser_id, pmuser_id);
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrycmpnopolis_ins(INOUT registry_id bigint, evn_id bigint, person_id bigint, evn_code character varying, person_surname character varying, person_firname character varying, person_secname character varying, person_birthday timestamp without time zone, registrynopolis_insdt timestamp without time zone, registrynopolis_upddt timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrycmpnopolis_upd(INOUT registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, evn_code character varying DEFAULT NULL::character varying, person_surname character varying DEFAULT NULL::character varying, person_firname character varying DEFAULT NULL::character varying, person_secname character varying DEFAULT NULL::character varying, person_birthday timestamp without time zone DEFAULT NULL::timestamp without time zone, registrynopolis_insdt timestamp without time zone DEFAULT NULL::timestamp without time zone, registrynopolis_upddt timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrycmpnopolis
set evn_id = p_registrycmpnopolis_upd.evn_id,
person_id = p_registrycmpnopolis_upd.person_id,
evn_code = p_registrycmpnopolis_upd.evn_code,
person_surname = p_registrycmpnopolis_upd.person_surname,
person_firname = p_registrycmpnopolis_upd.person_firname,
person_secname = p_registrycmpnopolis_upd.person_secname,
person_birthday = p_registrycmpnopolis_upd.person_birthday,
registrynopolis_insdt = p_registrycmpnopolis_upd.registrynopolis_insdt,
registrynopolis_upddt = p_registrycmpnopolis_upd.registrynopolis_upddt,
pmuser_updid = pmuser_id
where registrycmpnopolis.registry_id = p_registrycmpnopolis_upd.registry_id;

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


END; $$;


ALTER FUNCTION r477.p_registrycmpnopolis_upd(INOUT registry_id bigint, evn_id bigint, person_id bigint, evn_code character varying, person_surname character varying, person_firname character varying, person_secname character varying, person_birthday timestamp without time zone, registrynopolis_insdt timestamp without time zone, registrynopolis_upddt timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrydata_del(p_evn_id bigint, p_registry_id bigint, p_pmuser_id bigint, p_isremove bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
	_evn_class_sysnick text; 
begin

--autogen
--project promed
--delete from r477.registrydata
if p_isremove = 2 then

	delete from r477.registrydata where evn_id = p_evn_id and registry_id = p_registry_id
    ;
    
    _evn_class_sysnick = (select evnclass_sysnick from v_evn where evn_id = p_evn_id)
    ;
    
    --снимаем отметку нахождения в реестре 
    if _evn_class_sysnick = 'EvnSection' then 
    
    	update EvnSection set evnsection_isinreg = 1 where evn_id = p_evn_id
        ;
        
    elsif  _evn_class_sysnick ~ '^EvnVizit' then 
    
    	update EvnVizit set evnvizit_isinreg = 1 where evn_id = p_evn_id
        ;
        
    elsif  _evn_class_sysnick ~ '^EvnPLDisp' then 
    
    	update EvnPLDisp set evnpldisp_isinreg = 1 where evn_id = p_evn_id
        ; 
        
    elseif _evn_class_sysnick ~ '^EvnUsluga' then 
    	
    	update EvnUsluga set evnusluga_isinreg = 1 where evn_id = p_evn_id
        ;
    
    end if;
    
else

	update r477.registrydata rd
	set 
		pmuser_delid = p_pmuser_id,
		registrydata_deldt = now(),
		registrydata_deleted = case when registrydata_deleted = 2 then 1 else 2 end 
	where 
    	evn_id = p_evn_id and registry_id = p_registry_id 
    ;
	
end if;

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


end;
$$;


ALTER FUNCTION r477.p_registrydata_del(p_evn_id bigint, p_registry_id bigint, p_pmuser_id bigint, p_isremove bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_registrydata_ins(bigint, bigint, character varying, bigint, bigint, bigint, bigint, bigint, bigint, double precision, double precision, double precision, double precision, double precision, double precision, double precision, bigint, bigint, bigint, bigint, bigint, bigint, bigint, double precision, double precision, character varying, character varying, integer, timestamp without time zone, character varying, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, bigint, timestamp without time zone, bigint, uuid, bigint, bigint, bigint, double precision, double precision, double precision, double precision, integer, bigint, bigint, bigint, timestamp without time zone, bigint, integer, bigint, bigint, bigint, numeric, bigint, bigint, numeric, numeric, bigint, bigint, bigint, bigint, bigint, integer, character varying, bigint, numeric, numeric, integer, bigint, bigint, bigint, character varying, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registrydata_ins(INOUT evn_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, numcard character varying DEFAULT NULL::character varying, number bigint DEFAULT NULL::bigint, evn_rid bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, lpusectionprofile_id bigint DEFAULT NULL::bigint, medpersonal_id bigint DEFAULT NULL::bigint, registrydata_tariff double precision DEFAULT NULL::double precision, registrydata_kdfact double precision DEFAULT NULL::double precision, registrydata_kdplan double precision DEFAULT NULL::double precision, registrydata_kdpay double precision DEFAULT NULL::double precision, registrydata_ukl double precision DEFAULT NULL::double precision, registrydata_uklsum double precision DEFAULT NULL::double precision, registrydata_itogsum double precision DEFAULT NULL::double precision, omssprterr_id bigint DEFAULT NULL::bigint, address_id bigint DEFAULT NULL::bigint, registrydata_isprev bigint DEFAULT NULL::bigint, registrydata_isambul bigint DEFAULT NULL::bigint, vizittype_id bigint DEFAULT NULL::bigint, resultclass_id bigint DEFAULT NULL::bigint, diag_id bigint DEFAULT NULL::bigint, registrydata_ei2 double precision DEFAULT NULL::double precision, registrydata_g162 double precision DEFAULT NULL::double precision, medpersonal_fio character varying DEFAULT NULL::character varying, medpersonal_snils character varying DEFAULT NULL::character varying, omssprterr_code integer DEFAULT NULL::integer, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, lpusection_code character varying DEFAULT NULL::character varying, lpusectionprofile_code character varying DEFAULT NULL::character varying, medpersonal_code character varying DEFAULT NULL::character varying, polis_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgsmo_id bigint DEFAULT NULL::bigint, medspec_id bigint DEFAULT NULL::bigint, evn_upddate timestamp without time zone DEFAULT NULL::timestamp without time zone, dopdispspec_id bigint DEFAULT NULL::bigint, guid uuid DEFAULT NULL::uuid, usluga_id bigint DEFAULT NULL::bigint, paid_id bigint DEFAULT NULL::bigint, maxevn_id bigint DEFAULT NULL::bigint, registrydata_tarif_r double precision DEFAULT NULL::double precision, registrydata_tarif_f double precision DEFAULT NULL::double precision, registrydata_sum_r double precision DEFAULT NULL::double precision, registrydata_sum_f double precision DEFAULT NULL::double precision, registrydata_rownum integer DEFAULT NULL::integer, leavetype_id bigint DEFAULT NULL::bigint, resultdesease_id bigint DEFAULT NULL::bigint, leavecause_id bigint DEFAULT NULL::bigint, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, evnsection_isadultescort bigint DEFAULT NULL::bigint, registrydata_double integer DEFAULT NULL::integer, uslugacomplex_id bigint DEFAULT NULL::bigint, mestariff_id bigint DEFAULT NULL::bigint, mesitog_id bigint DEFAULT NULL::bigint, mestariff_value numeric DEFAULT NULL::numeric, evnsection_numgroup bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, mesitog_value numeric DEFAULT NULL::numeric, registrydata_coeffctp numeric DEFAULT NULL::numeric, paymedtype_id bigint DEFAULT NULL::bigint, registrydata_ispaid bigint DEFAULT NULL::bigint, server_id bigint DEFAULT NULL::bigint, personevn_id bigint DEFAULT NULL::bigint, registrydata_ispersfin bigint DEFAULT NULL::bigint, registrydata_period integer DEFAULT NULL::integer, socstatus_code character varying DEFAULT NULL::character varying, mesolduslugacomplex_id bigint DEFAULT NULL::bigint, koef_up numeric DEFAULT NULL::numeric, koef_u numeric DEFAULT NULL::numeric, registrydata_prer integer DEFAULT NULL::integer, evnmax_id bigint DEFAULT NULL::bigint, registrydata_iszno bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(evn_id, 0) = 0
then 
	insert into r477.registrydata(registry_id, numcard, number, evn_rid, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydata_tariff, registrydata_kdfact, registrydata_kdplan, registrydata_kdpay, registrydata_ukl, registrydata_uklsum, registrydata_itogsum, omssprterr_id, address_id, registrydata_isprev, registrydata_isambul, vizittype_id, resultclass_id, diag_id, registrydata_ei2, registrydata_g162, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, evn_upddate, dopdispspec_id, guid, usluga_id, paid_id, maxevn_id, registrydata_tarif_r, registrydata_tarif_f, registrydata_sum_r, registrydata_sum_f, registrydata_rownum, leavetype_id, resultdesease_id, leavecause_id, evn_setdate, evnsection_isadultescort, registrydata_double, uslugacomplex_id, mestariff_id, mesitog_id, mestariff_value, evnsection_numgroup, lpuunittype_id, mesitog_value, registrydata_coeffctp, paymedtype_id, registrydata_ispaid, server_id, personevn_id, registrydata_ispersfin, registrydata_period, socstatus_code, mesolduslugacomplex_id, koef_up, koef_u, registrydata_prer, evnmax_id, registrydata_iszno, pmuser_insid, pmuser_updid, registrydata_insdt, registrydata_upddt)
	values ( registry_id, numcard, number, evn_rid, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydata_tariff, registrydata_kdfact, registrydata_kdplan, registrydata_kdpay, registrydata_ukl, registrydata_uklsum, registrydata_itogsum, omssprterr_id, address_id, registrydata_isprev, registrydata_isambul, vizittype_id, resultclass_id, diag_id, registrydata_ei2, registrydata_g162, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, evn_upddate, dopdispspec_id, guid, usluga_id, paid_id, maxevn_id, registrydata_tarif_r, registrydata_tarif_f, registrydata_sum_r, registrydata_sum_f, registrydata_rownum, leavetype_id, resultdesease_id, leavecause_id, evn_setdate, evnsection_isadultescort, registrydata_double, uslugacomplex_id, mestariff_id, mesitog_id, mestariff_value, evnsection_numgroup, lpuunittype_id, mesitog_value, registrydata_coeffctp, paymedtype_id, registrydata_ispaid, server_id, personevn_id, registrydata_ispersfin, registrydata_period, socstatus_code, mesolduslugacomplex_id, koef_up, koef_u, registrydata_prer, evnmax_id, registrydata_iszno, pmuser_id, pmuser_id, now(), now())
	returning registrydata.evn_id into p_registrydata_ins.evn_id;
else
	insert into r477.registrydata(evn_id, registry_id, numcard, number, evn_rid, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydata_tariff, registrydata_kdfact, registrydata_kdplan, registrydata_kdpay, registrydata_ukl, registrydata_uklsum, registrydata_itogsum, omssprterr_id, address_id, registrydata_isprev, registrydata_isambul, vizittype_id, resultclass_id, diag_id, registrydata_ei2, registrydata_g162, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, evn_upddate, dopdispspec_id, guid, usluga_id, paid_id, maxevn_id, registrydata_tarif_r, registrydata_tarif_f, registrydata_sum_r, registrydata_sum_f, registrydata_rownum, leavetype_id, resultdesease_id, leavecause_id, evn_setdate, evnsection_isadultescort, registrydata_double, uslugacomplex_id, mestariff_id, mesitog_id, mestariff_value, evnsection_numgroup, lpuunittype_id, mesitog_value, registrydata_coeffctp, paymedtype_id, registrydata_ispaid, server_id, personevn_id, registrydata_ispersfin, registrydata_period, socstatus_code, mesolduslugacomplex_id, koef_up, koef_u, registrydata_prer, evnmax_id, registrydata_iszno, pmuser_insid, pmuser_updid, registrydata_insdt, registrydata_upddt)
	values (evn_id, registry_id, numcard, number, evn_rid, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydata_tariff, registrydata_kdfact, registrydata_kdplan, registrydata_kdpay, registrydata_ukl, registrydata_uklsum, registrydata_itogsum, omssprterr_id, address_id, registrydata_isprev, registrydata_isambul, vizittype_id, resultclass_id, diag_id, registrydata_ei2, registrydata_g162, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, evn_upddate, dopdispspec_id, guid, usluga_id, paid_id, maxevn_id, registrydata_tarif_r, registrydata_tarif_f, registrydata_sum_r, registrydata_sum_f, registrydata_rownum, leavetype_id, resultdesease_id, leavecause_id, evn_setdate, evnsection_isadultescort, registrydata_double, uslugacomplex_id, mestariff_id, mesitog_id, mestariff_value, evnsection_numgroup, lpuunittype_id, mesitog_value, registrydata_coeffctp, paymedtype_id, registrydata_ispaid, server_id, personevn_id, registrydata_ispersfin, registrydata_period, socstatus_code, mesolduslugacomplex_id, koef_up, koef_u, registrydata_prer, evnmax_id, registrydata_iszno, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrydata_ins(INOUT evn_id bigint, registry_id bigint, numcard character varying, number bigint, evn_rid bigint, person_id bigint, lpusection_id bigint, lpusectionprofile_id bigint, medpersonal_id bigint, registrydata_tariff double precision, registrydata_kdfact double precision, registrydata_kdplan double precision, registrydata_kdpay double precision, registrydata_ukl double precision, registrydata_uklsum double precision, registrydata_itogsum double precision, omssprterr_id bigint, address_id bigint, registrydata_isprev bigint, registrydata_isambul bigint, vizittype_id bigint, resultclass_id bigint, diag_id bigint, registrydata_ei2 double precision, registrydata_g162 double precision, medpersonal_fio character varying, medpersonal_snils character varying, omssprterr_code integer, evn_disdate timestamp without time zone, lpusection_code character varying, lpusectionprofile_code character varying, medpersonal_code character varying, polis_begdate timestamp without time zone, polis_enddate timestamp without time zone, orgsmo_id bigint, medspec_id bigint, evn_upddate timestamp without time zone, dopdispspec_id bigint, guid uuid, usluga_id bigint, paid_id bigint, maxevn_id bigint, registrydata_tarif_r double precision, registrydata_tarif_f double precision, registrydata_sum_r double precision, registrydata_sum_f double precision, registrydata_rownum integer, leavetype_id bigint, resultdesease_id bigint, leavecause_id bigint, evn_setdate timestamp without time zone, evnsection_isadultescort bigint, registrydata_double integer, uslugacomplex_id bigint, mestariff_id bigint, mesitog_id bigint, mestariff_value numeric, evnsection_numgroup bigint, lpuunittype_id bigint, mesitog_value numeric, registrydata_coeffctp numeric, paymedtype_id bigint, registrydata_ispaid bigint, server_id bigint, personevn_id bigint, registrydata_ispersfin bigint, registrydata_period integer, socstatus_code character varying, mesolduslugacomplex_id bigint, koef_up numeric, koef_u numeric, registrydata_prer integer, evnmax_id bigint, registrydata_iszno bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrydata_refresh(INOUT p_registry_id bigint DEFAULT NULL::bigint, p_pmuser_id bigint DEFAULT 1, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
Declare 
p_object_log varchar(50);
p_Log_id bigint;
p_log_msg varchar(150);

_registry_type_code text = r477.p_registry_get_registry_type_code(p_registry_id);
_evn_id_arr 		bigint[];
 _pay_type_code		VARCHAR(20) = (SELECT paytype.paytype_sysnick FROM dbo.paytype join r477.v_registry r on r.paytype_id =paytype.paytype_id WHERE r.registry_id = p_registry_id); 	
begin 

	
p_object_log := 'Registry/'||RTrim(cast(p_registry_id as varchar(20)));
perform dbo.p_log_set(p_object_log, 'запуск r477.p_RegistryData_Refresh', null ) ;

p_log_msg := 'Пользователь: '::char(14)||cast(p_pmUser_id as char(15));

perform dbo.p_Log_set (p_object_log, p_log_msg,null);




-- omspol - Поликлиника (на Тамбове общая только в связке с бюджетом regional)
-- omsstac - Стационар (на Тамбове не исп)
-- emergency - Неотложная помощь (на Тамбове не исп)
-- resemdent - Исследования, неотложная помощь, стоматология (на Тамбове не исп)
-- ambulatory_dialysis - Диализы
-- ambulatory - Поликлиника (иногородние)
-- per_capita_own - Поликлиника (подушевое свои)	
-- per_capita_alien - Поликлиника (подушевое чужие)	
-- per_capita_other - Поликлиника (вне подушевого)	
-- parusl - Параклинические услуги
-- stom - Стоматология
-- disp_1 - Диспансеризация и медосмотры	
-- disp_2 - Диспансеризация 2 этап	
-- htm - Высокотехнологичная медицинская помощь (на Тамбове ОМС и бюджет)
-- 0901 - Круглосуточный стационар (узкие специалисты)	
-- 0901_1 - Паллиативная помощь 1 уровня	
-- 0901_2 - Паллиативная помощь 2 уровня
if _pay_type_code = 'regional' and _registry_type_code = 'htm' then

    call r477.p_registry_evnhtm_recount_bud(p_registry_id);
   
elsif _pay_type_code ='regional' and _registry_type_code in ('omspol', 'pol_bug_palliativ', 'parakl_budg'  ) then
	
    
    -- Пересчитываем
    call r477.p_registry_evnpl_recount_bud(p_registry_id);

elsif _pay_type_code = 'regional' and _registry_type_code in ('omsks','omsds','0901_1','0901_2','0901') then

    call r477.p_registry_evnps_recount_bud(p_registry_id);
   
elsif _registry_type_code in ('ambulatory_dialysis', 'ambulatory', 'per_capita_own', 'per_capita_alien', 'per_capita_other', 'parusl', 'stom','mucalc') then	
	
    	call r477.p_registry_evnpl_recount(p_registry_id);   
   
elsif _registry_type_code in ('omsks', 'omsds', 'htm') then


    
    call r477.p_Registry_EvnPs_Recount(p_registry_id);
   
elsif _registry_type_code in ('disp_1','disp_2') then   
    

    
    call r477.p_registry_evnpldisp_recount(p_registry_id);
    
end if;


--обновляем итоги по реестру 
call r477.p_registry_calc_results(p_registry_id);


perform dbo.p_Log_set (p_object_log, 'отработал [r477].[p_RegistryData_Refresh]',null);

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


end;
$$;


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

--
-- Name: p_registrydata_upd(bigint, bigint, character varying, bigint, bigint, bigint, bigint, bigint, bigint, double precision, double precision, double precision, double precision, double precision, double precision, double precision, bigint, bigint, bigint, bigint, bigint, bigint, bigint, double precision, double precision, character varying, character varying, integer, timestamp without time zone, character varying, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, bigint, timestamp without time zone, bigint, uuid, bigint, bigint, bigint, double precision, double precision, double precision, double precision, integer, bigint, bigint, bigint, timestamp without time zone, bigint, integer, bigint, bigint, bigint, numeric, bigint, bigint, numeric, numeric, bigint, bigint, bigint, bigint, bigint, integer, character varying, bigint, numeric, numeric, integer, bigint, bigint, bigint, integer, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registrydata_upd(INOUT evn_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, numcard character varying DEFAULT NULL::character varying, number bigint DEFAULT NULL::bigint, evn_rid bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, lpusectionprofile_id bigint DEFAULT NULL::bigint, medpersonal_id bigint DEFAULT NULL::bigint, registrydata_tariff double precision DEFAULT NULL::double precision, registrydata_kdfact double precision DEFAULT NULL::double precision, registrydata_kdplan double precision DEFAULT NULL::double precision, registrydata_kdpay double precision DEFAULT NULL::double precision, registrydata_ukl double precision DEFAULT NULL::double precision, registrydata_uklsum double precision DEFAULT NULL::double precision, registrydata_itogsum double precision DEFAULT NULL::double precision, omssprterr_id bigint DEFAULT NULL::bigint, address_id bigint DEFAULT NULL::bigint, registrydata_isprev bigint DEFAULT NULL::bigint, registrydata_isambul bigint DEFAULT NULL::bigint, vizittype_id bigint DEFAULT NULL::bigint, resultclass_id bigint DEFAULT NULL::bigint, diag_id bigint DEFAULT NULL::bigint, registrydata_ei2 double precision DEFAULT NULL::double precision, registrydata_g162 double precision DEFAULT NULL::double precision, medpersonal_fio character varying DEFAULT NULL::character varying, medpersonal_snils character varying DEFAULT NULL::character varying, omssprterr_code integer DEFAULT NULL::integer, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, lpusection_code character varying DEFAULT NULL::character varying, lpusectionprofile_code character varying DEFAULT NULL::character varying, medpersonal_code character varying DEFAULT NULL::character varying, polis_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgsmo_id bigint DEFAULT NULL::bigint, medspec_id bigint DEFAULT NULL::bigint, evn_upddate timestamp without time zone DEFAULT NULL::timestamp without time zone, dopdispspec_id bigint DEFAULT NULL::bigint, guid uuid DEFAULT NULL::uuid, usluga_id bigint DEFAULT NULL::bigint, paid_id bigint DEFAULT NULL::bigint, maxevn_id bigint DEFAULT NULL::bigint, registrydata_tarif_r double precision DEFAULT NULL::double precision, registrydata_tarif_f double precision DEFAULT NULL::double precision, registrydata_sum_r double precision DEFAULT NULL::double precision, registrydata_sum_f double precision DEFAULT NULL::double precision, registrydata_rownum integer DEFAULT NULL::integer, leavetype_id bigint DEFAULT NULL::bigint, resultdesease_id bigint DEFAULT NULL::bigint, leavecause_id bigint DEFAULT NULL::bigint, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, evnsection_isadultescort bigint DEFAULT NULL::bigint, registrydata_double integer DEFAULT NULL::integer, uslugacomplex_id bigint DEFAULT NULL::bigint, mestariff_id bigint DEFAULT NULL::bigint, mesitog_id bigint DEFAULT NULL::bigint, mestariff_value numeric DEFAULT NULL::numeric, evnsection_numgroup bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, mesitog_value numeric DEFAULT NULL::numeric, registrydata_coeffctp numeric DEFAULT NULL::numeric, paymedtype_id bigint DEFAULT NULL::bigint, registrydata_ispaid bigint DEFAULT NULL::bigint, server_id bigint DEFAULT NULL::bigint, personevn_id bigint DEFAULT NULL::bigint, registrydata_ispersfin bigint DEFAULT NULL::bigint, registrydata_period integer DEFAULT NULL::integer, socstatus_code character varying DEFAULT NULL::character varying, mesolduslugacomplex_id bigint DEFAULT NULL::bigint, koef_up numeric DEFAULT NULL::numeric, koef_u numeric DEFAULT NULL::numeric, registrydata_prer integer DEFAULT NULL::integer, evnmax_id bigint DEFAULT NULL::bigint, registrydata_iszno bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrydata
set registry_id = p_registrydata_upd.registry_id,
numcard = p_registrydata_upd.numcard,
number = p_registrydata_upd.number,
evn_rid = p_registrydata_upd.evn_rid,
person_id = p_registrydata_upd.person_id,
lpusection_id = p_registrydata_upd.lpusection_id,
lpusectionprofile_id = p_registrydata_upd.lpusectionprofile_id,
medpersonal_id = p_registrydata_upd.medpersonal_id,
registrydata_tariff = p_registrydata_upd.registrydata_tariff,
registrydata_kdfact = p_registrydata_upd.registrydata_kdfact,
registrydata_kdplan = p_registrydata_upd.registrydata_kdplan,
registrydata_kdpay = p_registrydata_upd.registrydata_kdpay,
registrydata_ukl = p_registrydata_upd.registrydata_ukl,
registrydata_uklsum = p_registrydata_upd.registrydata_uklsum,
registrydata_itogsum = p_registrydata_upd.registrydata_itogsum,
omssprterr_id = p_registrydata_upd.omssprterr_id,
address_id = p_registrydata_upd.address_id,
registrydata_isprev = p_registrydata_upd.registrydata_isprev,
registrydata_isambul = p_registrydata_upd.registrydata_isambul,
vizittype_id = p_registrydata_upd.vizittype_id,
resultclass_id = p_registrydata_upd.resultclass_id,
diag_id = p_registrydata_upd.diag_id,
registrydata_ei2 = p_registrydata_upd.registrydata_ei2,
registrydata_g162 = p_registrydata_upd.registrydata_g162,
medpersonal_fio = p_registrydata_upd.medpersonal_fio,
medpersonal_snils = p_registrydata_upd.medpersonal_snils,
omssprterr_code = p_registrydata_upd.omssprterr_code,
evn_disdate = p_registrydata_upd.evn_disdate,
lpusection_code = p_registrydata_upd.lpusection_code,
lpusectionprofile_code = p_registrydata_upd.lpusectionprofile_code,
medpersonal_code = p_registrydata_upd.medpersonal_code,
polis_begdate = p_registrydata_upd.polis_begdate,
polis_enddate = p_registrydata_upd.polis_enddate,
orgsmo_id = p_registrydata_upd.orgsmo_id,
medspec_id = p_registrydata_upd.medspec_id,
evn_upddate = p_registrydata_upd.evn_upddate,
dopdispspec_id = p_registrydata_upd.dopdispspec_id,
guid = p_registrydata_upd.guid,
usluga_id = p_registrydata_upd.usluga_id,
paid_id = p_registrydata_upd.paid_id,
maxevn_id = p_registrydata_upd.maxevn_id,
registrydata_tarif_r = p_registrydata_upd.registrydata_tarif_r,
registrydata_tarif_f = p_registrydata_upd.registrydata_tarif_f,
registrydata_sum_r = p_registrydata_upd.registrydata_sum_r,
registrydata_sum_f = p_registrydata_upd.registrydata_sum_f,
registrydata_rownum = p_registrydata_upd.registrydata_rownum,
leavetype_id = p_registrydata_upd.leavetype_id,
resultdesease_id = p_registrydata_upd.resultdesease_id,
leavecause_id = p_registrydata_upd.leavecause_id,
evn_setdate = p_registrydata_upd.evn_setdate,
evnsection_isadultescort = p_registrydata_upd.evnsection_isadultescort,
registrydata_double = p_registrydata_upd.registrydata_double,
uslugacomplex_id = p_registrydata_upd.uslugacomplex_id,
mestariff_id = p_registrydata_upd.mestariff_id,
mesitog_id = p_registrydata_upd.mesitog_id,
mestariff_value = p_registrydata_upd.mestariff_value,
evnsection_numgroup = p_registrydata_upd.evnsection_numgroup,
lpuunittype_id = p_registrydata_upd.lpuunittype_id,
mesitog_value = p_registrydata_upd.mesitog_value,
registrydata_coeffctp = p_registrydata_upd.registrydata_coeffctp,
paymedtype_id = p_registrydata_upd.paymedtype_id,
registrydata_ispaid = p_registrydata_upd.registrydata_ispaid,
server_id = p_registrydata_upd.server_id,
personevn_id = p_registrydata_upd.personevn_id,
registrydata_ispersfin = p_registrydata_upd.registrydata_ispersfin,
registrydata_period = p_registrydata_upd.registrydata_period,
socstatus_code = p_registrydata_upd.socstatus_code,
mesolduslugacomplex_id = p_registrydata_upd.mesolduslugacomplex_id,
koef_up = p_registrydata_upd.koef_up,
koef_u = p_registrydata_upd.koef_u,
registrydata_prer = p_registrydata_upd.registrydata_prer,
evnmax_id = p_registrydata_upd.evnmax_id,
registrydata_iszno = p_registrydata_upd.registrydata_iszno,
pmuser_updid = pmuser_id,
registrydata_upddt = now()
where registrydata.evn_id = p_registrydata_upd.evn_id;

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




END; $$;


ALTER FUNCTION r477.p_registrydata_upd(INOUT evn_id bigint, registry_id bigint, numcard character varying, number bigint, evn_rid bigint, person_id bigint, lpusection_id bigint, lpusectionprofile_id bigint, medpersonal_id bigint, registrydata_tariff double precision, registrydata_kdfact double precision, registrydata_kdplan double precision, registrydata_kdpay double precision, registrydata_ukl double precision, registrydata_uklsum double precision, registrydata_itogsum double precision, omssprterr_id bigint, address_id bigint, registrydata_isprev bigint, registrydata_isambul bigint, vizittype_id bigint, resultclass_id bigint, diag_id bigint, registrydata_ei2 double precision, registrydata_g162 double precision, medpersonal_fio character varying, medpersonal_snils character varying, omssprterr_code integer, evn_disdate timestamp without time zone, lpusection_code character varying, lpusectionprofile_code character varying, medpersonal_code character varying, polis_begdate timestamp without time zone, polis_enddate timestamp without time zone, orgsmo_id bigint, medspec_id bigint, evn_upddate timestamp without time zone, dopdispspec_id bigint, guid uuid, usluga_id bigint, paid_id bigint, maxevn_id bigint, registrydata_tarif_r double precision, registrydata_tarif_f double precision, registrydata_sum_r double precision, registrydata_sum_f double precision, registrydata_rownum integer, leavetype_id bigint, resultdesease_id bigint, leavecause_id bigint, evn_setdate timestamp without time zone, evnsection_isadultescort bigint, registrydata_double integer, uslugacomplex_id bigint, mestariff_id bigint, mesitog_id bigint, mestariff_value numeric, evnsection_numgroup bigint, lpuunittype_id bigint, mesitog_value numeric, registrydata_coeffctp numeric, paymedtype_id bigint, registrydata_ispaid bigint, server_id bigint, personevn_id bigint, registrydata_ispersfin bigint, registrydata_period integer, socstatus_code character varying, mesolduslugacomplex_id bigint, koef_up numeric, koef_u numeric, registrydata_prer integer, evnmax_id bigint, registrydata_iszno bigint, pmuser_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registrydatacmp
if (coalesce(isremove,1)=2) then
	delete from r477.registrydatacmp
	where registrydatacmp.cmpclosecard_id = p_registrydatacmp_del.cmpclosecard_id;
else
	update r477.registrydatacmp
	set 
	pmuser_delid=pmuser_id,
	registrydatacmp_deldt=now(),
	registrydatacmp_deleted=2
	where registrydatacmp.cmpclosecard_id = p_registrydatacmp_del.cmpclosecard_id;
	end if;

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


end; $$;


ALTER FUNCTION r477.p_registrydatacmp_del(cmpclosecard_id bigint, pmuser_id bigint, isremove bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_registrydatacmp_ins(bigint, bigint, character, bigint, bigint, bigint, bigint, double precision, double precision, double precision, double precision, bigint, bigint, bigint, bigint, bigint, character varying, character varying, integer, timestamp without time zone, character varying, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, bigint, timestamp without time zone, bigint, character varying, character varying, timestamp without time zone, integer, bigint, bigint, bigint, bigint, integer, integer, bigint, bigint, bigint, double precision, double precision, double precision, double precision, double precision, bigint, bigint, double precision, double precision, double precision, double precision, bigint, bigint, bigint, numeric, bigint, bigint, bigint, integer, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registrydatacmp_ins(INOUT cmpclosecard_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, numcard character DEFAULT NULL::bpchar, person_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, lpusectionprofile_id bigint DEFAULT NULL::bigint, medpersonal_id bigint DEFAULT NULL::bigint, registrydatacmp_tariff double precision DEFAULT NULL::double precision, registrydatacmp_ukl double precision DEFAULT NULL::double precision, registrydatacmp_uklsum double precision DEFAULT NULL::double precision, registrydatacmp_itogsum double precision DEFAULT NULL::double precision, omssprterr_id bigint DEFAULT NULL::bigint, address_id bigint DEFAULT NULL::bigint, registrydatacmp_isprev bigint DEFAULT NULL::bigint, registrydatacmp_isambul bigint DEFAULT NULL::bigint, diag_id bigint DEFAULT NULL::bigint, medpersonal_fio character varying DEFAULT NULL::character varying, medpersonal_snils character varying DEFAULT NULL::character varying, omssprterr_code integer DEFAULT NULL::integer, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, lpusection_code character varying DEFAULT NULL::character varying, lpusectionprofile_code character varying DEFAULT NULL::character varying, medpersonal_code character varying DEFAULT NULL::character varying, polis_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgsmo_id bigint DEFAULT NULL::bigint, medspec_id bigint DEFAULT NULL::bigint, cmpclosecard_upddate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_id bigint DEFAULT NULL::bigint, polis_ser character varying DEFAULT NULL::character varying, polis_num character varying DEFAULT NULL::character varying, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, needreform integer DEFAULT NULL::integer, evnps_iscont bigint DEFAULT NULL::bigint, prehospdirect_id bigint DEFAULT NULL::bigint, registrydatacmp_isperev bigint DEFAULT NULL::bigint, cmpresult_id bigint DEFAULT NULL::bigint, registrydatacmp_rownum integer DEFAULT NULL::integer, registrydatacmp_double integer DEFAULT NULL::integer, evnsection_isadultescort bigint DEFAULT NULL::bigint, registrydatacmp_ispaid bigint DEFAULT NULL::bigint, uslugacomplex_id bigint DEFAULT NULL::bigint, registrydatacmp_tarif_r double precision DEFAULT NULL::double precision, registrydatacmp_tarif_f double precision DEFAULT NULL::double precision, registrydatacmp_sum_r double precision DEFAULT NULL::double precision, registrydatacmp_sum_f double precision DEFAULT NULL::double precision, registrydatacmp_ei2 double precision DEFAULT NULL::double precision, paymedtype_id bigint DEFAULT NULL::bigint, number bigint DEFAULT NULL::bigint, registrydatacmp_kdfact double precision DEFAULT NULL::double precision, registrydatacmp_kdplan double precision DEFAULT NULL::double precision, registrydatacmp_kdpay double precision DEFAULT NULL::double precision, registrydatacmp_g162 double precision DEFAULT NULL::double precision, maxevn_id bigint DEFAULT NULL::bigint, evnsection_numgroup bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, registrydatacmp_coeffctp numeric DEFAULT NULL::numeric, registrydatacmp_ispersfin bigint DEFAULT NULL::bigint, cmpclosecard_sid bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(cmpclosecard_id, 0) = 0
then 
	insert into r477.registrydatacmp(registry_id, numcard, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydatacmp_tariff, registrydatacmp_ukl, registrydatacmp_uklsum, registrydatacmp_itogsum, omssprterr_id, address_id, registrydatacmp_isprev, registrydatacmp_isambul, diag_id, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, cmpclosecard_upddate, polis_id, polis_ser, polis_num, evn_setdate, needreform, evnps_iscont, prehospdirect_id, registrydatacmp_isperev, cmpresult_id, registrydatacmp_rownum, registrydatacmp_double, evnsection_isadultescort, registrydatacmp_ispaid, uslugacomplex_id, registrydatacmp_tarif_r, registrydatacmp_tarif_f, registrydatacmp_sum_r, registrydatacmp_sum_f, registrydatacmp_ei2, paymedtype_id, number, registrydatacmp_kdfact, registrydatacmp_kdplan, registrydatacmp_kdpay, registrydatacmp_g162, maxevn_id, evnsection_numgroup, lpuunittype_id, registrydatacmp_coeffctp, registrydatacmp_ispersfin, cmpclosecard_sid, pmuser_insid, pmuser_updid, registrydatacmp_insdt, registrydatacmp_upddt)
	values (registry_id, numcard, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydatacmp_tariff, registrydatacmp_ukl, registrydatacmp_uklsum, registrydatacmp_itogsum, omssprterr_id, address_id, registrydatacmp_isprev, registrydatacmp_isambul, diag_id, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, cmpclosecard_upddate, polis_id, polis_ser, polis_num, evn_setdate, needreform, evnps_iscont, prehospdirect_id, registrydatacmp_isperev, cmpresult_id, registrydatacmp_rownum, registrydatacmp_double, evnsection_isadultescort, registrydatacmp_ispaid, uslugacomplex_id, registrydatacmp_tarif_r, registrydatacmp_tarif_f, registrydatacmp_sum_r, registrydatacmp_sum_f, registrydatacmp_ei2, paymedtype_id, number, registrydatacmp_kdfact, registrydatacmp_kdplan, registrydatacmp_kdpay, registrydatacmp_g162, maxevn_id, evnsection_numgroup, lpuunittype_id, registrydatacmp_coeffctp, registrydatacmp_ispersfin, cmpclosecard_sid, pmuser_id, pmuser_id, now(), now())
	returning registrydatacmp.cmpclosecard_id into p_registrydatacmp_ins.cmpclosecard_id;
else
	insert into r477.registrydatacmp(cmpclosecard_id, registry_id, numcard, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydatacmp_tariff, registrydatacmp_ukl, registrydatacmp_uklsum, registrydatacmp_itogsum, omssprterr_id, address_id, registrydatacmp_isprev, registrydatacmp_isambul, diag_id, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, cmpclosecard_upddate, polis_id, polis_ser, polis_num, evn_setdate, needreform, evnps_iscont, prehospdirect_id, registrydatacmp_isperev, cmpresult_id, registrydatacmp_rownum, registrydatacmp_double, evnsection_isadultescort, registrydatacmp_ispaid, uslugacomplex_id, registrydatacmp_tarif_r, registrydatacmp_tarif_f, registrydatacmp_sum_r, registrydatacmp_sum_f, registrydatacmp_ei2, paymedtype_id, number, registrydatacmp_kdfact, registrydatacmp_kdplan, registrydatacmp_kdpay, registrydatacmp_g162, maxevn_id, evnsection_numgroup, lpuunittype_id, registrydatacmp_coeffctp, registrydatacmp_ispersfin, cmpclosecard_sid, pmuser_insid, pmuser_updid, registrydatacmp_insdt, registrydatacmp_upddt)
	values (cmpclosecard_id, registry_id, numcard, person_id, lpusection_id, lpusectionprofile_id, medpersonal_id, registrydatacmp_tariff, registrydatacmp_ukl, registrydatacmp_uklsum, registrydatacmp_itogsum, omssprterr_id, address_id, registrydatacmp_isprev, registrydatacmp_isambul, diag_id, medpersonal_fio, medpersonal_snils, omssprterr_code, evn_disdate, lpusection_code, lpusectionprofile_code, medpersonal_code, polis_begdate, polis_enddate, orgsmo_id, medspec_id, cmpclosecard_upddate, polis_id, polis_ser, polis_num, evn_setdate, needreform, evnps_iscont, prehospdirect_id, registrydatacmp_isperev, cmpresult_id, registrydatacmp_rownum, registrydatacmp_double, evnsection_isadultescort, registrydatacmp_ispaid, uslugacomplex_id, registrydatacmp_tarif_r, registrydatacmp_tarif_f, registrydatacmp_sum_r, registrydatacmp_sum_f, registrydatacmp_ei2, paymedtype_id, number, registrydatacmp_kdfact, registrydatacmp_kdplan, registrydatacmp_kdpay, registrydatacmp_g162, maxevn_id, evnsection_numgroup, lpuunittype_id, registrydatacmp_coeffctp, registrydatacmp_ispersfin, cmpclosecard_sid, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrydatacmp_ins(INOUT cmpclosecard_id bigint, registry_id bigint, numcard character, person_id bigint, lpusection_id bigint, lpusectionprofile_id bigint, medpersonal_id bigint, registrydatacmp_tariff double precision, registrydatacmp_ukl double precision, registrydatacmp_uklsum double precision, registrydatacmp_itogsum double precision, omssprterr_id bigint, address_id bigint, registrydatacmp_isprev bigint, registrydatacmp_isambul bigint, diag_id bigint, medpersonal_fio character varying, medpersonal_snils character varying, omssprterr_code integer, evn_disdate timestamp without time zone, lpusection_code character varying, lpusectionprofile_code character varying, medpersonal_code character varying, polis_begdate timestamp without time zone, polis_enddate timestamp without time zone, orgsmo_id bigint, medspec_id bigint, cmpclosecard_upddate timestamp without time zone, polis_id bigint, polis_ser character varying, polis_num character varying, evn_setdate timestamp without time zone, needreform integer, evnps_iscont bigint, prehospdirect_id bigint, registrydatacmp_isperev bigint, cmpresult_id bigint, registrydatacmp_rownum integer, registrydatacmp_double integer, evnsection_isadultescort bigint, registrydatacmp_ispaid bigint, uslugacomplex_id bigint, registrydatacmp_tarif_r double precision, registrydatacmp_tarif_f double precision, registrydatacmp_sum_r double precision, registrydatacmp_sum_f double precision, registrydatacmp_ei2 double precision, paymedtype_id bigint, number bigint, registrydatacmp_kdfact double precision, registrydatacmp_kdplan double precision, registrydatacmp_kdpay double precision, registrydatacmp_g162 double precision, maxevn_id bigint, evnsection_numgroup bigint, lpuunittype_id bigint, registrydatacmp_coeffctp numeric, registrydatacmp_ispersfin bigint, cmpclosecard_sid bigint, pmuser_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

--
-- Name: p_registrydatacmp_upd(bigint, bigint, character, bigint, bigint, bigint, bigint, double precision, double precision, double precision, double precision, bigint, bigint, bigint, bigint, bigint, character varying, character varying, integer, timestamp without time zone, character varying, character varying, character varying, timestamp without time zone, timestamp without time zone, bigint, bigint, timestamp without time zone, bigint, character varying, character varying, timestamp without time zone, integer, bigint, bigint, bigint, bigint, integer, integer, bigint, bigint, bigint, double precision, double precision, double precision, double precision, double precision, bigint, bigint, double precision, double precision, double precision, double precision, bigint, bigint, bigint, numeric, bigint, bigint, bigint, integer, character varying); Type: FUNCTION; Schema: r477; Owner: developer_rep
--

CREATE FUNCTION r477.p_registrydatacmp_upd(INOUT cmpclosecard_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, numcard character DEFAULT NULL::bpchar, person_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, lpusectionprofile_id bigint DEFAULT NULL::bigint, medpersonal_id bigint DEFAULT NULL::bigint, registrydatacmp_tariff double precision DEFAULT NULL::double precision, registrydatacmp_ukl double precision DEFAULT NULL::double precision, registrydatacmp_uklsum double precision DEFAULT NULL::double precision, registrydatacmp_itogsum double precision DEFAULT NULL::double precision, omssprterr_id bigint DEFAULT NULL::bigint, address_id bigint DEFAULT NULL::bigint, registrydatacmp_isprev bigint DEFAULT NULL::bigint, registrydatacmp_isambul bigint DEFAULT NULL::bigint, diag_id bigint DEFAULT NULL::bigint, medpersonal_fio character varying DEFAULT NULL::character varying, medpersonal_snils character varying DEFAULT NULL::character varying, omssprterr_code integer DEFAULT NULL::integer, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, lpusection_code character varying DEFAULT NULL::character varying, lpusectionprofile_code character varying DEFAULT NULL::character varying, medpersonal_code character varying DEFAULT NULL::character varying, polis_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgsmo_id bigint DEFAULT NULL::bigint, medspec_id bigint DEFAULT NULL::bigint, cmpclosecard_upddate timestamp without time zone DEFAULT NULL::timestamp without time zone, polis_id bigint DEFAULT NULL::bigint, polis_ser character varying DEFAULT NULL::character varying, polis_num character varying DEFAULT NULL::character varying, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, needreform integer DEFAULT NULL::integer, evnps_iscont bigint DEFAULT NULL::bigint, prehospdirect_id bigint DEFAULT NULL::bigint, registrydatacmp_isperev bigint DEFAULT NULL::bigint, cmpresult_id bigint DEFAULT NULL::bigint, registrydatacmp_rownum integer DEFAULT NULL::integer, registrydatacmp_double integer DEFAULT NULL::integer, evnsection_isadultescort bigint DEFAULT NULL::bigint, registrydatacmp_ispaid bigint DEFAULT NULL::bigint, uslugacomplex_id bigint DEFAULT NULL::bigint, registrydatacmp_tarif_r double precision DEFAULT NULL::double precision, registrydatacmp_tarif_f double precision DEFAULT NULL::double precision, registrydatacmp_sum_r double precision DEFAULT NULL::double precision, registrydatacmp_sum_f double precision DEFAULT NULL::double precision, registrydatacmp_ei2 double precision DEFAULT NULL::double precision, paymedtype_id bigint DEFAULT NULL::bigint, number bigint DEFAULT NULL::bigint, registrydatacmp_kdfact double precision DEFAULT NULL::double precision, registrydatacmp_kdplan double precision DEFAULT NULL::double precision, registrydatacmp_kdpay double precision DEFAULT NULL::double precision, registrydatacmp_g162 double precision DEFAULT NULL::double precision, maxevn_id bigint DEFAULT NULL::bigint, evnsection_numgroup bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, registrydatacmp_coeffctp numeric DEFAULT NULL::numeric, registrydatacmp_ispersfin bigint DEFAULT NULL::bigint, cmpclosecard_sid bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrydatacmp
set registry_id = p_registrydatacmp_upd.registry_id,
numcard = p_registrydatacmp_upd.numcard,
person_id = p_registrydatacmp_upd.person_id,
lpusection_id = p_registrydatacmp_upd.lpusection_id,
lpusectionprofile_id = p_registrydatacmp_upd.lpusectionprofile_id,
medpersonal_id = p_registrydatacmp_upd.medpersonal_id,
registrydatacmp_tariff = p_registrydatacmp_upd.registrydatacmp_tariff,
registrydatacmp_ukl = p_registrydatacmp_upd.registrydatacmp_ukl,
registrydatacmp_uklsum = p_registrydatacmp_upd.registrydatacmp_uklsum,
registrydatacmp_itogsum = p_registrydatacmp_upd.registrydatacmp_itogsum,
omssprterr_id = p_registrydatacmp_upd.omssprterr_id,
address_id = p_registrydatacmp_upd.address_id,
registrydatacmp_isprev = p_registrydatacmp_upd.registrydatacmp_isprev,
registrydatacmp_isambul = p_registrydatacmp_upd.registrydatacmp_isambul,
diag_id = p_registrydatacmp_upd.diag_id,
medpersonal_fio = p_registrydatacmp_upd.medpersonal_fio,
medpersonal_snils = p_registrydatacmp_upd.medpersonal_snils,
omssprterr_code = p_registrydatacmp_upd.omssprterr_code,
evn_disdate = p_registrydatacmp_upd.evn_disdate,
lpusection_code = p_registrydatacmp_upd.lpusection_code,
lpusectionprofile_code = p_registrydatacmp_upd.lpusectionprofile_code,
medpersonal_code = p_registrydatacmp_upd.medpersonal_code,
polis_begdate = p_registrydatacmp_upd.polis_begdate,
polis_enddate = p_registrydatacmp_upd.polis_enddate,
orgsmo_id = p_registrydatacmp_upd.orgsmo_id,
medspec_id = p_registrydatacmp_upd.medspec_id,
cmpclosecard_upddate = p_registrydatacmp_upd.cmpclosecard_upddate,
polis_id = p_registrydatacmp_upd.polis_id,
polis_ser = p_registrydatacmp_upd.polis_ser,
polis_num = p_registrydatacmp_upd.polis_num,
evn_setdate = p_registrydatacmp_upd.evn_setdate,
needreform = p_registrydatacmp_upd.needreform,
evnps_iscont = p_registrydatacmp_upd.evnps_iscont,
prehospdirect_id = p_registrydatacmp_upd.prehospdirect_id,
registrydatacmp_isperev = p_registrydatacmp_upd.registrydatacmp_isperev,
cmpresult_id = p_registrydatacmp_upd.cmpresult_id,
registrydatacmp_rownum = p_registrydatacmp_upd.registrydatacmp_rownum,
registrydatacmp_double = p_registrydatacmp_upd.registrydatacmp_double,
evnsection_isadultescort = p_registrydatacmp_upd.evnsection_isadultescort,
registrydatacmp_ispaid = p_registrydatacmp_upd.registrydatacmp_ispaid,
uslugacomplex_id = p_registrydatacmp_upd.uslugacomplex_id,
registrydatacmp_tarif_r = p_registrydatacmp_upd.registrydatacmp_tarif_r,
registrydatacmp_tarif_f = p_registrydatacmp_upd.registrydatacmp_tarif_f,
registrydatacmp_sum_r = p_registrydatacmp_upd.registrydatacmp_sum_r,
registrydatacmp_sum_f = p_registrydatacmp_upd.registrydatacmp_sum_f,
registrydatacmp_ei2 = p_registrydatacmp_upd.registrydatacmp_ei2,
paymedtype_id = p_registrydatacmp_upd.paymedtype_id,
number = p_registrydatacmp_upd.number,
registrydatacmp_kdfact = p_registrydatacmp_upd.registrydatacmp_kdfact,
registrydatacmp_kdplan = p_registrydatacmp_upd.registrydatacmp_kdplan,
registrydatacmp_kdpay = p_registrydatacmp_upd.registrydatacmp_kdpay,
registrydatacmp_g162 = p_registrydatacmp_upd.registrydatacmp_g162,
maxevn_id = p_registrydatacmp_upd.maxevn_id,
evnsection_numgroup = p_registrydatacmp_upd.evnsection_numgroup,
lpuunittype_id = p_registrydatacmp_upd.lpuunittype_id,
registrydatacmp_coeffctp = p_registrydatacmp_upd.registrydatacmp_coeffctp,
registrydatacmp_ispersfin = p_registrydatacmp_upd.registrydatacmp_ispersfin,
cmpclosecard_sid = p_registrydatacmp_upd.cmpclosecard_sid,
pmuser_updid = pmuser_id,
registrydatacmp_upddt = now()
where registrydatacmp.cmpclosecard_id = p_registrydatacmp_upd.cmpclosecard_id;

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




END; $$;


ALTER FUNCTION r477.p_registrydatacmp_upd(INOUT cmpclosecard_id bigint, registry_id bigint, numcard character, person_id bigint, lpusection_id bigint, lpusectionprofile_id bigint, medpersonal_id bigint, registrydatacmp_tariff double precision, registrydatacmp_ukl double precision, registrydatacmp_uklsum double precision, registrydatacmp_itogsum double precision, omssprterr_id bigint, address_id bigint, registrydatacmp_isprev bigint, registrydatacmp_isambul bigint, diag_id bigint, medpersonal_fio character varying, medpersonal_snils character varying, omssprterr_code integer, evn_disdate timestamp without time zone, lpusection_code character varying, lpusectionprofile_code character varying, medpersonal_code character varying, polis_begdate timestamp without time zone, polis_enddate timestamp without time zone, orgsmo_id bigint, medspec_id bigint, cmpclosecard_upddate timestamp without time zone, polis_id bigint, polis_ser character varying, polis_num character varying, evn_setdate timestamp without time zone, needreform integer, evnps_iscont bigint, prehospdirect_id bigint, registrydatacmp_isperev bigint, cmpresult_id bigint, registrydatacmp_rownum integer, registrydatacmp_double integer, evnsection_isadultescort bigint, registrydatacmp_ispaid bigint, uslugacomplex_id bigint, registrydatacmp_tarif_r double precision, registrydatacmp_tarif_f double precision, registrydatacmp_sum_r double precision, registrydatacmp_sum_f double precision, registrydatacmp_ei2 double precision, paymedtype_id bigint, number bigint, registrydatacmp_kdfact double precision, registrydatacmp_kdplan double precision, registrydatacmp_kdpay double precision, registrydatacmp_g162 double precision, maxevn_id bigint, evnsection_numgroup bigint, lpuunittype_id bigint, registrydatacmp_coeffctp numeric, registrydatacmp_ispersfin bigint, cmpclosecard_sid bigint, pmuser_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registrydatasl
delete from r477.registrydatasl
where registrydatasl.registrydatasl_id = p_registrydatasl_del.registrydatasl_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registrydatasl_ins(INOUT registrydatasl_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, registrydatasl_rownum integer DEFAULT NULL::integer, evn_id bigint DEFAULT NULL::bigint, evn_rid bigint DEFAULT NULL::bigint, maxevn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, lpu_id bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, personevn_id bigint DEFAULT NULL::bigint, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, omssprterr_id bigint DEFAULT NULL::bigint, orgsmo_id bigint DEFAULT NULL::bigint, registrydatasl_sum double precision DEFAULT NULL::double precision, kd_z integer DEFAULT NULL::integer, server_id bigint DEFAULT NULL::bigint, numcard character varying DEFAULT NULL::character varying, leavetype_id bigint DEFAULT NULL::bigint, resultdesease_id bigint DEFAULT NULL::bigint, vb_p integer DEFAULT NULL::integer, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registrydatasl_id, 0) = 0
then 
	insert into r477.registrydatasl(registry_id, registrydatasl_rownum, evn_id, evn_rid, maxevn_id, person_id, lpu_id, lpuunittype_id, personevn_id, evn_setdate, evn_disdate, omssprterr_id, orgsmo_id, registrydatasl_sum, kd_z, server_id, numcard, leavetype_id, resultdesease_id, vb_p, pmuser_insid, pmuser_updid, registrydatasl_insdt, registrydatasl_upddt)
	values ( registry_id, registrydatasl_rownum, evn_id, evn_rid, maxevn_id, person_id, lpu_id, lpuunittype_id, personevn_id, evn_setdate, evn_disdate, omssprterr_id, orgsmo_id, registrydatasl_sum, kd_z, server_id, numcard, leavetype_id, resultdesease_id, vb_p, pmuser_id, pmuser_id, now(), now())
	returning registrydatasl.registrydatasl_id into p_registrydatasl_ins.registrydatasl_id;
else
	insert into r477.registrydatasl(registrydatasl_id, registry_id, registrydatasl_rownum, evn_id, evn_rid, maxevn_id, person_id, lpu_id, lpuunittype_id, personevn_id, evn_setdate, evn_disdate, omssprterr_id, orgsmo_id, registrydatasl_sum, kd_z, server_id, numcard, leavetype_id, resultdesease_id, vb_p, pmuser_insid, pmuser_updid, registrydatasl_insdt, registrydatasl_upddt)
	values (registrydatasl_id, registry_id, registrydatasl_rownum, evn_id, evn_rid, maxevn_id, person_id, lpu_id, lpuunittype_id, personevn_id, evn_setdate, evn_disdate, omssprterr_id, orgsmo_id, registrydatasl_sum, kd_z, server_id, numcard, leavetype_id, resultdesease_id, vb_p, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrydatasl_ins(INOUT registrydatasl_id bigint, registry_id bigint, registrydatasl_rownum integer, evn_id bigint, evn_rid bigint, maxevn_id bigint, person_id bigint, lpu_id bigint, lpuunittype_id bigint, personevn_id bigint, evn_setdate timestamp without time zone, evn_disdate timestamp without time zone, omssprterr_id bigint, orgsmo_id bigint, registrydatasl_sum double precision, kd_z integer, server_id bigint, numcard character varying, leavetype_id bigint, resultdesease_id bigint, vb_p integer, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrydatasl_upd(INOUT registrydatasl_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, registrydatasl_rownum integer DEFAULT NULL::integer, evn_id bigint DEFAULT NULL::bigint, evn_rid bigint DEFAULT NULL::bigint, maxevn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, lpu_id bigint DEFAULT NULL::bigint, lpuunittype_id bigint DEFAULT NULL::bigint, personevn_id bigint DEFAULT NULL::bigint, evn_setdate timestamp without time zone DEFAULT NULL::timestamp without time zone, evn_disdate timestamp without time zone DEFAULT NULL::timestamp without time zone, omssprterr_id bigint DEFAULT NULL::bigint, orgsmo_id bigint DEFAULT NULL::bigint, registrydatasl_sum double precision DEFAULT NULL::double precision, kd_z integer DEFAULT NULL::integer, server_id bigint DEFAULT NULL::bigint, numcard character varying DEFAULT NULL::character varying, leavetype_id bigint DEFAULT NULL::bigint, resultdesease_id bigint DEFAULT NULL::bigint, vb_p integer DEFAULT NULL::integer, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrydatasl
set registry_id = p_registrydatasl_upd.registry_id,
registrydatasl_rownum = p_registrydatasl_upd.registrydatasl_rownum,
evn_id = p_registrydatasl_upd.evn_id,
evn_rid = p_registrydatasl_upd.evn_rid,
maxevn_id = p_registrydatasl_upd.maxevn_id,
person_id = p_registrydatasl_upd.person_id,
lpu_id = p_registrydatasl_upd.lpu_id,
lpuunittype_id = p_registrydatasl_upd.lpuunittype_id,
personevn_id = p_registrydatasl_upd.personevn_id,
evn_setdate = p_registrydatasl_upd.evn_setdate,
evn_disdate = p_registrydatasl_upd.evn_disdate,
omssprterr_id = p_registrydatasl_upd.omssprterr_id,
orgsmo_id = p_registrydatasl_upd.orgsmo_id,
registrydatasl_sum = p_registrydatasl_upd.registrydatasl_sum,
kd_z = p_registrydatasl_upd.kd_z,
server_id = p_registrydatasl_upd.server_id,
numcard = p_registrydatasl_upd.numcard,
leavetype_id = p_registrydatasl_upd.leavetype_id,
resultdesease_id = p_registrydatasl_upd.resultdesease_id,
vb_p = p_registrydatasl_upd.vb_p,
pmuser_updid = pmuser_id,
registrydatasl_upddt = now()

where registrydatasl.registrydatasl_id = p_registrydatasl_upd.registrydatasl_id;

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


END; $$;


ALTER FUNCTION r477.p_registrydatasl_upd(INOUT registrydatasl_id bigint, registry_id bigint, registrydatasl_rownum integer, evn_id bigint, evn_rid bigint, maxevn_id bigint, person_id bigint, lpu_id bigint, lpuunittype_id bigint, personevn_id bigint, evn_setdate timestamp without time zone, evn_disdate timestamp without time zone, omssprterr_id bigint, orgsmo_id bigint, registrydatasl_sum double precision, kd_z integer, server_id bigint, numcard character varying, leavetype_id bigint, resultdesease_id bigint, vb_p integer, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registrydouble
delete from r477.registrydouble
where registrydouble.registry_id = p_registrydouble_del.registry_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registrydouble_ins(INOUT registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, evn_code character varying DEFAULT NULL::character varying, person_surname character varying DEFAULT NULL::character varying, person_firname character varying DEFAULT NULL::character varying, person_secname character varying DEFAULT NULL::character varying, person_birthday timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registry_id, 0) = 0
then 
	insert into r477.registrydouble(evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, pmuser_insid, pmuser_updid, registrydouble_insdt, registrydouble_upddt)
	values ( evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, pmuser_id, pmuser_id, now(), now())
	returning registrydouble.registry_id into p_registrydouble_ins.registry_id;
else
	insert into r477.registrydouble(registry_id, evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, pmuser_insid, pmuser_updid, registrydouble_insdt, registrydouble_upddt)
	values (registry_id, evn_id, person_id, evn_code, person_surname, person_firname, person_secname, person_birthday, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrydouble_ins(INOUT registry_id bigint, evn_id bigint, person_id bigint, evn_code character varying, person_surname character varying, person_firname character varying, person_secname character varying, person_birthday timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrydouble_upd(INOUT registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, person_id bigint DEFAULT NULL::bigint, evn_code character varying DEFAULT NULL::character varying, person_surname character varying DEFAULT NULL::character varying, person_firname character varying DEFAULT NULL::character varying, person_secname character varying DEFAULT NULL::character varying, person_birthday timestamp without time zone DEFAULT NULL::timestamp without time zone, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrydouble
set evn_id = p_registrydouble_upd.evn_id,
person_id = p_registrydouble_upd.person_id,
evn_code = p_registrydouble_upd.evn_code,
person_surname = p_registrydouble_upd.person_surname,
person_firname = p_registrydouble_upd.person_firname,
person_secname = p_registrydouble_upd.person_secname,
person_birthday = p_registrydouble_upd.person_birthday,
pmuser_updid = pmuser_id,
registrydouble_upddt = now()

where registrydouble.registry_id = p_registrydouble_upd.registry_id;

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


END; $$;


ALTER FUNCTION r477.p_registrydouble_upd(INOUT registry_id bigint, evn_id bigint, person_id bigint, evn_code character varying, person_surname character varying, person_firname character varying, person_secname character varying, person_birthday timestamp without time zone, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryerrorclass
delete from r477.registryerrorclass
where registryerrorclass.registryerrorclass_id = p_registryerrorclass_del.registryerrorclass_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryerrorclass_ins(INOUT registryerrorclass_id bigint DEFAULT NULL::bigint, registryerrorclass_code integer DEFAULT NULL::integer, registryerrorclass_name character varying DEFAULT NULL::character varying, registryerrorclass_nick character varying DEFAULT NULL::character varying, registryerrorclass_sysnick character varying DEFAULT NULL::character varying, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registryerrorclass_id, 0) = 0
then 
	insert into r477.registryerrorclass(registryerrorclass_code, registryerrorclass_name, registryerrorclass_nick, registryerrorclass_sysnick, pmuser_insid, pmuser_updid, registryerrorclass_insdt, registryerrorclass_upddt)
	values ( registryerrorclass_code, registryerrorclass_name, registryerrorclass_nick, registryerrorclass_sysnick, pmuser_id, pmuser_id, now(), now())
	returning registryerrorclass.registryerrorclass_id into p_registryerrorclass_ins.registryerrorclass_id;
else
	insert into r477.registryerrorclass(registryerrorclass_id, registryerrorclass_code, registryerrorclass_name, registryerrorclass_nick, registryerrorclass_sysnick, pmuser_insid, pmuser_updid, registryerrorclass_insdt, registryerrorclass_upddt)
	values (registryerrorclass_id, registryerrorclass_code, registryerrorclass_name, registryerrorclass_nick, registryerrorclass_sysnick, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registryerrorclass_ins(INOUT registryerrorclass_id bigint, registryerrorclass_code integer, registryerrorclass_name character varying, registryerrorclass_nick character varying, registryerrorclass_sysnick character varying, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryerrorclass_upd(INOUT registryerrorclass_id bigint DEFAULT NULL::bigint, registryerrorclass_code integer DEFAULT NULL::integer, registryerrorclass_name character varying DEFAULT NULL::character varying, registryerrorclass_nick character varying DEFAULT NULL::character varying, registryerrorclass_sysnick character varying DEFAULT NULL::character varying, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryerrorclass
set registryerrorclass_code = p_registryerrorclass_upd.registryerrorclass_code,
registryerrorclass_name = p_registryerrorclass_upd.registryerrorclass_name,
registryerrorclass_nick = p_registryerrorclass_upd.registryerrorclass_nick,
registryerrorclass_sysnick = p_registryerrorclass_upd.registryerrorclass_sysnick,
pmuser_updid = pmuser_id,
registryerrorclass_upddt = now()
where registryerrorclass.registryerrorclass_id = p_registryerrorclass_upd.registryerrorclass_id;

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




END; $$;


ALTER FUNCTION r477.p_registryerrorclass_upd(INOUT registryerrorclass_id bigint, registryerrorclass_code integer, registryerrorclass_name character varying, registryerrorclass_nick character varying, registryerrorclass_sysnick character varying, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryerrorcmp
delete from r477.registryerrorcmp
where registryerrorcmp.registry_id = p_registryerrorcmp_del.registry_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryerrorcmp_ins(INOUT registry_id bigint DEFAULT NULL::bigint, cmpclosecard_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, registryerror_desc character varying DEFAULT NULL::character varying, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registry_id, 0) = 0
then 
	insert into r477.registryerrorcmp(cmpclosecard_id, registryerrortype_id, lpusection_id, registryerror_desc, pmuser_insid, pmuser_updid, registryerrorcmp_insdt, registryerrorcmp_upddt)
	values ( cmpclosecard_id, registryerrortype_id, lpusection_id, registryerror_desc, pmuser_id, pmuser_id, now(), now())
	returning registryerrorcmp.registry_id into p_registryerrorcmp_ins.registry_id;
else
	insert into r477.registryerrorcmp(registry_id, cmpclosecard_id, registryerrortype_id, lpusection_id, registryerror_desc, pmuser_insid, pmuser_updid, registryerrorcmp_insdt, registryerrorcmp_upddt)
	values (registry_id, cmpclosecard_id, registryerrortype_id, lpusection_id, registryerror_desc, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registryerrorcmp_ins(INOUT registry_id bigint, cmpclosecard_id bigint, registryerrortype_id bigint, lpusection_id bigint, registryerror_desc character varying, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryerrorcmp_upd(INOUT registry_id bigint DEFAULT NULL::bigint, cmpclosecard_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, lpusection_id bigint DEFAULT NULL::bigint, registryerror_desc character varying DEFAULT NULL::character varying, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryerrorcmp
set cmpclosecard_id = p_registryerrorcmp_upd.cmpclosecard_id,
registryerrortype_id = p_registryerrorcmp_upd.registryerrortype_id,
lpusection_id = p_registryerrorcmp_upd.lpusection_id,
registryerror_desc = p_registryerrorcmp_upd.registryerror_desc,
pmuser_updid = pmuser_id,
registryerrorcmp_upddt = now()

where registryerrorcmp.registry_id = p_registryerrorcmp_upd.registry_id;

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


END; $$;


ALTER FUNCTION r477.p_registryerrorcmp_upd(INOUT registry_id bigint, cmpclosecard_id bigint, registryerrortype_id bigint, lpusection_id bigint, registryerror_desc character varying, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryerrorcom
delete from r477.registryerrorcom
where registryerrorcom.registry_id = p_registryerrorcom_del.registry_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryerrorcom_ins(INOUT registry_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registry_id, 0) = 0
then 
	insert into r477.registryerrorcom(registryerrortype_id, pmuser_insid, pmuser_updid, registryerrorcom_insdt, registryerrorcom_upddt)
	values ( registryerrortype_id, pmuser_id, pmuser_id, now(), now())
	returning registryerrorcom.registry_id into p_registryerrorcom_ins.registry_id;
else
	insert into r477.registryerrorcom(registry_id, registryerrortype_id, pmuser_insid, pmuser_updid, registryerrorcom_insdt, registryerrorcom_upddt)
	values (registry_id, registryerrortype_id, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registryerrorcom_ins(INOUT registry_id bigint, registryerrortype_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryerrorcom_upd(INOUT registry_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryerrorcom
set registryerrortype_id = p_registryerrorcom_upd.registryerrortype_id,
pmuser_updid = pmuser_id,
registryerrorcom_upddt = now()

where registryerrorcom.registry_id = p_registryerrorcom_upd.registry_id;

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


END; $$;


ALTER FUNCTION r477.p_registryerrorcom_upd(INOUT registry_id bigint, registryerrortype_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryerrortfoms
delete from r477.registryerrortfoms
where registryerrortfoms.registryerrortfoms_id = p_registryerrortfoms_del.registryerrortfoms_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryerrortfoms_ins(INOUT registryerrortfoms_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, registryerrortype_code character varying DEFAULT NULL::character varying, registryerrortfoms_fieldname character varying DEFAULT NULL::character varying, registryerrortfoms_baseelement character varying DEFAULT NULL::character varying, registryerrortfoms_rownum integer DEFAULT NULL::integer, registryerrortfoms_comment character varying DEFAULT NULL::character varying, registryerrortfoms_idcase integer DEFAULT NULL::integer, registry_task character varying DEFAULT NULL::character varying, registryerrortfomstype_id bigint DEFAULT NULL::bigint, registryerrortfoms_caseguid bigint DEFAULT NULL::bigint, registryerrortfoms_severity character varying DEFAULT NULL::character varying, registryerrortfomslevel_id bigint DEFAULT NULL::bigint, registryerrorclass_id bigint DEFAULT NULL::bigint, cmpclosecard_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registryerrortfoms_id, 0) = 0
then 
	insert into r477.registryerrortfoms(registry_id, evn_id, registryerrortype_id, registryerrortype_code, registryerrortfoms_fieldname, registryerrortfoms_baseelement, registryerrortfoms_rownum, registryerrortfoms_comment, registryerrortfoms_idcase, registry_task, registryerrortfomstype_id, registryerrortfoms_caseguid, registryerrortfoms_severity, registryerrortfomslevel_id, registryerrorclass_id, cmpclosecard_id, pmuser_insid, pmuser_updid, registryerrortfoms_insdt, registryerrortfoms_upddt)
	values ( registry_id, evn_id, registryerrortype_id, registryerrortype_code, registryerrortfoms_fieldname, registryerrortfoms_baseelement, registryerrortfoms_rownum, registryerrortfoms_comment, registryerrortfoms_idcase, registry_task, registryerrortfomstype_id, registryerrortfoms_caseguid, registryerrortfoms_severity, registryerrortfomslevel_id, registryerrorclass_id, cmpclosecard_id, pmuser_id, pmuser_id, now(), now())
	returning registryerrortfoms.registryerrortfoms_id into p_registryerrortfoms_ins.registryerrortfoms_id;
else
	insert into r477.registryerrortfoms(registryerrortfoms_id, registry_id, evn_id, registryerrortype_id, registryerrortype_code, registryerrortfoms_fieldname, registryerrortfoms_baseelement, registryerrortfoms_rownum, registryerrortfoms_comment, registryerrortfoms_idcase, registry_task, registryerrortfomstype_id, registryerrortfoms_caseguid, registryerrortfoms_severity, registryerrortfomslevel_id, registryerrorclass_id, cmpclosecard_id, pmuser_insid, pmuser_updid, registryerrortfoms_insdt, registryerrortfoms_upddt)
	values (registryerrortfoms_id, registry_id, evn_id, registryerrortype_id, registryerrortype_code, registryerrortfoms_fieldname, registryerrortfoms_baseelement, registryerrortfoms_rownum, registryerrortfoms_comment, registryerrortfoms_idcase, registry_task, registryerrortfomstype_id, registryerrortfoms_caseguid, registryerrortfoms_severity, registryerrortfomslevel_id, registryerrorclass_id, cmpclosecard_id, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registryerrortfoms_ins(INOUT registryerrortfoms_id bigint, registry_id bigint, evn_id bigint, registryerrortype_id bigint, registryerrortype_code character varying, registryerrortfoms_fieldname character varying, registryerrortfoms_baseelement character varying, registryerrortfoms_rownum integer, registryerrortfoms_comment character varying, registryerrortfoms_idcase integer, registry_task character varying, registryerrortfomstype_id bigint, registryerrortfoms_caseguid bigint, registryerrortfoms_severity character varying, registryerrortfomslevel_id bigint, registryerrorclass_id bigint, cmpclosecard_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryerrortfoms_upd(INOUT registryerrortfoms_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, evn_id bigint DEFAULT NULL::bigint, registryerrortype_id bigint DEFAULT NULL::bigint, registryerrortype_code character varying DEFAULT NULL::character varying, registryerrortfoms_fieldname character varying DEFAULT NULL::character varying, registryerrortfoms_baseelement character varying DEFAULT NULL::character varying, registryerrortfoms_rownum integer DEFAULT NULL::integer, registryerrortfoms_comment character varying DEFAULT NULL::character varying, registryerrortfoms_idcase integer DEFAULT NULL::integer, registry_task character varying DEFAULT NULL::character varying, registryerrortfomstype_id bigint DEFAULT NULL::bigint, registryerrortfoms_caseguid bigint DEFAULT NULL::bigint, registryerrortfoms_severity character varying DEFAULT NULL::character varying, registryerrortfomslevel_id bigint DEFAULT NULL::bigint, registryerrorclass_id bigint DEFAULT NULL::bigint, cmpclosecard_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryerrortfoms
set registry_id = p_registryerrortfoms_upd.registry_id,
evn_id = p_registryerrortfoms_upd.evn_id,
registryerrortype_id = p_registryerrortfoms_upd.registryerrortype_id,
registryerrortype_code = p_registryerrortfoms_upd.registryerrortype_code,
registryerrortfoms_fieldname = p_registryerrortfoms_upd.registryerrortfoms_fieldname,
registryerrortfoms_baseelement = p_registryerrortfoms_upd.registryerrortfoms_baseelement,
registryerrortfoms_rownum = p_registryerrortfoms_upd.registryerrortfoms_rownum,
registryerrortfoms_comment = p_registryerrortfoms_upd.registryerrortfoms_comment,
registryerrortfoms_idcase = p_registryerrortfoms_upd.registryerrortfoms_idcase,
registry_task = p_registryerrortfoms_upd.registry_task,
registryerrortfomstype_id = p_registryerrortfoms_upd.registryerrortfomstype_id,
registryerrortfoms_caseguid = p_registryerrortfoms_upd.registryerrortfoms_caseguid,
registryerrortfoms_severity = p_registryerrortfoms_upd.registryerrortfoms_severity,
registryerrortfomslevel_id = p_registryerrortfoms_upd.registryerrortfomslevel_id,
registryerrorclass_id = p_registryerrortfoms_upd.registryerrorclass_id,
cmpclosecard_id = p_registryerrortfoms_upd.cmpclosecard_id,
pmuser_updid = pmuser_id,
registryerrortfoms_upddt = now()
where registryerrortfoms.registryerrortfoms_id = p_registryerrortfoms_upd.registryerrortfoms_id;

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




END; $$;


ALTER FUNCTION r477.p_registryerrortfoms_upd(INOUT registryerrortfoms_id bigint, registry_id bigint, evn_id bigint, registryerrortype_id bigint, registryerrortype_code character varying, registryerrortfoms_fieldname character varying, registryerrortfoms_baseelement character varying, registryerrortfoms_rownum integer, registryerrortfoms_comment character varying, registryerrortfoms_idcase integer, registry_task character varying, registryerrortfomstype_id bigint, registryerrortfoms_caseguid bigint, registryerrortfoms_severity character varying, registryerrortfomslevel_id bigint, registryerrorclass_id bigint, cmpclosecard_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryerrortype
delete from r477.registryerrortype
where registryerrortype.registryerrortype_id = p_registryerrortype_del.registryerrortype_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryerrortype_ins(INOUT registryerrortype_id bigint DEFAULT NULL::bigint, registryerrortype_code character varying DEFAULT NULL::character varying, registryerrortype_name character varying DEFAULT NULL::character varying, registryerrortype_descr character varying DEFAULT NULL::character varying, registryerrortype_sysnick character varying DEFAULT NULL::character varying, registryerrorclass_id bigint DEFAULT NULL::bigint, registryerrortype_isuser bigint DEFAULT NULL::bigint, registryerrortype_iscrit bigint DEFAULT NULL::bigint, registryfield_percent double precision DEFAULT NULL::double precision, registrytype_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registryerrortype_id, 0) = 0
then 
	insert into r477.registryerrortype(registryerrortype_code, registryerrortype_name, registryerrortype_descr, registryerrortype_sysnick, registryerrorclass_id, registryerrortype_isuser, registryerrortype_iscrit, registryfield_percent, registrytype_id, pmuser_insid, pmuser_updid, registryerrortype_insdt, registryerrortype_upddt)
	values ( registryerrortype_code, registryerrortype_name, registryerrortype_descr, registryerrortype_sysnick, registryerrorclass_id, registryerrortype_isuser, registryerrortype_iscrit, registryfield_percent, registrytype_id, pmuser_id, pmuser_id, now(), now())
	returning registryerrortype.registryerrortype_id into p_registryerrortype_ins.registryerrortype_id;
else
	insert into r477.registryerrortype(registryerrortype_id, registryerrortype_code, registryerrortype_name, registryerrortype_descr, registryerrortype_sysnick, registryerrorclass_id, registryerrortype_isuser, registryerrortype_iscrit, registryfield_percent, registrytype_id, pmuser_insid, pmuser_updid, registryerrortype_insdt, registryerrortype_upddt)
	values (registryerrortype_id, registryerrortype_code, registryerrortype_name, registryerrortype_descr, registryerrortype_sysnick, registryerrorclass_id, registryerrortype_isuser, registryerrortype_iscrit, registryfield_percent, registrytype_id, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registryerrortype_ins(INOUT registryerrortype_id bigint, registryerrortype_code character varying, registryerrortype_name character varying, registryerrortype_descr character varying, registryerrortype_sysnick character varying, registryerrorclass_id bigint, registryerrortype_isuser bigint, registryerrortype_iscrit bigint, registryfield_percent double precision, registrytype_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryerrortype_upd(INOUT registryerrortype_id bigint DEFAULT NULL::bigint, registryerrortype_code character varying DEFAULT NULL::character varying, registryerrortype_name character varying DEFAULT NULL::character varying, registryerrortype_descr character varying DEFAULT NULL::character varying, registryerrortype_sysnick character varying DEFAULT NULL::character varying, registryerrorclass_id bigint DEFAULT NULL::bigint, registryerrortype_isuser bigint DEFAULT NULL::bigint, registryerrortype_iscrit bigint DEFAULT NULL::bigint, registryfield_percent double precision DEFAULT NULL::double precision, registrytype_id bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryerrortype
set registryerrortype_code = p_registryerrortype_upd.registryerrortype_code,
registryerrortype_name = p_registryerrortype_upd.registryerrortype_name,
registryerrortype_descr = p_registryerrortype_upd.registryerrortype_descr,
registryerrortype_sysnick = p_registryerrortype_upd.registryerrortype_sysnick,
registryerrorclass_id = p_registryerrortype_upd.registryerrorclass_id,
registryerrortype_isuser = p_registryerrortype_upd.registryerrortype_isuser,
registryerrortype_iscrit = p_registryerrortype_upd.registryerrortype_iscrit,
registryfield_percent = p_registryerrortype_upd.registryfield_percent,
registrytype_id = p_registryerrortype_upd.registrytype_id,
pmuser_updid = pmuser_id,
registryerrortype_upddt = now()
where registryerrortype.registryerrortype_id = p_registryerrortype_upd.registryerrortype_id;

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




END; $$;


ALTER FUNCTION r477.p_registryerrortype_upd(INOUT registryerrortype_id bigint, registryerrortype_code character varying, registryerrortype_name character varying, registryerrortype_descr character varying, registryerrortype_sysnick character varying, registryerrorclass_id bigint, registryerrortype_isuser bigint, registryerrortype_iscrit bigint, registryfield_percent double precision, registrytype_id bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registrygrouplink
delete from r477.registrygrouplink
where registrygrouplink.registrygrouplink_id = p_registrygrouplink_del.registrygrouplink_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registrygrouplink_ins(INOUT registrygrouplink_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, registry_pid bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

if coalesce(registrygrouplink_id, 0) = 0
then 
	insert into r477.registrygrouplink(registry_id, registry_pid, pmuser_insid, pmuser_updid, registrygrouplink_insdt, registrygrouplink_upddt)
	values ( registry_id, registry_pid, pmuser_id, pmuser_id, now(), now())
	returning registrygrouplink.registrygrouplink_id into p_registrygrouplink_ins.registrygrouplink_id;
else
	insert into r477.registrygrouplink(registrygrouplink_id, registry_id, registry_pid, pmuser_insid, pmuser_updid, registrygrouplink_insdt, registrygrouplink_upddt)
	values (registrygrouplink_id, registry_id, registry_pid, pmuser_id, pmuser_id, now(), now());
end if;
EXCEPTION
	when others then error_code:=SQLSTATE; error_message:=SQLERRM;


END; $$;


ALTER FUNCTION r477.p_registrygrouplink_ins(INOUT registrygrouplink_id bigint, registry_id bigint, registry_pid bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrygrouplink_upd(INOUT registrygrouplink_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, registry_pid bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registrygrouplink
set registry_id = p_registrygrouplink_upd.registry_id,
registry_pid = p_registrygrouplink_upd.registry_pid,
pmuser_updid = pmuser_id,
registrygrouplink_upddt = now()
where registrygrouplink.registrygrouplink_id = p_registrygrouplink_upd.registrygrouplink_id;

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




END; $$;


ALTER FUNCTION r477.p_registrygrouplink_upd(INOUT registrygrouplink_id bigint, registry_id bigint, registry_pid bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrylpubuilding_del(p_registrylpubuilding_id bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
BEGIN
	
  delete from r477.registrylpubuilding where registrylpubuilding_id = p_registrylpubuilding_id
  ;

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


ALTER FUNCTION r477.p_registrylpubuilding_del(p_registrylpubuilding_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrylpubuilding_ins(p_registry_id bigint, p_lpubuilding_id bigint, p_registryqueue_id bigint, p_pmuser_id bigint, INOUT registrylpubuilding_id bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE
 
BEGIN
 
 if p_pmuser_id = 0 then p_pmuser_id = null; end if;
 
 if coalesce(RegistryLpuBuilding_id, 0) = 0 then 
  
      insert into r477.registrylpubuilding (Registry_id, LpuBuilding_id, RegistryQueue_id, pmUser_insID, pmUser_updID, RegistryLpuBuilding_insDT, RegistryLpuBuilding_updDT)
      values (p_Registry_id, p_LpuBuilding_id, p_RegistryQueue_id, p_pmUser_id, p_pmUser_id, now(), now())
      returning registrylpubuilding.registrylpubuilding_id into registrylpubuilding_id
      ;
  
  else
  
      insert into r477.registrylpubuilding (RegistryLpuBuilding_id, Registry_id, LpuBuilding_id, RegistryQueue_id, pmUser_insID, pmUser_updID, RegistryLpuBuilding_insDT, RegistryLpuBuilding_updDT)
      values (RegistryLpuBuilding_id, p_Registry_id, p_LpuBuilding_id, p_RegistryQueue_id, p_pmUser_id, p_pmUser_id, now(), now())
      ;
      
  end if;
 

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


ALTER FUNCTION r477.p_registrylpubuilding_ins(p_registry_id bigint, p_lpubuilding_id bigint, p_registryqueue_id bigint, p_pmuser_id bigint, INOUT registrylpubuilding_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrylpusection_del(p_registrylpusection_id bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
BEGIN
	
  delete from r477.registrylpusection where registrylpusection_id = p_registrylpusection_id
  ;

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


ALTER FUNCTION r477.p_registrylpusection_del(p_registrylpusection_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrylpusection_ins(p_registry_id bigint, p_lpusection_id bigint, p_registryqueue_id bigint, p_pmuser_id bigint, INOUT registrylpusection_id bigint DEFAULT NULL::bigint, INOUT error_code integer DEFAULT NULL::integer, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
DECLARE
 
BEGIN
 
 if p_pmuser_id = 0 then p_pmuser_id = null; end if;
 
 if coalesce(RegistryLpuSection_id, 0) = 0 then 
  
      insert into r477.registrylpusection (Registry_id, LpuSection_id, RegistryQueue_id, pmUser_insID, pmUser_updID, RegistryLpuSection_insDT, RegistryLpuSection_updDT)
      values (p_Registry_id, p_LpuSection_id, p_RegistryQueue_id, p_pmUser_id, p_pmUser_id, now(), now())
      returning registrylpusection.registrylpusection_id into registrylpusection_id
      ;
  
  else
  
      insert into r477.registrylpusection (RegistryLpuSection_id, Registry_id, LpuSection_id, RegistryQueue_id, pmUser_insID, pmUser_updID, RegistryLpuSection_insDT, RegistryLpuSection_updDT)
      values (RegistryLpuSection_id, p_Registry_id, p_LpuSection_id, p_RegistryQueue_id, p_pmUser_id, p_pmUser_id, now(), now())
      ;
      
  end if;
 

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


ALTER FUNCTION r477.p_registrylpusection_ins(p_registry_id bigint, p_lpusection_id bigint, p_registryqueue_id bigint, p_pmuser_id bigint, INOUT registrylpusection_id bigint, INOUT error_code integer, INOUT error_message character varying) OWNER TO developer_rep;

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

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

begin

--autogen
--project promed
--delete from r477.registryqueue
delete from r477.registryqueue
where registryqueue.registryqueue_id = p_registryqueue_del.registryqueue_id;

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


end; $$;


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

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

CREATE FUNCTION r477.p_registryqueue_ins(INOUT p_registryqueue_id bigint DEFAULT NULL::bigint, INOUT p_registryqueue_position bigint DEFAULT NULL::bigint, p_registry_id bigint DEFAULT NULL::bigint, p_registrytype_id bigint DEFAULT NULL::bigint, p_lpu_id bigint DEFAULT NULL::bigint, p_lpubuilding_id bigint DEFAULT NULL::bigint, p_registry_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_orgsmo_id bigint DEFAULT NULL::bigint, p_lpuunitset_id bigint DEFAULT NULL::bigint, p_registry_num character varying DEFAULT NULL::character varying, p_registry_accdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registrystatus_id bigint DEFAULT NULL::bigint, p_org_mid bigint DEFAULT NULL::bigint, p_orgrschet_mid bigint DEFAULT NULL::bigint, p_katnasel_id bigint DEFAULT NULL::bigint, p_dispclass_id bigint DEFAULT NULL::bigint, p_orgrschet_id bigint DEFAULT NULL::bigint, p_reform integer DEFAULT NULL::integer, p_registry_isrepeated bigint DEFAULT NULL::bigint, p_registry_rid bigint DEFAULT NULL::bigint, p_paytype_id bigint DEFAULT NULL::bigint, p_registry_iszno bigint DEFAULT NULL::bigint, p_lpu_cid bigint DEFAULT NULL::bigint, p_registry_counterr bigint DEFAULT NULL::bigint, p_pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$
declare
	_registryqueuehistory_isupdate integer;
begin


if p_pmuser_id = 0
	then p_pmuser_id := null; end if;

if coalesce(p_registryqueue_id, 0) = 0
then 
	insert into r477.registryqueue(registry_id, registrytype_id, lpu_id, registry_begdate, registry_enddate, orgsmo_id, lpuunitset_id, registry_num, registry_accdate, registrystatus_id, org_mid, orgrschet_mid, katnasel_id, dispclass_id, orgrschet_id, reform, registry_isrepeated, registry_rid, paytype_id, registry_iszno, registry_counterr, lpubuilding_id, pmuser_insid, pmuser_updid, registryqueue_insdt, registryqueue_upddt, lpu_cid)
	values (p_registry_id, p_registrytype_id, p_lpu_id, p_registry_begdate, p_registry_enddate, p_orgsmo_id, p_lpuunitset_id, p_registry_num, p_registry_accdate, p_registrystatus_id, p_org_mid, p_orgrschet_mid, p_katnasel_id, p_dispclass_id, p_orgrschet_id, p_reform, p_registry_isrepeated, p_registry_rid, p_paytype_id, p_registry_iszno, p_registry_counterr, p_lpubuilding_id, p_pmuser_id, p_pmuser_id, now(), now(), p_lpu_cid)
	returning registryqueue.registryqueue_id into p_registryqueue_ins.p_registryqueue_id;
else
	insert into r477.registryqueue(registryqueue_id, registry_id, registrytype_id, lpu_id, registry_begdate, registry_enddate, orgsmo_id, lpuunitset_id, registry_num, registry_accdate, registrystatus_id, org_mid, orgrschet_mid, katnasel_id, dispclass_id, orgrschet_id, reform, registry_isrepeated, registry_rid, paytype_id, registry_iszno, registry_counterr, lpubuilding_id, pmuser_insid, pmuser_updid, registryqueue_insdt, registryqueue_upddt, lpu_cid)
	values (p_registryqueue_id, p_registry_id, p_registrytype_id, p_lpu_id, p_registry_begdate, p_registry_enddate, p_orgsmo_id, p_lpuunitset_id, p_registry_num, p_registry_accdate, p_registrystatus_id, p_org_mid, p_orgrschet_mid, p_katnasel_id, p_dispclass_id, p_orgrschet_id, p_reform, p_registry_isrepeated, p_registry_rid, p_paytype_id, p_registry_iszno, p_registry_counterr, p_lpubuilding_id, p_pmuser_id, p_pmuser_id, now(), now(), p_lpu_cid);
end if;


p_registryqueue_position := (select count(*) from r477.registryqueue);

if p_registry_id is null
    then
        _registryqueuehistory_isupdate := 1;
    else
        _registryqueuehistory_isupdate := 2;
end if;


insert into r477.registryqueuehistory (registryqueuehistory_id, registry_id, registrytype_id, lpu_id, orgrschet_id, registry_begdate, registry_enddate, katnasel_id, registry_num, registry_accdate, registryqueuehistory_isupdate, registryqueue_position, pmuser_insid, pmuser_updid, registryqueuehistory_insdt, registryqueuehistory_upddt,orgsmo_id,registry_isrepeated,paytype_id, lpu_cid)
values (p_registryqueue_id, p_registry_id, p_registrytype_id, p_lpu_id, p_orgrschet_id, p_registry_begdate, p_registry_enddate, p_katnasel_id, p_registry_num, p_registry_accdate, _registryqueuehistory_isupdate, p_registryqueue_position, p_pmuser_id, p_pmuser_id, getdate(), getdate(), p_orgsmo_id,p_registry_isrepeated,p_paytype_id, p_lpu_cid)
;

if p_registry_id is not null then
    update r477.registry r
    set 
        registry_exportpath = null, registry_xmlexportpath = null, registry_xmlexpdt = null
    where r.registry_id = p_registry_id
    ;
end if;


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


END;
$$;


ALTER FUNCTION r477.p_registryqueue_ins(INOUT p_registryqueue_id bigint, INOUT p_registryqueue_position bigint, p_registry_id bigint, p_registrytype_id bigint, p_lpu_id bigint, p_lpubuilding_id bigint, p_registry_begdate timestamp without time zone, p_registry_enddate timestamp without time zone, p_orgsmo_id bigint, p_lpuunitset_id bigint, p_registry_num character varying, p_registry_accdate timestamp without time zone, p_registrystatus_id bigint, p_org_mid bigint, p_orgrschet_mid bigint, p_katnasel_id bigint, p_dispclass_id bigint, p_orgrschet_id bigint, p_reform integer, p_registry_isrepeated bigint, p_registry_rid bigint, p_paytype_id bigint, p_registry_iszno bigint, p_lpu_cid bigint, p_registry_counterr bigint, p_pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registryqueue_upd(INOUT registryqueue_id bigint DEFAULT NULL::bigint, registry_id bigint DEFAULT NULL::bigint, registrytype_id bigint DEFAULT NULL::bigint, lpu_id bigint DEFAULT NULL::bigint, registry_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, registry_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, orgsmo_id bigint DEFAULT NULL::bigint, lpuunitset_id bigint DEFAULT NULL::bigint, registry_num character varying DEFAULT NULL::character varying, registry_accdate timestamp without time zone DEFAULT NULL::timestamp without time zone, registrystatus_id bigint DEFAULT NULL::bigint, org_mid bigint DEFAULT NULL::bigint, orgrschet_mid bigint DEFAULT NULL::bigint, katnasel_id bigint DEFAULT NULL::bigint, dispclass_id bigint DEFAULT NULL::bigint, orgrschet_id bigint DEFAULT NULL::bigint, reform integer DEFAULT NULL::integer, registry_isrepeated bigint DEFAULT NULL::bigint, registry_rid bigint DEFAULT NULL::bigint, paytype_id bigint DEFAULT NULL::bigint, registry_iszno bigint DEFAULT NULL::bigint, registry_counterr bigint DEFAULT NULL::bigint, pmuser_id bigint DEFAULT NULL::bigint, INOUT error_code character varying DEFAULT NULL::character varying, INOUT error_message character varying DEFAULT NULL::character varying) RETURNS record
    LANGUAGE plpgsql
    AS $$

begin

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

update r477.registryqueue
set registry_id = p_registryqueue_upd.registry_id,
registrytype_id = p_registryqueue_upd.registrytype_id,
lpu_id = p_registryqueue_upd.lpu_id,
registry_begdate = p_registryqueue_upd.registry_begdate,
registry_enddate = p_registryqueue_upd.registry_enddate,
orgsmo_id = p_registryqueue_upd.orgsmo_id,
lpuunitset_id = p_registryqueue_upd.lpuunitset_id,
registry_num = p_registryqueue_upd.registry_num,
registry_accdate = p_registryqueue_upd.registry_accdate,
registrystatus_id = p_registryqueue_upd.registrystatus_id,
org_mid = p_registryqueue_upd.org_mid,
orgrschet_mid = p_registryqueue_upd.orgrschet_mid,
katnasel_id = p_registryqueue_upd.katnasel_id,
dispclass_id = p_registryqueue_upd.dispclass_id,
orgrschet_id = p_registryqueue_upd.orgrschet_id,
reform = p_registryqueue_upd.reform,
registry_isrepeated = p_registryqueue_upd.registry_isrepeated,
registry_rid = p_registryqueue_upd.registry_rid,
paytype_id = p_registryqueue_upd.paytype_id,
registry_iszno = p_registryqueue_upd.registry_iszno,
registry_counterr = p_registryqueue_upd.registry_counterr,
pmuser_updid = pmuser_id,
registryqueue_upddt = now()
where registryqueue.registryqueue_id = p_registryqueue_upd.registryqueue_id;

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




END; $$;


ALTER FUNCTION r477.p_registryqueue_upd(INOUT registryqueue_id bigint, registry_id bigint, registrytype_id bigint, lpu_id bigint, registry_begdate timestamp without time zone, registry_enddate timestamp without time zone, orgsmo_id bigint, lpuunitset_id bigint, registry_num character varying, registry_accdate timestamp without time zone, registrystatus_id bigint, org_mid bigint, orgrschet_mid bigint, katnasel_id bigint, dispclass_id bigint, orgrschet_id bigint, reform integer, registry_isrepeated bigint, registry_rid bigint, paytype_id bigint, registry_iszno bigint, registry_counterr bigint, pmuser_id bigint, INOUT error_code character varying, INOUT error_message character varying) OWNER TO developer_rep;

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

CREATE FUNCTION r477.p_registrysmp_gen(p_registry_id bigint DEFAULT NULL::bigint, p_lpu_id bigint DEFAULT NULL::bigint, p_katnasel_id bigint DEFAULT NULL::bigint, p_orgsmo_id bigint DEFAULT NULL::bigint, p_lpuunitset_id bigint DEFAULT NULL::bigint, p_registry_begdate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registry_enddate timestamp without time zone DEFAULT NULL::timestamp without time zone, p_registrystatus_id bigint DEFAULT NULL::bigint, p_pmuser_id bigint DEFAULT NULL::bigint) RETURNS void
    LANGUAGE plpgsql
    AS $$
declare 
	v_object_log varchar(50) = 'Registry/' || RTrim(cast(p_registrysmp_gen.p_Registry_id as varchar(20)));
begin	
	perform p_Log_set( v_object_log, 'Начало апдейта по СМП');

	-- Обнуляем путь выгруженного файла при переформировании
	update r477.Registry  set 
		Registry_ExportPath = null
	where Registry.Registry_id = p_registrysmp_gen.Registry_id;

	-- Проставляем при признак вхождения в реестр в Нет
	-- но только у тех реестров, которые окончательные (у предварительных такая функция ошибочна)
	update dbo.CmpCloseCard  -- #79283
		set
			 CmpCloseCard_IsInReg = 1
		from r477.RegistryDataCmp as rd 
		where rd.CmpCloseCard_id = CmpCloseCard.CmpCloseCard_id
			and rd.Registry_id = p_registrysmp_gen.p_Registry_id;

-- Удаляем нафик все что создано было до этого в этом реестре
delete from r477.RegistryDataCmp
 where Registry_id = p_Registry_id;
 
delete from r477.RegistryUsluga
 where Registry_id = p_Registry_id;

delete from r477.RegistryDataTemp
 where Registry_id = p_Registry_id;

delete from r477.RegistryErrorTFOMS
 where Registry_id = p_Registry_id;

perform p_Log_set( v_object_log, 'Начало основного инсерта');

perform r477.p_registry_smp_sql  p_Registry_id,p_Lpu_id,p_KatNasel_id,p_OrgSmo_id,p_LpuUnitSet_id,p_Registry_begDate,p_Registry_endDate,p_RegistryStatus_id,p_pmUser_id;


perform p_Log_set (p_object_log, 'Формирование списка безполисных пациентов...');
  -- Очищаем все что без полиса
  delete from r477.RegistryCmpNoPolis 
    where Registry_id = p_Registry_id;
	
insert into r477.RegistryCmpNoPolis (
	Registry_id,
	Evn_id,
	Person_id,
	Evn_Code,
	Person_Surname,
	Person_Firname,
	Person_Secname,
	Person_Birthday,
	pmUser_insID,
	pmUser_updID,
	RegistryNoPolis_insDT,
	RegistryNoPolis_updDT
	)
	select
	Registry_id,
	Evn_id,
	Person_id,
	NumCard,
	Person_Surname,
	substring(Person_Firname, 1, 15),
	substring(Person_Secname, 1, 15),
	Person_Birthday,
	rd.pmUser_insID,
	rd.pmUser_updID,
	RegistryData_insDT,
	RegistryData_updDT
	from r477.RegistryDataTemp rd
	left join Polis on Polis.Polis_id=rd.polis_id
	left join OrgSmo on OrgSMO.OrgSMO_id=Polis.orgsmo_id
	where Registry_id = p_Registry_id and (((rd.Polis_Num is null or length(rtrim(rd.Polis_Num)) = 0)
	or OrgSMO.Orgsmo_f002smocod is null
	or Polis.PolisType_id is null)
	--and not (dbo.Age2(rd.Person_BirthDay, rd.Evn_setDate) = 0 and dbo.AgeYMD (rd.Person_BirthDay,rd.Evn_setDate, 2) <= 3)
	);
delete from r477.RegistryDataTemp  
      where Registry_id = p_Registry_id   
      and Evn_id in  (
         select rp.Evn_id from r477.RegistryCmpNoPolis rp  
         where rp.Registry_id = RegistryDataTemp .Registry_id
        );
-- вставка полученных в реестр
insert into r477.RegistryDataCmp(
--Number,
--[Guid],
CmpCloseCard_id,
CmpCloseCard_sid,
Registry_id,
RegistryDataCmp_RowNum,
NumCard,
--Evn_rid,
Person_id,
LpuSection_id,
LpuSection_Code,
LpuSectionProfile_id,
LpuSectionProfile_Code,
MedPersonal_id,
MedPersonal_Code,
MedPersonal_FIO,
RegistryDataCmp_Tariff,
--RegistryData_KdFact,
--RegistryData_KdPlan,
--RegistryData_KdPay,
RegistryDataCmp_UKLSum,
RegistryDataCmp_ItogSum,
RegistryDataCmp_isPersFin,
RegistryDataCmp_EI2,
RegistryDataCmp_UKL,
Polis_id,
Polis_Ser,
Polis_Num,
Polis_begDate,
Polis_endDate,
OrgSmo_id,
MedSpec_id,
OMSSprTerr_id,
OMSSprTerr_Code,
Address_id,
Diag_id,
--VizitType_id,
CmpResult_id,
Evn_disDate,
--Evn_updDate,
pmUser_insID,
pmUser_updID,
RegistryDataCmp_insDT,
RegistryDataCmp_updDT,
UslugaComplex_id,
Evn_setDate
)
select
--ROW_NUMBER() over(order by Evn_rid, Evn_id) as Number,
--Evn_id as Number, 
--newid() as [Guid], 
Evn_id,
Evn_id,
Registry_id,
RegistryData_RowNum,
NumCard,
--Evn_rid,
Person_id,
LpuSection_id,
LpuSection_Code,
LpuSectionProfile_id,
LpuSectionProfile_Code,
MedPersonal_id,
MedPersonal_Code,
MedPersonal_FIO,
RegistryData_Tariff,
--RegistryData_KdFact,
--RegistryData_KdPlan,
--RegistryData_KdPay,
RegistryData_UKLSum,
RegistryData_ItogSum,
RegistryDataTemp_isPersFin,
RegistryData_EI2,
RegistryData_UKL,
Polis_id,
Polis_Ser,
Polis_Num,
Polis_begDate,
Polis_endDate,
OrgSmo_id,
MedSpec_id,
OMSSprTerr_id,
OMSSprTerr_Code,
Address_id,
Diag_id,
--VizitType_id,
ResultClass_id,
Evn_disDate,
--Evn_updDate,
pmUser_insID,
pmUser_updID,
RegistryData_insDT,
RegistryData_updDT,
UslugaComplex_id,
Evn_setDate
from r477.RegistryDataTemp rd
where Registry_id = p_Registry_id
order by Evn_rid, rd.Evn_id;
 
-- #123886 
-- вставка услуг тромболизиса как случаев

insert into r477.RegistryDataCmp(
--Number,
--[Guid],
CmpCloseCard_id,
CmpCloseCard_sid,
Registry_id,
RegistryDataCmp_RowNum,
NumCard,
--Evn_rid,
Person_id,
LpuSection_id,
LpuSection_Code,
LpuSectionProfile_id,
LpuSectionProfile_Code,
MedPersonal_id,
MedPersonal_Code,
MedPersonal_FIO,
RegistryDataCmp_Tariff,
--RegistryData_KdFact,
--RegistryData_KdPlan,
--RegistryData_KdPay,
RegistryDataCmp_UKLSum,
RegistryDataCmp_ItogSum,
RegistryDataCmp_isPersFin,
RegistryDataCmp_EI2,
RegistryDataCmp_UKL,
Polis_id,
Polis_Ser,
Polis_Num,
Polis_begDate,
Polis_endDate,
OrgSmo_id,
MedSpec_id,
OMSSprTerr_id,
OMSSprTerr_Code,
Address_id,
Diag_id,
--VizitType_id,
CmpResult_id,
Evn_disDate,
--Evn_updDate,
pmUser_insID,
pmUser_updID,
RegistryDataCmp_insDT,
RegistryDataCmp_updDT,
UslugaComplex_id,
Evn_setDate
)
select
--ROW_NUMBER() over(order by Evn_rid, Evn_id) as Number,
--Evn_id as Number, 
--newid() as [Guid], 
Evn_id,
CmpCallCardUsluga.CmpCallCardUsluga_id as CmpCloseCard_sid,
Registry_id,
RegistryData_RowNum,
NumCard,
--Evn_rid,
Person_id,
rd.LpuSection_id,
LpuSection_Code,
rd.LpuSectionProfile_id,
LpuSectionProfile_Code,
MedPersonal_id,
MedPersonal_Code,
MedPersonal_FIO,
--RegistryData_Tariff,
Tariff.UslugaComplexTariff_Tariff,
--RegistryData_KdFact,
--RegistryData_KdPlan,
--RegistryData_KdPay,
RegistryData_UKLSum,
Tariff.UslugaComplexTariff_Tariff as RegistryData_ItogSum,
null::varchar,
RegistryData_EI2,
RegistryData_UKL,
Polis_id,
Polis_Ser,
Polis_Num,
Polis_begDate,
Polis_endDate,
OrgSmo_id,
MedSpec_id,
OMSSprTerr_id,
OMSSprTerr_Code,
Address_id,
Diag_id,
--VizitType_id,
ResultClass_id,
Evn_disDate,
--Evn_updDate,
rd.pmUser_insID,
rd.pmUser_updID,
RegistryData_insDT,
RegistryData_updDT,
--CmpCallCardUsluga.UslugaComplex_id,
CmpCallCardUsluga.UslugaComplex_id,
Evn_setDate
from r477.RegistryDataTemp rd
inner join v_CmpCallCardUsluga CmpCallCardUsluga on CmpCallCardUsluga.CmpCallCard_id = rd.Evn_rid
inner join v_UslugaComplex UslugaComplex on UslugaComplex.UslugaComplex_id = CmpCallCardUsluga.UslugaComplex_id
inner join v_UslugaComplexAttribute UCA on  UslugaComplex.UslugaComplex_id=UCA.UslugaComplex_id
  and UslugaComplexAttribute_begDate<=rd.Evn_disDate
  and (UslugaComplexAttribute_endDate >=rd.Evn_disDate or UslugaComplexAttribute_endDate is null)
inner join v_UslugaComplexAttributetype UCAT on UCA.UslugaComplexAttributetype_id=UCAT.UslugaComplexAttributetype_id
	and UslugaComplexAttributeType_SysNick in ('smpcalltrombolizis') -- #160664

left join lateral (
	select UslugaComplexTariff_id,UslugaComplexTariff_Tariff
	from UslugaComplexTariff
	where 
		UslugaComplexTariff.UslugaComplex_id = CmpCallCardUsluga.UslugaComplex_id
		and UslugaComplexTariff.UslugaComplexTariff_begDate <= rd.Evn_disDate
		and (UslugaComplexTariff.UslugaComplexTariff_endDate is null or UslugaComplexTariff.UslugaComplexTariff_endDate >=rd.Evn_disDate)
		--and  UslugaComplexAttributeType_SysNick='smpcalltrombolizis'
	order by UslugaComplexTariff.UslugaComplexTariff_begDate desc
	limit 1
) Tariff on true
where Registry_id = p_Registry_id
order by Evn_rid, Evn_id;

perform p_Log_set( v_object_log, 'Конец вставки полученных в регистр');	

update CmpCloseCard
set
	 CmpCloseCard_IsInReg = 2
from r477.RegistryDataCmp
where RegistryDataCmp.CmpCloseCard_id = CmpCloseCard.CmpCloseCard_id
and Registry_id = p_Registry_id;

perform p_Log_set( v_object_log, 'Вставка ошибок');	
perform r477.p_registry_smp_seterrors 
 p_Registry_id,
 p_Lpu_id,
 p_pmUser_id,
 0,
 1;
 
perform p_Log_set( v_object_log, 'Счет суммы');	

perform r477.p_registry_smp_recount(
		p_Registry_id,
		p_Lpu_id,
		p_OrgSmo_id,
		p_LpuUnitSet_id,
		p_Registry_begDate,
		p_Registry_endDate,
		p_RegistryStatus_id,
		p_pmUser_id,
		1,
		1
	);
delete from r477.RegistryDataTemp where Registry_id = p_Registry_id;
update r477.Registry set Registry_IsNeedReform=1 where Registry.Registry_id=p_Registry_id;

perform p_Log_set( v_object_log, 'Последние апдейты и все');

END; 
$$;


ALTER FUNCTION r477.p_registrysmp_gen(p_registry_id bigint, p_lpu_id bigint, p_katnasel_id bigint, p_orgsmo_id bigint, p_lpuunitset_id bigint, p_registry_begdate timestamp without time zone, p_registry_enddate timestamp without time zone, p_registrystatus_id bigint, p_pmuser_id bigint) OWNER TO developer_rep;

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

CREATE FUNCTION r477.raise_error(p1_text text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    
    RAISE EXCEPTION '%',p1_text;     
 
END;
$$;


ALTER FUNCTION r477.raise_error(p1_text text) OWNER TO developer_rep;

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

CREATE FUNCTION r477.registry_processing_region() RETURNS void
    LANGUAGE plpgsql
    AS $$
declare
	
     _Lpu_Nick varchar(100);
     _Error_Code varchar;
	 _Error_Message varchar(4000);
     _Registry_insDT timestamp;
	 _Registry_updDT timestamp;
     
     _beg_dt timestamp;
     _end_dt timestamp; 
     _r record;
begin
	if (select count(*)	from pg_catalog.pg_stat_activity where strpos(query,'r477.registry_processing_region')>0 
			and datname=current_database () and state='active' and pid <> pg_backend_pid() )>0
    then
       	raise notice 'return without execute!(Не завершен текущий процесс)';
        return;
    end if;
	

	for _r in 
		select RegistryQueue_id, Registry_id,RegistryType_id,Lpu_id,LpuUnitSet_id,
		 Registry_begDate,Registry_endDate,OrgSMO_id,Registry_Num,Registry_accDate,
		 pmUser_insID as pmUser_id,Org_mid,OrgRSchet_mid,KatNasel_id,DispClass_id,OrgRSchet_id,
		 Registry_IsRepeated,Registry_rid,PayType_id,Registry_IsZNO,Registry_CountErr,LpuBuilding_id,
		 lpu_cid,registry_isfap
		from r477.v_RegistryQueue rq
		order by 
        	--упавшие счета в конец очереди, чтобы не блокировали остальные 
            exists (
            	select 1 from r477.v_RegistryQueueHistory rqh 
                where rq.registryqueue_id = rqh.registryqueuehistory_id and rqh.error_message is not null 
                order by rqh.registryqueuehistory_id 
                limit 1 
            ), 
            RegistryQueue_Position
		limit 3
	loop	
		
		update r477.RegistryQueue  set
			reform=2,
			RegistryQueue_updDT = getdate()
		where RegistryQueue_id = _r.RegistryQueue_id;
		
		select Lpu_Nick into _Lpu_Nick from v_Lpu where Lpu_id = _r.Lpu_id;
		raise notice 'processing registry on %, registry_id = %',_Lpu_Nick, _r.Registry_id;
		
		if _r.RegistryQueue_id is not null
		then
			
        	_beg_dt = clock_timestamp();
            
            update r477.RegistryQueueHistory set
              RegistryQueueHistory_begDT = _beg_dt,
              RegistryQueueHistory_updDT = _beg_dt
			where RegistryQueueHistory_id = _r.RegistryQueue_id
            ;
		
			if _r.Registry_id is null
			then
				select fnc.p_Registry_id,fnc.p_Error_Code,fnc.p_Error_Message into _r.Registry_id,_Error_Code,_Error_Message from  r477.p_Registry_ins (
				p_Registry_id := _r.Registry_id,
				p_RegistryType_id := _r.RegistryType_id,
				p_Lpu_id := _r.Lpu_id,
				p_LpuUnitSet_id := _r.LpuUnitSet_id,
				p_Registry_begDate := _r.Registry_begDate,
				p_Registry_endDate := _r.Registry_endDate,
				p_OrgSMO_id := _r.OrgSMO_id,
				p_Registry_Num := _r.Registry_Num,
				p_Registry_accDate := _r.Registry_accDate,
				p_RegistryStatus_id := 3::bigint,
				p_Registry_Sum := 0::numeric,
				p_Registry_IsActive := 2::bigint,
				p_Registry_ErrorCount := null::integer,
				p_Registry_ErrorCommonCount := null::integer,
				p_Registry_RecordCount := null::integer,
				p_pmUser_id := _r.pmUser_id,
				p_Org_mid :=_r.Org_mid,
				p_OrgRSchet_mid := _r.OrgRSchet_mid,
				p_KatNasel_id := _r.KatNasel_id,
				p_DispClass_id := _r.DispClass_id,
				p_OrgRSchet_id := _r.OrgRSchet_id,
				p_Registry_IsRepeated := _r.Registry_IsRepeated,
				p_Registry_rid := _r.Registry_rid,
				p_PayType_id := _r.PayType_id,
				p_Registry_IsZNO := _r.Registry_IsZNO,
                p_LpuBuilding_id := _r.LpuBuilding_id,
                p_lpu_cid := _r.lpu_cid,
                p_registry_isfap := _r.registry_isfap,
                p_registryqueue_id := _r.RegistryQueue_id                
                ) fnc
                ; 
			
			else
				select fnc.p_Registry_id,fnc.p_Error_Code,fnc.p_Error_Message into _r.Registry_id,_Error_Code,_Error_Message from r477.p_Registry_upd (
				p_Registry_id := _r.Registry_id ,
				p_RegistryType_id := _r.RegistryType_id,
				p_Lpu_id := _r.Lpu_id,
				p_LpuUnitSet_id := _r.LpuUnitSet_id,
				p_Registry_begDate := _r.Registry_begDate,
				p_Registry_endDate := _r.Registry_endDate,
				p_OrgSMO_id := _r.OrgSMO_id,
				p_Registry_Num := _r.Registry_Num,
				p_Registry_accDate := _r.Registry_accDate,
				p_RegistryStatus_id := 3::bigint,
				p_Registry_Sum := 0::numeric,
				p_Registry_IsActive := 2::bigint,
				p_Registry_ErrorCount := null::integer,
				p_Registry_ErrorCommonCount := null::integer,
				p_Registry_RecordCount := null::integer,
				p_pmUser_id := _r.pmUser_id,
				p_Org_mid := _r.Org_mid,
				p_OrgRSchet_mid := _r.OrgRSchet_mid,
				p_KatNasel_id := _r.KatNasel_id,
				p_DispClass_id := _r.DispClass_id,
				p_OrgRSchet_id := _r.OrgRSchet_id,
				p_Registry_IsRepeated := _r.Registry_IsRepeated,
				p_Registry_rid := _r.Registry_rid,
				p_PayType_id := _r.PayType_id,
				p_Registry_IsZNO := _r.Registry_IsZNO,
                p_LpuBuilding_id := _r.LpuBuilding_id,
                p_lpu_cid := _r.lpu_cid,
                p_registry_isfap := _r.registry_isfap
                ) fnc
                ;
		
			end if;
		
			delete from r477.RegistryQueue
			where RegistryQueue_id = _r.RegistryQueue_id;
		
        	_end_dt = clock_timestamp();
        
			update r477.RegistryQueueHistory set
				RegistryQueueHistory_endDT = _end_dt,
				RegistryQueueHistory_updDT = _end_dt,
				Registry_id = _r.Registry_id
			where RegistryQueueHistory_id = _r.RegistryQueue_id
            ;
		
			if coalesce(_Error_Code,'')<>''
			then
				
            	rollback;	--откатываем все изменения по реестуру 
                
                update r477.RegistryQueueHistory set
					Error_Code = _Error_Code,
					Error_Message = _Error_Message,
                    RegistryQueueHistory_endDT = _end_dt,
					RegistryQueueHistory_updDT = _end_dt,
                    RegistryQueueHistory_begDT = _beg_dt					
				where RegistryQueueHistory_id = _r.RegistryQueue_id
                ;
                
                commit; --сохраняем транзакцию, чтобы raise exception не откатил сохранение ошибки в r477.RegistryQueueHistory
		
				_Error_Message :=  coalesce(_Error_Code||' ','') || _Error_Message;
				RAISE EXCEPTION 'Message: %. Code: %', _Error_Message,'16';
			else
					select Registry_insDT,Registry_updDT
					into _Registry_insDT,_Registry_updDT
					from r477.registry
					where registry_id = _r.registry_id
                    ;
					
					select fnc.Error_Code,fnc.Error_Message into _Error_Code,_Error_Message from p_registryhistory_ins(
					registrycondition_id:=1,
					Registry_id := _r.Registry_id,
					RegistryType_id := _r.RegistryType_id,
					Lpu_id := _r.Lpu_id,
					LpuUnitSet_id := _r.LpuUnitSet_id,
					Registry_begDate := _r.Registry_begDate,
					Registry_endDate := _r.Registry_endDate,
					OrgSMO_id := _r.OrgSMO_id,
					Registry_Num := _r.Registry_Num,
					Registry_accDate := _r.Registry_accDate,
					RegistryStatus_id := 3,
					Registry_Sum := 0,
					Registry_IsActive := 2,
					Registry_ErrorCount := null,
					Registry_ErrorCommonCount := null,
					Registry_RecordCount := null,
					Registry_insDT:=_Registry_insDT,
					Registry_updDT:=_Registry_updDT,
					pmUser_id := _r.pmUser_id,
					Org_mid := _r.Org_mid,
					OrgRSchet_mid := _r.OrgRSchet_mid,
					KatNasel_id := _r.KatNasel_id,
					DispClass_id := _r.DispClass_id,
					OrgRSchet_id := _r.OrgRSchet_id,
					Registry_IsRepeated := _r.Registry_IsRepeated,
					Registry_rid := _r.Registry_rid,
					Registry_IsZNO := _r.Registry_IsZNO,
                    lpubuilding_id := _r.LpuBuilding_id,
                    lpu_cid := _r.lpu_cid
                    ) fnc;
				--IN registryhistory_id bigint , registrycondition_id bigint , registry_id bigint , registrytype_id bigint , lpu_id bigint , registry_begdate timestamp , registry_enddate timestamp , katnasel_id bigint , registry_num character , registry_accdate timestamp , registrystatus_id bigint , registry_sum numeric DEFAULT NULL::numeric, registry_isactive bigint , registry_errorcount integer DEFAULT NULL::integer, registry_errorcommoncount integer DEFAULT NULL::integer, registry_recordcount integer DEFAULT NULL::integer, registry_insdt timestamp , registry_upddt timestamp , orgrschet_id bigint , registry_exportpath character , registry_expdt timestamp , registrystactype_id bigint , registry_recordpaidcount integer DEFAULT NULL::integer, registry_kdcount integer DEFAULT NULL::integer, registry_kdpaidcount integer DEFAULT NULL::integer, registry_deleted bigint , registry_deldt timestamp , registry_xmlexportpath character , registry_xmlexpdt timestamp , registrycheckstatus_id bigint , registry_task character , lpubuilding_id bigint , paytype_id bigint , registry_sumpaid numeric DEFAULT NULL::numeric, registry_checkstatusdate timestamp , registry_checkstatustfomsdate timestamp , registry_senddt timestamp , registry_isneedreform bigint , org_mid bigint , orgrschet_mid bigint , dispclass_id bigint , registrygrouptype_id bigint , registry_ispolisclose bigint , registry_isrepeated bigint , registry_evnnum character , registry_exportsign character , registry_noerrsum numeric DEFAULT NULL::numeric, registry_isarchive bigint , registry_isrecalc bigint , drugfinance_id bigint , lpu_oid bigint , lpuunitset_id bigint , org_id bigint , orgsmo_id bigint , pmuser_downid bigint , registry_comments character , registry_countisbadvol bigint , registry_downdt timestamp , registry_filenum integer DEFAULT NULL::integer, registry_isaddacc bigint , registry_isfinal bigint , registry_isfinanc bigint , registry_isflk bigint , registry_isloadtfoms bigint , registry_islocked bigint , registry_isnew bigint , registry_isnotinsur bigint , registry_isonceintwoyears bigint , registry_orderdate timestamp , registry_pack integer DEFAULT NULL::integer, registry_persfincount integer DEFAULT NULL::integer, registry_persfinpaycount integer DEFAULT NULL::integer, registry_persfinsum numeric DEFAULT NULL::numeric, registry_rid bigint , registry_sumf numeric DEFAULT NULL::numeric, registry_sumr numeric DEFAULT NULL::numeric, registry_xmlexppatherr character , registryeventtype_id bigint , registrysubtype_id bigint , whsdocumentcostitemtype_id bigint , lpufilial_id bigint , registry_iszno bigint , lpu_cid bigint , registry_istest bigint , registry_filenamecase character , registry_filenamepersonaldata character , registry_casecount bigint , registry_personaldatacount bigint , org_did bigint , registry_ispersfin bigint , registry_counterr bigint , pmuser_id bigint , INOUT error_code character , INOUT error_message character )
			end if;
            
            commit;	--завершаем транзакцию при успешном формировании реестра, в одной транзакции формировать несколько реестров нельзя
            
		end if;
	end loop;
	
end;
$$;


ALTER FUNCTION r477.registry_processing_region() OWNER TO developer_rep;

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

CREATE FUNCTION r477.tambov_fin_get_value_dev(p_params jsonb) RETURNS text
    LANGUAGE plpgsql STRICT
    AS $_$
DECLARE
	_region_id INTEGER := (p_params ->> 'p_region')::INTEGER;
	_get_region_id INTEGER := dbo.getregion();
	_object_code TEXT := p_params ->> 'object_code';
	_object_type TEXT := p_params ->> 'object_type';
	_object_type_view TEXT := split_part(p_params ->> 'object_type', '.', 1) || '.v_' || split_part(p_params ->> 'object_type', '.', 2);
	_code_field_name TEXT := LOWER(split_part(_object_type, '.', 2)) || '_code';
	_id_field_name TEXT := LOWER(split_part(_object_type, '.', 2)) || '_id';
	_bd_field_name TEXT := LOWER(split_part(_object_type, '.', 2)) || CASE WHEN _object_type = 'dbo.TariffClass' THEN '_begdt' WHEN _object_type = 'dbo.VolumeType' THEN '_begdate' END;
	_ed_field_name TEXT := LOWER(split_part(_object_type, '.', 2)) || CASE WHEN _object_type = 'dbo.TariffClass' THEN '_enddt' WHEN _object_type = 'dbo.VolumeType' THEN '_enddate' END;
	_on_date DATE := COALESCE((p_params ->> 'p_date')::DATE, CURRENT_DATE);
	_valuefieldname_type TEXT;
	_object_id BIGINT;
	_mainrec record;
	_r record;
	_sql TEXT;
	_info TEXT;
BEGIN

	IF COALESCE(_region_id, _get_region_id)  IS DISTINCT FROM _get_region_id THEN SET SESSION.Region TO _region_id; END IF;
 
	CREATE TEMP TABLE tmp_attr(attributevalue_id BIGINT, attributevalue_rid BIGINT, attributevalue_value TEXT, attributevalue_iskey BOOLEAN) ON COMMIT DROP;

	-- Вычисляем id входной сущности
	_sql = 
		concat (
			$$ 
			SELECT $$, _id_field_name, $$ 
			FROM $$, _object_type_view, $$ 
			WHERE $$, _code_field_name, $$ = '$$, _object_code, $$'
			AND '$$, _on_date, $$'::DATE BETWEEN COALESCE($$, _bd_field_name, $$, '-INFINITY') AND COALESCE($$, _ed_field_name, $$, 'INFINITY')			
			;
			$$
			);

	EXECUTE _sql INTO _object_id;

	--RAISE NOTICE '_object_id = %', _object_id;
	--RAISE NOTICE '_sql = %', _sql;

	-- Основные параметры модели
	SELECT 
		COUNT(1) AS cnt, 
		av.attributevision_tablepkey, 
		(ARRAY_AGG(av.attributevision_id) FILTER (WHERE attributevision_iskeyvalue = 2))[1] AS attributevision_id_key,
		ARRAY_AGG(av.attributevision_id) AS attributevision_id_arr
	INTO _mainrec
	FROM dbo.v_attributevision AS av 
	WHERE av.attributevision_tablepkey = _object_id 
	AND av.attributevision_tablename = _object_type 
	AND _on_date BETWEEN COALESCE(av.attributevision_begdate, '-INFINITY') AND COALESCE(av.attributevision_enddate, 'INFINITY')
	GROUP BY av.attributevision_tablepkey;

	--RAISE NOTICE '_mainrec = %', _mainrec;

	-- Вычисляем модель сущности
	FOR _r IN 
		SELECT av.attributevision_id, av.attributevision_tablepkey, a.attribute_id, a.attribute_code::TEXT, a.attribute_sysnick, a.attribute_tablename, 
		LOWER(split_part(a.attribute_tablename, '.', 2)) || '_id' AS attribute_idfieldname,
		LOWER(split_part(a.attribute_tablename, '.', 2)) || '_code' AS attribute_codefieldname,
		av.attributevision_iskeyvalue, 
		concat(
			'attributevalue_value', 
			CASE 
				WHEN avt.attributevaluetype_sysnick IN ('ident', 'baseident') THEN 'ident'
				WHEN avt.attributevaluetype_sysnick IN ('bool') THEN 'boolean'
				WHEN avt.attributevaluetype_sysnick IN ('money') THEN 'float'
				ELSE avt.attributevaluetype_sysnick
			END
			) AS attributevalue_valuefieldname,
		CASE WHEN avt.attributevaluetype_sysnick IN ('ident', 'baseident') THEN TRUE ELSE FALSE END::TEXT AS is_directory
		FROM dbo.v_attributevision AS av
		JOIN dbo.v_attribute AS a ON av.attribute_id = a.attribute_id
		JOIN dbo.v_attributevaluetype AS avt ON a.attributevaluetype_id = avt.attributevaluetype_id
		WHERE av.attributevision_id = ANY(_mainrec.attributevision_id_arr)
	LOOP 
		-- Тип поля где хранится значение атрибута
		_sql = 
			concat (
				$$ 
				SELECT pg_typeof($$, _r.attributevalue_valuefieldname, $$) FROM dbo.v_attributevalue
				;
				$$
				);

		EXECUTE _sql INTO _valuefieldname_type;

		-- Если атрибут является ключевым значением в модели то обрабатываем немного по другому
		IF _r.attributevision_id = _mainrec.attributevision_id_key THEN 
			_sql = 
				concat (
					$$ 
					INSERT INTO tmp_attr (attributevalue_id, attributevalue_rid, attributevalue_value, attributevalue_iskey)
					SELECT 
						attributevalue_id, 
						attributevalue_id, 
						$$, 
						CASE 
							WHEN _r.is_directory::BOOLEAN THEN concat($$at.$$,_r.attribute_codefieldname, $$$$)					
							ELSE concat($$av.$$, _r.attributevalue_valuefieldname, $$$$)
						END, 
						$$::TEXT, 
						TRUE 
					FROM dbo.v_attributevalue AS av 
						$$, 
						CASE 
							WHEN _r.is_directory::BOOLEAN THEN concat($$JOIN $$, _r.attribute_tablename, $$ AS at ON at.$$, _r.attribute_idfieldname, $$ = av.$$, _r.attributevalue_valuefieldname, $$$$)
							ELSE NULL
						END, 
						$$
					WHERE attributevision_id = $$, _r.attributevision_id, $$ 
					AND attributevalue_tablepkey = $$, _r.attributevision_tablepkey, $$ 
					AND attribute_id = $$, _r.attribute_id, $$
					AND '$$, _on_date, $$'::DATE BETWEEN COALESCE(attributevalue_begdate, '-INFINITY') AND COALESCE(attributevalue_enddate, 'INFINITY')
					;
					$$
					);			
		ELSE
			-- Добавляем во временную таблицу найденные значения
			_sql = 
				concat (
					$$ 
					INSERT INTO tmp_attr (attributevalue_id, attributevalue_rid, attributevalue_value, attributevalue_iskey)
					SELECT attributevalue_id, attributevalue_rid, $$, _r.attributevalue_valuefieldname, $$::TEXT, FALSE 
					FROM dbo.v_attributevalue 
					WHERE attributevision_id = $$, _r.attributevision_id, $$ 
					AND attributevalue_tablepkey = $$, _r.attributevision_tablepkey, $$ 
					AND attribute_id = $$, _r.attribute_id, $$
					AND ($$, _r.attributevalue_valuefieldname, $$ = ('$$, p_params, $$'::JSONB ->> '$$, COALESCE(_r.attribute_idfieldname, _r.attribute_sysnick, _r.attribute_code), $$' )::$$, UPPER(_valuefieldname_type), $$ OR $$, _r.attributevalue_valuefieldname, $$ IS NULL)
					AND '$$, _on_date, $$'::DATE BETWEEN COALESCE(attributevalue_begdate, '-INFINITY') AND COALESCE(attributevalue_enddate, 'INFINITY')
					;
					$$
					);

		END IF;

		EXECUTE _sql;

		--RAISE NOTICE '%', _sql;

	END LOOP;

	CREATE INDEX ON tmp_attr(attributevalue_rid);

	WITH t AS (
		SELECT 
			string_agg(attributevalue_value, ',') FILTER (WHERE attributevalue_iskey) AS value, 
			COUNT(attributevalue_id) FILTER (WHERE NOT attributevalue_iskey AND attributevalue_value IS NOT NULL) AS priority
		FROM tmp_attr
		GROUP BY attributevalue_rid HAVING COUNT(attributevalue_id) = _mainrec.cnt
		ORDER BY 2 DESC
		LIMIT 1
		)
	SELECT value INTO _info FROM t;

	DROP TABLE tmp_attr;

	RETURN _info;
  
END;
$_$;


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



--
-- Name: militarycategory; Type: TABLE; Schema: r477; Owner: r477_role
--

CREATE TABLE r477.militarycategory (
    militarycategory_id bigint NOT NULL,
    militarycategory_code character varying(15),
    militarycategory_name character varying(100),
    militarycategory_begdate timestamp without time zone,
    militarycategory_enddate timestamp without time zone,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    militarycategory_insdt timestamp without time zone NOT NULL,
    militarycategory_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.militarycategory OWNER TO r477_role;

--
-- Name: TABLE militarycategory; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON TABLE r477.militarycategory IS '300.Локальный справочник для Мин. обороны';


--
-- Name: COLUMN militarycategory.militarycategory_id; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_id IS 'Уникальный идентификатор';


--
-- Name: COLUMN militarycategory.militarycategory_code; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_code IS 'Код';


--
-- Name: COLUMN militarycategory.militarycategory_name; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_name IS 'Наименование';


--
-- Name: COLUMN militarycategory.militarycategory_begdate; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_begdate IS 'Дата начала действия';


--
-- Name: COLUMN militarycategory.militarycategory_enddate; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_enddate IS 'Дата окончания действия';


--
-- Name: COLUMN militarycategory.pmuser_insid; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.pmuser_insid IS 'Пользователь, добавивший запись';


--
-- Name: COLUMN militarycategory.pmuser_updid; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.pmuser_updid IS 'Пользователь, обновивший запись';


--
-- Name: COLUMN militarycategory.militarycategory_insdt; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_insdt IS 'Дата добавления записи';


--
-- Name: COLUMN militarycategory.militarycategory_upddt; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON COLUMN r477.militarycategory.militarycategory_upddt IS 'Дата обновления записи';


--
-- Name: militarycategory_militarycategory_id_seq; Type: SEQUENCE; Schema: r477; Owner: r477_role
--

ALTER TABLE r477.militarycategory ALTER COLUMN militarycategory_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.militarycategory_militarycategory_id_seq
    START WITH 140101000000001
    INCREMENT BY 1
    MINVALUE 140101000000001
    MAXVALUE 140101999999999
    CACHE 1
);


--
-- Name: orgmilitarytype; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.orgmilitarytype (
    orgmilitarytype_id bigint NOT NULL,
    orgmilitarytype_code character varying(15),
    orgmilitarytype_name character varying(150),
    klcountry_id bigint,
    orgmilitarytype_begdate timestamp without time zone,
    orgmilitarytype_enddate timestamp without time zone,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    orgmilitarytype_insdt timestamp without time zone NOT NULL,
    orgmilitarytype_upddt timestamp without time zone NOT NULL,
    orgmilitarytype_deleted bigint DEFAULT 1 NOT NULL,
    pmuser_delid bigint,
    orgmilitarytype_deldt timestamp without time zone
);


ALTER TABLE r477.orgmilitarytype OWNER TO developer_rep;

--
-- Name: TABLE orgmilitarytype; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.orgmilitarytype IS 'Региональный справочник типов ВМО';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_id IS 'Уникальный идентификатор';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_code IS 'Код';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_name; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_name IS 'Наименование';


--
-- Name: COLUMN orgmilitarytype.klcountry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.klcountry_id IS 'Идентификатор страны';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_begdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_begdate IS 'Дата начала действия';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_enddate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_enddate IS 'Дата окончания действия';


--
-- Name: COLUMN orgmilitarytype.pmuser_insid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.pmuser_insid IS 'Пользователь, добавивший запись';


--
-- Name: COLUMN orgmilitarytype.pmuser_updid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.pmuser_updid IS 'Пользователь, обновивший запись';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_insdt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_insdt IS 'Дата добавления записи';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_upddt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_upddt IS 'Дата обновления записи';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_deleted; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_deleted IS 'Признак удаления';


--
-- Name: COLUMN orgmilitarytype.pmuser_delid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.pmuser_delid IS 'Пользователь, удаливший запись';


--
-- Name: COLUMN orgmilitarytype.orgmilitarytype_deldt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytype.orgmilitarytype_deldt IS 'Дата удаления записи';


--
-- Name: orgmilitarytype_orgmilitarytype_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.orgmilitarytype ALTER COLUMN orgmilitarytype_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.orgmilitarytype_orgmilitarytype_id_seq
    START WITH 140101000000001
    INCREMENT BY 1
    MINVALUE 140101000000001
    MAXVALUE 140101999999999
    CACHE 1
);


--
-- Name: orgmilitarytypelink; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.orgmilitarytypelink (
    orgmilitarytypelink_id bigint NOT NULL,
    orgmilitarytype_id bigint,
    org_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    orgmilitarytypelink_insdt timestamp without time zone NOT NULL,
    orgmilitarytypelink_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.orgmilitarytypelink OWNER TO developer_rep;

--
-- Name: TABLE orgmilitarytypelink; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.orgmilitarytypelink IS 'Связи организации с типом ВМО';


--
-- Name: COLUMN orgmilitarytypelink.orgmilitarytypelink_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.orgmilitarytypelink_id IS 'Уникальный идентификатор';


--
-- Name: COLUMN orgmilitarytypelink.orgmilitarytype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.orgmilitarytype_id IS 'Идентификатор типа ВМО';


--
-- Name: COLUMN orgmilitarytypelink.org_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.org_id IS 'Организация';


--
-- Name: COLUMN orgmilitarytypelink.pmuser_insid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.pmuser_insid IS 'Пользователь, добавивший запись';


--
-- Name: COLUMN orgmilitarytypelink.pmuser_updid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.pmuser_updid IS 'Пользователь, обновивший запись';


--
-- Name: COLUMN orgmilitarytypelink.orgmilitarytypelink_insdt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.orgmilitarytypelink_insdt IS 'Дата добавления записи';


--
-- Name: COLUMN orgmilitarytypelink.orgmilitarytypelink_upddt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.orgmilitarytypelink.orgmilitarytypelink_upddt IS 'Дата обновления записи';


--
-- Name: orgmilitarytypelink_orgmilitarytypelink_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.orgmilitarytypelink ALTER COLUMN orgmilitarytypelink_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.orgmilitarytypelink_orgmilitarytypelink_id_seq
    START WITH 140101000000001
    INCREMENT BY 1
    MINVALUE 140101000000001
    MAXVALUE 140101999999999
    CACHE 1
);


--
-- Name: registry; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registry (
    registry_id bigint NOT NULL,
    registrytype_id bigint NOT NULL,
    lpu_id bigint NOT NULL,
    registry_begdate timestamp without time zone NOT NULL,
    registry_enddate timestamp without time zone NOT NULL,
    orgsmo_id bigint,
    lpuunitset_id bigint,
    registry_num character varying(10) NOT NULL,
    registry_accdate timestamp without time zone NOT NULL,
    registrystatus_id bigint NOT NULL,
    registry_sum numeric,
    registry_isactive bigint NOT NULL,
    registry_errorcount integer,
    registry_errorcommoncount integer,
    registry_recordcount integer,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registry_insdt timestamp without time zone NOT NULL,
    registry_upddt timestamp without time zone NOT NULL,
    registry_exportpath character varying(200),
    registry_expdt timestamp without time zone,
    registry_xmlexportpath character varying(200),
    registry_xmlexpdt timestamp without time zone,
    registry_sumr numeric,
    registry_sumf numeric,
    registry_downdt timestamp without time zone,
    pmuser_downid bigint,
    registry_isneedreform bigint,
    katnasel_id bigint,
    orgrschet_id bigint,
    registrystactype_id bigint,
    registry_recordpaidcount integer,
    registry_kdcount integer,
    registry_kdpaidcount integer,
    registry_deleted bigint,
    pmuser_delid bigint,
    registry_deldt timestamp without time zone,
    registrycheckstatus_id bigint,
    registry_task character varying(100),
    lpubuilding_id bigint,
    paytype_id bigint,
    registry_sumpaid numeric,
    registry_checkstatusdate timestamp without time zone,
    registry_checkstatustfomsdate timestamp without time zone,
    registry_senddt timestamp without time zone,
    drugfinance_id bigint,
    whsdocumentcostitemtype_id bigint,
    org_id bigint,
    org_mid bigint,
    orgrschet_mid bigint,
    registry_filenum integer,
    dispclass_id bigint,
    registrygrouptype_id bigint,
    registry_xmlexppatherr character varying(200),
    registry_isrepeated bigint,
    registry_rid bigint,
    registry_persfincount integer,
    registry_persfinpaycount integer,
    registry_persfinsum numeric,
    registry_exportsign character varying(200),
    registry_iszno bigint,
    registry_counterr bigint,
    registry_islocked bigint,
    registry_packnum bigint,
    lpu_cid bigint
);


ALTER TABLE r477.registry OWNER TO developer_rep;

--
-- Name: COLUMN registry.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_id IS 'Флаг Повторная подача';


--
-- Name: COLUMN registry.orgsmo_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.orgsmo_id IS 'СМО, для уфы';


--
-- Name: COLUMN registry.registry_isneedreform; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_isneedreform IS 'Признак необходимости переформирования реестра';


--
-- Name: COLUMN registry.katnasel_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.katnasel_id IS 'категория населения';


--
-- Name: COLUMN registry.orgrschet_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.orgrschet_id IS 'идентификатор расчетного счета';


--
-- Name: COLUMN registry.registrystactype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registrystactype_id IS 'тип реестра стационара';


--
-- Name: COLUMN registry.registry_deleted; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_deleted IS 'признак удаления';


--
-- Name: COLUMN registry.pmuser_delid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.pmuser_delid IS 'Пользователь, удаливший запись';


--
-- Name: COLUMN registry.registry_deldt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_deldt IS 'дата удаления записи';


--
-- Name: COLUMN registry.registrycheckstatus_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registrycheckstatus_id IS 'Статус проверки реестра';


--
-- Name: COLUMN registry.registry_task; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_task IS 'задание на обработку реестра';


--
-- Name: COLUMN registry.lpubuilding_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.lpubuilding_id IS 'идентификатор подразделения';


--
-- Name: COLUMN registry.paytype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.paytype_id IS 'Тип оплаты';


--
-- Name: COLUMN registry.registry_sumpaid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_sumpaid IS 'Реально оплаченная сумма реестра';


--
-- Name: COLUMN registry.registry_checkstatusdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_checkstatusdate IS 'Дата установления статуса в Промед';


--
-- Name: COLUMN registry.registry_checkstatustfomsdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_checkstatustfomsdate IS 'Дата проставления статуса в ТФОМС';


--
-- Name: COLUMN registry.registry_senddt; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_senddt IS 'Дата отправки реестра';


--
-- Name: COLUMN registry.drugfinance_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.drugfinance_id IS 'Источник финансирования';


--
-- Name: COLUMN registry.whsdocumentcostitemtype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.whsdocumentcostitemtype_id IS 'Статья расхода';


--
-- Name: COLUMN registry.org_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.org_id IS 'Организация';


--
-- Name: COLUMN registry.org_mid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.org_mid IS 'Организация, оплачивающая реестр';


--
-- Name: COLUMN registry.orgrschet_mid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.orgrschet_mid IS 'Счет организации, оплачивающей реестр';


--
-- Name: COLUMN registry.registry_filenum; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_filenum IS 'Порядковый номер выгруженного файла в отчетном периоде';


--
-- Name: COLUMN registry.dispclass_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.dispclass_id IS 'Вид диспансеризации';


--
-- Name: COLUMN registry.registrygrouptype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registrygrouptype_id IS 'тип объединенных реестров';


--
-- Name: COLUMN registry.registry_isrepeated; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_isrepeated IS 'Флаг Повторная подача';


--
-- Name: COLUMN registry.registry_persfincount; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_persfincount IS 'Количество случаев по подушевому финансированию';


--
-- Name: COLUMN registry.registry_persfinpaycount; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_persfinpaycount IS 'Количество оплаченных случаев по подушевому финансированию';


--
-- Name: COLUMN registry.registry_persfinsum; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_persfinsum IS 'Сумма по подушевуму финансированию';


--
-- Name: COLUMN registry.registry_exportsign; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_exportsign IS 'Путь к файлу подписи реестра';


--
-- Name: COLUMN registry.registry_counterr; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registry.registry_counterr IS 'Количество записей с ошибками данных, не вошедших в реестр';


--
-- Name: registry_registry_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registry ALTER COLUMN registry_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registry_registry_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registrycmpnopolis; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrycmpnopolis (
    registry_id bigint NOT NULL,
    evn_id bigint NOT NULL,
    person_id bigint NOT NULL,
    evn_code character varying(20),
    person_surname character varying(30) NOT NULL,
    person_firname character varying(30),
    person_secname character varying(30),
    person_birthday timestamp without time zone NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrynopolis_insdt timestamp without time zone NOT NULL,
    registrynopolis_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registrycmpnopolis OWNER TO developer_rep;

--
-- Name: registrydata; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrydata (
    evn_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    numcard character varying(50),
    number bigint,
    evn_rid bigint,
    person_id bigint,
    lpusection_id bigint,
    lpusectionprofile_id bigint,
    medpersonal_id bigint,
    registrydata_tariff double precision,
    registrydata_kdfact double precision,
    registrydata_kdplan double precision,
    registrydata_kdpay double precision,
    registrydata_ukl double precision,
    registrydata_uklsum double precision,
    registrydata_itogsum double precision,
    omssprterr_id bigint,
    address_id bigint,
    registrydata_isprev bigint,
    registrydata_isambul bigint,
    vizittype_id bigint,
    resultclass_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrydata_insdt timestamp without time zone NOT NULL,
    registrydata_upddt timestamp without time zone NOT NULL,
    diag_id bigint,
    registrydata_ei2 double precision,
    registrydata_g162 double precision,
    medpersonal_fio character varying(100),
    medpersonal_snils character varying(11),
    omssprterr_code integer,
    evn_disdate timestamp without time zone,
    lpusection_code character varying(9),
    lpusectionprofile_code character varying(10),
    medpersonal_code character varying(11),
    polis_begdate timestamp without time zone,
    polis_enddate timestamp without time zone,
    orgsmo_id bigint,
    medspec_id bigint,
    evn_upddate timestamp without time zone,
    dopdispspec_id bigint,
    guid uuid DEFAULT dbo.newid() NOT NULL,
    usluga_id bigint,
    paid_id bigint,
    maxevn_id bigint,
    registrydata_tarif_r double precision,
    registrydata_tarif_f double precision,
    registrydata_sum_r double precision,
    registrydata_sum_f double precision,
    registrydata_rownum integer,
    leavetype_id bigint,
    resultdesease_id bigint,
    leavecause_id bigint,
    evn_setdate timestamp without time zone,
    evnsection_isadultescort bigint,
    registrydata_double integer,
    uslugacomplex_id bigint,
    registrydata_deleted integer,
    mestariff_id bigint,
    mesitog_id bigint,
    mestariff_value numeric(25,15),
    evnsection_numgroup bigint,
    lpuunittype_id bigint,
    mesitog_value numeric(25,15),
    registrydata_coeffctp numeric(10,4),
    paymedtype_id bigint,
    registrydata_ispaid bigint,
    server_id bigint NOT NULL,
    personevn_id bigint NOT NULL,
    registrydata_ispersfin bigint,
    registrydata_period integer,
    socstatus_code character varying(5),
    mesolduslugacomplex_id bigint,
    koef_up numeric(5,2),
    koef_u numeric(5,2),
    registrydata_prer integer,
    evnmax_id bigint,
    registrydata_iszno bigint,
    region_data jsonb,
    pmuser_delid bigint,
    registrydata_deldt timestamp without time zone,
    needreform integer,
    evnclass_id bigint NOT NULL,
    medstafffact_id bigint,
    parentevnclass_id bigint NOT NULL
);


ALTER TABLE r477.registrydata OWNER TO developer_rep;

--
-- Name: COLUMN registrydata.paid_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.paid_id IS 'Признак оплаченности посещения';


--
-- Name: COLUMN registrydata.uslugacomplex_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.uslugacomplex_id IS 'Идентификатор комплексной услуги';


--
-- Name: COLUMN registrydata.evnsection_numgroup; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.evnsection_numgroup IS 'Номер группы';


--
-- Name: COLUMN registrydata.paymedtype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.paymedtype_id IS 'Способы оплаты медицинской помощи';


--
-- Name: COLUMN registrydata.registrydata_ispaid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.registrydata_ispaid IS 'Случай оплачен';


--
-- Name: COLUMN registrydata.registrydata_ispersfin; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydata.registrydata_ispersfin IS 'Признак подушевного финансирования';


--
-- Name: registrydatacmp; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrydatacmp (
    cmpclosecard_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    numcard character(20),
    person_id bigint,
    lpusection_id bigint,
    lpusectionprofile_id bigint,
    medpersonal_id bigint,
    registrydatacmp_tariff double precision,
    registrydatacmp_ukl double precision,
    registrydatacmp_uklsum double precision,
    registrydatacmp_itogsum double precision,
    omssprterr_id bigint,
    address_id bigint,
    registrydatacmp_isprev bigint,
    registrydatacmp_isambul bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrydatacmp_insdt timestamp without time zone NOT NULL,
    registrydatacmp_upddt timestamp without time zone NOT NULL,
    diag_id bigint,
    medpersonal_fio character varying(100),
    medpersonal_snils character varying(11),
    omssprterr_code integer,
    evn_disdate timestamp without time zone,
    lpusection_code character varying(5),
    lpusectionprofile_code character varying(10),
    medpersonal_code character varying(10),
    polis_begdate timestamp without time zone,
    polis_enddate timestamp without time zone,
    orgsmo_id bigint,
    medspec_id bigint,
    cmpclosecard_upddate timestamp without time zone,
    polis_id bigint,
    polis_ser character varying(10),
    polis_num character varying(30),
    evn_setdate timestamp without time zone,
    needreform integer,
    evnps_iscont bigint,
    prehospdirect_id bigint,
    registrydatacmp_isperev bigint,
    cmpresult_id bigint,
    registrydatacmp_rownum integer,
    registrydatacmp_deleted integer,
    registrydatacmp_double integer,
    evnsection_isadultescort bigint,
    registrydatacmp_ispaid bigint,
    uslugacomplex_id bigint,
    registrydatacmp_tarif_r double precision,
    registrydatacmp_tarif_f double precision,
    registrydatacmp_sum_r double precision,
    registrydatacmp_sum_f double precision,
    registrydatacmp_ei2 double precision,
    paymedtype_id bigint,
    number bigint,
    registrydatacmp_kdfact double precision,
    registrydatacmp_kdplan double precision,
    registrydatacmp_kdpay double precision,
    registrydatacmp_g162 double precision,
    maxevn_id bigint,
    evnsection_numgroup bigint,
    lpuunittype_id bigint,
    registrydatacmp_coeffctp numeric(10,4),
    registrydatacmp_ispersfin bigint,
    cmpclosecard_sid bigint NOT NULL,
    region_data jsonb
);


ALTER TABLE r477.registrydatacmp OWNER TO developer_rep;

--
-- Name: TABLE registrydatacmp; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registrydatacmp IS 'Данные по реестрам';


--
-- Name: COLUMN registrydatacmp.cmpclosecard_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.cmpclosecard_id IS 'идентификатор СМП:карты';


--
-- Name: COLUMN registrydatacmp.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registry_id IS 'идентификатор реестра';


--
-- Name: COLUMN registrydatacmp.numcard; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.numcard IS 'номер карты';


--
-- Name: COLUMN registrydatacmp.person_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.person_id IS 'идентификатор человека';


--
-- Name: COLUMN registrydatacmp.lpusection_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.lpusection_id IS 'идентификатор отделения ЛПУ';


--
-- Name: COLUMN registrydatacmp.lpusectionprofile_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.lpusectionprofile_id IS 'профиль отделения ЛПУ';


--
-- Name: COLUMN registrydatacmp.medpersonal_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.medpersonal_id IS 'идентификатор справочника медицинских работников';


--
-- Name: COLUMN registrydatacmp.registrydatacmp_ukl; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registrydatacmp_ukl IS 'уровень качества лечения';


--
-- Name: COLUMN registrydatacmp.omssprterr_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.omssprterr_id IS 'идентификатор справочника территорий страхования';


--
-- Name: COLUMN registrydatacmp.address_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.address_id IS 'адрес';


--
-- Name: COLUMN registrydatacmp.registrydatacmp_isambul; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registrydatacmp_isambul IS 'направлен на амбулаторное лечение';


--
-- Name: COLUMN registrydatacmp.diag_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.diag_id IS 'Идентификатор диагноза';


--
-- Name: COLUMN registrydatacmp.medpersonal_fio; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.medpersonal_fio IS 'ФИО врача';


--
-- Name: COLUMN registrydatacmp.medpersonal_snils; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.medpersonal_snils IS 'СНИЛС мед работника';


--
-- Name: COLUMN registrydatacmp.omssprterr_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.omssprterr_code IS 'код территории страхования';


--
-- Name: COLUMN registrydatacmp.evn_disdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.evn_disdate IS 'дата выписки';


--
-- Name: COLUMN registrydatacmp.lpusection_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.lpusection_code IS 'код отделения ЛПУ';


--
-- Name: COLUMN registrydatacmp.lpusectionprofile_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.lpusectionprofile_code IS 'код профиля отделения ЛПУ';


--
-- Name: COLUMN registrydatacmp.medpersonal_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.medpersonal_code IS 'Код медицинского работника';


--
-- Name: COLUMN registrydatacmp.polis_begdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.polis_begdate IS 'дата начала действия полиса';


--
-- Name: COLUMN registrydatacmp.polis_enddate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.polis_enddate IS 'дата окончания действия полиса';


--
-- Name: COLUMN registrydatacmp.orgsmo_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.orgsmo_id IS 'идентификатор справочника страховых организаций';


--
-- Name: COLUMN registrydatacmp.medspec_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.medspec_id IS 'идентификатор специальности врача';


--
-- Name: COLUMN registrydatacmp.polis_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.polis_id IS 'идентификатор полиса';


--
-- Name: COLUMN registrydatacmp.polis_ser; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.polis_ser IS 'серия полиса';


--
-- Name: COLUMN registrydatacmp.polis_num; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.polis_num IS 'номер полиса';


--
-- Name: COLUMN registrydatacmp.evn_setdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.evn_setdate IS 'дата поступления';


--
-- Name: COLUMN registrydatacmp.needreform; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.needreform IS 'Требуется переформирование/перепроверка по данной записи в реестре';


--
-- Name: COLUMN registrydatacmp.evnps_iscont; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.evnps_iscont IS 'продолжение случая';


--
-- Name: COLUMN registrydatacmp.prehospdirect_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.prehospdirect_id IS 'кем направлен в предварительной госпитализации';


--
-- Name: COLUMN registrydatacmp.cmpresult_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.cmpresult_id IS 'результат заболевания';


--
-- Name: COLUMN registrydatacmp.registrydatacmp_deleted; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registrydatacmp_deleted IS 'признак удаления данных';


--
-- Name: COLUMN registrydatacmp.registrydatacmp_ispaid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registrydatacmp_ispaid IS 'Случай оплачен';


--
-- Name: COLUMN registrydatacmp.uslugacomplex_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.uslugacomplex_id IS 'Идентификатор комплексной услуги';


--
-- Name: COLUMN registrydatacmp.paymedtype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.paymedtype_id IS 'Способы оплаты медицинской помощи';


--
-- Name: COLUMN registrydatacmp.registrydatacmp_ispersfin; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.registrydatacmp_ispersfin IS 'Признак подушевного финансирования';


--
-- Name: COLUMN registrydatacmp.cmpclosecard_sid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatacmp.cmpclosecard_sid IS 'Ссылка на карту СМП либо услугу карты вызова СМП';


--
-- Name: registrydatasl; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrydatasl (
    registrydatasl_id bigint NOT NULL,
    registry_id bigint,
    registrydatasl_rownum integer,
    evn_id bigint,
    evn_rid bigint,
    maxevn_id bigint,
    person_id bigint,
    lpu_id bigint,
    lpuunittype_id bigint,
    personevn_id bigint,
    evn_setdate timestamp without time zone,
    evn_disdate timestamp without time zone,
    omssprterr_id bigint,
    orgsmo_id bigint,
    registrydatasl_sum double precision,
    pmuser_insid bigint,
    pmuser_updid bigint,
    registrydatasl_insdt timestamp without time zone,
    registrydatasl_upddt timestamp without time zone,
    kd_z integer,
    server_id bigint,
    numcard character varying(50),
    leavetype_id bigint,
    resultdesease_id bigint,
    vb_p integer
);


ALTER TABLE r477.registrydatasl OWNER TO developer_rep;

--
-- Name: registrydatasl_registrydatasl_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registrydatasl ALTER COLUMN registrydatasl_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registrydatasl_registrydatasl_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registrydatatemp; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrydatatemp (
    evn_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    numcard character varying(50),
    evn_rid bigint,
    person_id bigint,
    lpusection_id bigint,
    lpusectionprofile_id bigint,
    medpersonal_id bigint,
    medpersonal_fio character varying(100),
    registrydata_tariff double precision,
    registrydata_kdfact double precision,
    registrydata_kdplan double precision,
    registrydata_kdpay double precision,
    registrydata_ukl double precision,
    registrydata_uklsum double precision,
    registrydata_itogsum double precision,
    registrydata_ei2 double precision,
    registrydata_g162 double precision,
    omssprterr_id bigint,
    omssprterr_code integer,
    address_id bigint,
    person_address character varying(300),
    person_surname character varying(30),
    person_firname character varying(30),
    person_secname character varying(30),
    person_birthday timestamp without time zone,
    polis_id bigint,
    polis_ser character varying(10),
    polis_num character varying(30),
    evndiagps_id bigint,
    registrydata_isprev bigint,
    leavetype_id bigint,
    resultdesease_id bigint,
    leavecause_id bigint,
    registrydata_isambul bigint,
    diag_id bigint,
    vizittype_id bigint,
    resultclass_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrydata_insdt timestamp without time zone,
    registrydata_upddt timestamp without time zone,
    registrydata_deleted integer,
    evn_disdate timestamp without time zone,
    lpusection_code character varying(9),
    lpusectionprofile_code character varying(10),
    medpersonal_code character varying(11),
    polis_begdate timestamp without time zone,
    polis_enddate timestamp without time zone,
    orgsmo_id bigint,
    medspec_id bigint,
    evn_upddate timestamp without time zone,
    dopdispspec_id bigint,
    err_firname integer,
    err_surname integer,
    err_birthday integer,
    err_personsex integer,
    err_socstatus integer,
    err_persondoc integer,
    err_personinn integer,
    err_result integer,
    err_dates integer,
    err_codes integer,
    err_lpusection integer,
    err_levelmes integer,
    err_codemes integer,
    err_codedrug integer,
    err_inonojob integer,
    err_doublepolis integer,
    err_inoterprmes integer,
    err_profilemes integer,
    err_maxsection integer,
    err_sopdesease integer,
    err_doubledate integer,
    err_nocorrres integer,
    err_terrisempty integer,
    err_uklnull integer,
    err_badorgsmo integer,
    err_omssprterr integer,
    err_uslinvizit integer,
    err_codediag integer,
    err_lpusectionclose integer,
    err_kladrcode integer,
    err_vizitplsetdate integer,
    err_medspecoms integer,
    err_meddolvrach integer,
    err_deseasetype integer,
    err_firstmedhelp integer,
    err_purvizit integer,
    err_koledmedhelp integer,
    err_edmedhelp integer,
    err_personcard_code integer,
    err_secname integer,
    err_inoterinrb integer,
    err_jobpolisold integer,
    err_nojobsmoaddr integer,
    err_diagoms integer,
    err_polisnum integer,
    err_statusage integer,
    err_jobchild integer,
    err_inodiag integer,
    err_sexusluga integer,
    err_diagcentr integer,
    err_doublevizit integer,
    err_doublevizitprev integer,
    err_doublevizitstac integer,
    err_childortoped integer,
    err_norgn integer,
    err_regcity integer,
    err_numpolis integer,
    err_endsmo integer,
    err_inosmo integer,
    err_subrgn integer,
    usluga_id bigint,
    err_badusluga integer,
    err_nookato integer,
    registrydata_rownum integer,
    err_medpers_badsnils integer,
    evn_setdate timestamp without time zone,
    uslugacomplex_id bigint,
    err_nevsostlech integer,
    err_nresult integer,
    err_nadres integer,
    err_oneevnpsdiag integer,
    err_reshosp bigint,
    err_resdedease bigint,
    err_lpusecprofcode integer,
    err_certificate integer,
    mestariff_id bigint,
    mesitog_id bigint,
    maxevn_id bigint,
    mestariff_value numeric(25,15),
    evnsection_numgroup bigint,
    number bigint,
    lpuunittype_id bigint,
    mesitog_value numeric(25,15),
    registrydatatemp_coeffctp numeric(10,4),
    err_no_medcode_usl integer,
    err_no_snils integer,
    err_notuslugalpu integer,
    err_vidpom integer,
    server_id bigint,
    personevn_id bigint,
    registrydatatemp_ispersfin bigint,
    err_nookatowarn integer,
    cmpclosecard_sid bigint,
    registrydata_period integer,
    socstatus_code character varying(5),
    mesolduslugacomplex_id bigint,
    koef_up numeric(5,2),
    koef_u numeric(5,2),
    registrydata_prer integer,
    err_noevnsecksg integer,
    evnmax_id bigint,
    registrydata_iszno bigint,
    err_nofulldirection integer,
    err_direction integer,
    err_nodisp integer,
    err_noonkodiaginsmp integer,
    err_polis integer,
    err_notevnprescr integer,
    err_nocarddn integer,
    err_nonextvizit integer,
    region_data jsonb,
    medpersonal_snils character varying(11),
    paymedtype_id bigint,
    evnclass_id bigint,
    medstafffact_id bigint,
    parentevnclass_id bigint
);


ALTER TABLE r477.registrydatatemp OWNER TO developer_rep;

--
-- Name: COLUMN registrydatatemp.uslugacomplex_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatatemp.uslugacomplex_id IS 'Идентификатор комплексной услуги';


--
-- Name: COLUMN registrydatatemp.err_nevsostlech; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatatemp.err_nevsostlech IS 'Не верный состав случая лечения';


--
-- Name: COLUMN registrydatatemp.registrydatatemp_ispersfin; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatatemp.registrydatatemp_ispersfin IS 'Признак подушевного финансирования';


--
-- Name: COLUMN registrydatatemp.cmpclosecard_sid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatatemp.cmpclosecard_sid IS 'Ссылка на карту СМП либо услугу карты вызова СМП';


--
-- Name: COLUMN registrydatatemp.err_noonkodiaginsmp; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrydatatemp.err_noonkodiaginsmp IS 'Ошибка указания основного онко.диаг. для СМП';


--
-- Name: registrydouble; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrydouble (
    registry_id bigint NOT NULL,
    evn_id bigint NOT NULL,
    person_id bigint NOT NULL,
    evn_code character varying(20),
    person_surname character varying(30) NOT NULL,
    person_firname character varying(30),
    person_secname character varying(30),
    person_birthday timestamp without time zone NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrydouble_insdt timestamp without time zone NOT NULL,
    registrydouble_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registrydouble OWNER TO developer_rep;

--
-- Name: registryerror; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerror (
    registry_id bigint NOT NULL,
    evn_id bigint NOT NULL,
    registryerrortype_id bigint NOT NULL,
    lpusection_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerror_insdt timestamp without time zone NOT NULL,
    registryerror_upddt timestamp without time zone NOT NULL,
    evn_rid bigint,
    registryerror_desc character varying(1000),
    registryerror_name character varying(500),
    registryerror_id bigint NOT NULL,
    real_evn_id bigint,
    region_data jsonb
);


ALTER TABLE r477.registryerror OWNER TO developer_rep;

--
-- Name: registryerror_registryerror_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryerror ALTER COLUMN registryerror_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryerror_registryerror_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryerrorclass; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrorclass (
    registryerrorclass_id bigint NOT NULL,
    registryerrorclass_code integer NOT NULL,
    registryerrorclass_name character varying(30) NOT NULL,
    registryerrorclass_nick character varying(30) NOT NULL,
    registryerrorclass_sysnick character varying(20),
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerrorclass_insdt timestamp without time zone NOT NULL,
    registryerrorclass_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registryerrorclass OWNER TO developer_rep;

--
-- Name: registryerrorclass_registryerrorclass_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryerrorclass ALTER COLUMN registryerrorclass_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryerrorclass_registryerrorclass_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryerrorcmp; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrorcmp (
    registry_id bigint NOT NULL,
    cmpclosecard_id bigint NOT NULL,
    registryerrortype_id bigint NOT NULL,
    lpusection_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerrorcmp_insdt timestamp without time zone NOT NULL,
    registryerrorcmp_upddt timestamp without time zone NOT NULL,
    registryerror_desc character varying
);


ALTER TABLE r477.registryerrorcmp OWNER TO developer_rep;

--
-- Name: registryerrorcom; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrorcom (
    registry_id bigint NOT NULL,
    registryerrortype_id bigint NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerrorcom_insdt timestamp without time zone NOT NULL,
    registryerrorcom_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registryerrorcom OWNER TO developer_rep;

--
-- Name: registryerrorreturned; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrorreturned (
    registryerrorreturned_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    evn_id bigint,
    registryerrorreturned_idcase text,
    registryerrorreturned_id_pac text,
    registryerrorreturned_nhistory text,
    registryerrorreturned_date_1 text,
    registryerrorreturned_date_2 text,
    registryerrorreturned_sank text,
    registryerrorreturned_oplata text,
    pmuser_insid bigint DEFAULT (1)::bigint,
    pmuser_updid bigint DEFAULT (1)::bigint,
    registryerrorreturned_insdt timestamp without time zone DEFAULT now(),
    registryerrorreturned_upddt timestamp without time zone DEFAULT now(),
    registryerrorreturned_upload_filename text,
    registryerrorreturned_code text,
    registry_id_fact bigint
);


ALTER TABLE r477.registryerrorreturned OWNER TO developer_rep;

--
-- Name: registryerrorreturned_registryerrorreturned_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryerrorreturned ALTER COLUMN registryerrorreturned_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryerrorreturned_registryerrorreturned_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryerrortfoms; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrortfoms (
    registryerrortfoms_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    evn_id bigint,
    registryerrortype_id bigint,
    registryerrortype_code character varying(10),
    registryerrortfoms_fieldname character varying(50),
    registryerrortfoms_baseelement character varying(50),
    registryerrortfoms_rownum integer,
    registryerrortfoms_comment character varying(1024),
    registryerrortfoms_idcase integer,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerrortfoms_insdt timestamp without time zone NOT NULL,
    registryerrortfoms_upddt timestamp without time zone NOT NULL,
    registry_task character varying(100),
    registryerrortfomstype_id bigint,
    registryerrortfoms_caseguid bigint,
    registryerrortfoms_severity character varying(20),
    registryerrortfomslevel_id bigint,
    registryerrorclass_id bigint,
    cmpclosecard_id bigint
);


ALTER TABLE r477.registryerrortfoms OWNER TO developer_rep;

--
-- Name: registryerrortfoms_registryerrortfoms_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryerrortfoms ALTER COLUMN registryerrortfoms_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryerrortfoms_registryerrortfoms_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryerrortype; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryerrortype (
    registryerrortype_id bigint NOT NULL,
    registryerrortype_code character varying(10) NOT NULL,
    registryerrortype_name character varying(500) NOT NULL,
    registryerrortype_descr character varying(1000) NOT NULL,
    registryerrortype_sysnick character varying(20),
    registryerrorclass_id bigint,
    registryerrortype_isuser bigint,
    registryerrortype_iscrit bigint,
    registryfield_percent double precision,
    registrytype_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryerrortype_insdt timestamp without time zone NOT NULL,
    registryerrortype_upddt timestamp without time zone NOT NULL,
    registryerrortype_begdt timestamp without time zone,
    registryerrortype_enddt timestamp without time zone
);


ALTER TABLE r477.registryerrortype OWNER TO developer_rep;

--
-- Name: TABLE registryerrortype; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registryerrortype IS 'Тип ошибок по реестрам';


--
-- Name: COLUMN registryerrortype.registryerrortype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrortype_id IS 'идентификатор';


--
-- Name: COLUMN registryerrortype.registryerrortype_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrortype_code IS 'код ошибки';


--
-- Name: COLUMN registryerrortype.registryerrortype_name; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrortype_name IS 'наименование';


--
-- Name: COLUMN registryerrortype.registryerrortype_descr; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrortype_descr IS 'описание ошибки';


--
-- Name: COLUMN registryerrortype.registryerrortype_sysnick; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrortype_sysnick IS 'системное наименование';


--
-- Name: COLUMN registryerrortype.registryerrorclass_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registryerrorclass_id IS 'класс ошибки по реестрам';


--
-- Name: COLUMN registryerrortype.registrytype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryerrortype.registrytype_id IS 'тип реестра';


--
-- Name: registryerrortype_registryerrortype_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryerrortype ALTER COLUMN registryerrortype_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryerrortype_registryerrortype_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryexportnumber; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryexportnumber (
    registryexportnumber_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    registryaction_id bigint NOT NULL,
    registryexportnumber_insdt timestamp without time zone DEFAULT clock_timestamp()
);


ALTER TABLE r477.registryexportnumber OWNER TO developer_rep;

--
-- Name: registryexportnumber_registryexportnumber_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryexportnumber ALTER COLUMN registryexportnumber_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryexportnumber_registryexportnumber_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryflcreturned_id_seq; Type: SEQUENCE; Schema: r477; Owner: AsanovS
--

CREATE SEQUENCE r477.registryflcreturned_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
    CYCLE;


ALTER SEQUENCE r477.registryflcreturned_id_seq OWNER TO "AsanovS";

--
-- Name: registryflcreturned; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryflcreturned (
    registry_id bigint DEFAULT nextval('r477.registryflcreturned_id_seq'::regclass) NOT NULL,
    registryflcreturned_oshib text,
    registryflcreturned_im_pol text,
    registryflcreturned_zn_pol text,
    registryflcreturned_bas_el text,
    registryflcreturned_n_zap text,
    registryflcreturned_id_pac text,
    registryflcreturned_idcase text,
    registryflcreturned_sl_id text,
    registryflcreturned_idserv text,
    registryflcreturned_comment text,
    registryflcreturned_upload_filename text,
    pmuser_insid bigint DEFAULT (1)::bigint,
    pmuser_updid bigint DEFAULT (1)::bigint,
    registryflcreturned_insdt timestamp(6) without time zone DEFAULT now(),
    registryflcreturned_upddt timestamp(6) without time zone DEFAULT now(),
    registryflcreturned_fname_i text,
    registryflcreturned_fname text
);


ALTER TABLE r477.registryflcreturned OWNER TO developer_rep;

--
-- Name: registrygrouplink; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrygrouplink (
    registrygrouplink_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    registry_pid bigint NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrygrouplink_insdt timestamp without time zone NOT NULL,
    registrygrouplink_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registrygrouplink OWNER TO developer_rep;

--
-- Name: TABLE registrygrouplink; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registrygrouplink IS 'Связь реестров';


--
-- Name: COLUMN registrygrouplink.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrygrouplink.registry_id IS 'Подчиненный реестр';


--
-- Name: COLUMN registrygrouplink.registry_pid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrygrouplink.registry_pid IS 'Родительский реестр';


--
-- Name: registrygrouplink_registrygrouplink_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registrygrouplink ALTER COLUMN registrygrouplink_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registrygrouplink_registrygrouplink_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryidentify; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryidentify (
    registryidentify_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    evn_id bigint,
    registryidentify_idcase text,
    registryidentify_id_pac text,
    registryidentify_smook text,
    registryidentify_vpolis text,
    registryidentify_spolis text,
    registryidentify_npolis text,
    registryidentify_smoogrn text,
    registryidentify_date_1 text,
    registryidentify_date_2 text,
    pmuser_insid bigint DEFAULT (1)::bigint,
    pmuser_updid bigint DEFAULT (1)::bigint,
    registryidentify_insdt timestamp(6) without time zone DEFAULT now(),
    registryidentify_upddt timestamp(6) without time zone DEFAULT now(),
    registryidentify_upload_filename text,
    registryidentify_code text,
    registry_id_fact bigint
);


ALTER TABLE r477.registryidentify OWNER TO developer_rep;

--
-- Name: registryidentify_registryidentify_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

CREATE SEQUENCE r477.registryidentify_registryidentify_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1;


ALTER SEQUENCE r477.registryidentify_registryidentify_id_seq OWNER TO developer_rep;

--
-- Name: registryidentify_registryidentify_id_seq; Type: SEQUENCE OWNED BY; Schema: r477; Owner: developer_rep
--

ALTER SEQUENCE r477.registryidentify_registryidentify_id_seq OWNED BY r477.registryidentify.registryidentify_id;


--
-- Name: registrylpubuilding; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrylpubuilding (
    registrylpubuilding_id bigint NOT NULL,
    registry_id bigint,
    lpubuilding_id bigint NOT NULL,
    registryqueue_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrylpubuilding_insdt timestamp without time zone NOT NULL,
    registrylpubuilding_upddt timestamp without time zone NOT NULL
);


ALTER TABLE r477.registrylpubuilding OWNER TO developer_rep;

--
-- Name: registrylpubuilding_registrylpubuilding_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registrylpubuilding ALTER COLUMN registrylpubuilding_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registrylpubuilding_registrylpubuilding_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registrylpusection; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrylpusection (
    registrylpusection_id bigint NOT NULL,
    registry_id bigint,
    lpusection_id bigint NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrylpusection_insdt timestamp without time zone NOT NULL,
    registrylpusection_upddt timestamp without time zone NOT NULL,
    registryqueue_id bigint
);


ALTER TABLE r477.registrylpusection OWNER TO developer_rep;

--
-- Name: TABLE registrylpusection; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registrylpusection IS 'Связь реестра с отделением ЛПУ';


--
-- Name: COLUMN registrylpusection.registrylpusection_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrylpusection.registrylpusection_id IS 'Идентификатор';


--
-- Name: COLUMN registrylpusection.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrylpusection.registry_id IS 'Реестр';


--
-- Name: COLUMN registrylpusection.lpusection_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrylpusection.lpusection_id IS 'Отделение';


--
-- Name: registrylpusection_registrylpusection_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registrylpusection ALTER COLUMN registrylpusection_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registrylpusection_registrylpusection_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registrylpuunit; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrylpuunit (
    registrylpuunit_id bigint NOT NULL,
    registry_id bigint,
    lpuunit_id bigint NOT NULL,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrylpuunit_insdt timestamp without time zone NOT NULL,
    registrylpuunit_upddt timestamp without time zone NOT NULL,
    registryqueue_id bigint
);


ALTER TABLE r477.registrylpuunit OWNER TO developer_rep;

--
-- Name: registrylpuunit_registrylpuunit_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registrylpuunit ALTER COLUMN registrylpuunit_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registrylpuunit_registrylpuunit_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registrynopolis; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registrynopolis (
    registry_id bigint NOT NULL,
    evn_id bigint NOT NULL,
    person_id bigint NOT NULL,
    evn_code character varying(50),
    person_surname character varying(30) NOT NULL,
    person_firname character varying(30),
    person_secname character varying(30),
    person_birthday timestamp without time zone,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registrynopolis_insdt timestamp without time zone NOT NULL,
    registrynopolis_upddt timestamp without time zone NOT NULL,
    evn_sid bigint
);


ALTER TABLE r477.registrynopolis OWNER TO developer_rep;

--
-- Name: TABLE registrynopolis; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registrynopolis IS 'Случаи без полиса в реестрах';


--
-- Name: COLUMN registrynopolis.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.registry_id IS 'идентификатор реестра';


--
-- Name: COLUMN registrynopolis.evn_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.evn_id IS 'идентификатор события';


--
-- Name: COLUMN registrynopolis.person_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.person_id IS 'идентификатор человека';


--
-- Name: COLUMN registrynopolis.evn_code; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.evn_code IS 'код события';


--
-- Name: COLUMN registrynopolis.person_surname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.person_surname IS 'фамилия';


--
-- Name: COLUMN registrynopolis.person_firname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.person_firname IS 'имя';


--
-- Name: COLUMN registrynopolis.person_secname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.person_secname IS 'отчество';


--
-- Name: COLUMN registrynopolis.person_birthday; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registrynopolis.person_birthday IS 'дата рождения';


--
-- Name: registryperson; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryperson (
    registry_id bigint NOT NULL,
    maxevnperson_id bigint NOT NULL,
    person_id bigint NOT NULL,
    person_surname character varying(30) NOT NULL,
    person_firname character varying(30),
    person_secname character varying(30),
    person_birthday timestamp without time zone,
    polis_id bigint NOT NULL,
    polis_ser character varying(10),
    polis_num character varying(30),
    polis_begdate timestamp without time zone,
    polis_enddate timestamp without time zone,
    orgsmo_id bigint,
    person2_id bigint,
    person2_surname character varying(30),
    person2_firname character varying(30),
    person2_secname character varying(30),
    person2_birthday timestamp without time zone,
    polis2_id bigint,
    polis2_ser character varying(10),
    polis2_num character varying(30),
    polis2_begdate timestamp without time zone,
    polis2_enddate timestamp without time zone,
    orgsmo2_id bigint,
    maxevnperson_setdate timestamp without time zone,
    polis_numint bigint,
    registryperson_isdifferent bigint,
    registryperson_ismerge bigint
);


ALTER TABLE r477.registryperson OWNER TO developer_rep;

--
-- Name: TABLE registryperson; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registryperson IS 'Ошибки персданных в реестрах';


--
-- Name: COLUMN registryperson.registry_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.registry_id IS 'идентификатор реестра';


--
-- Name: COLUMN registryperson.person_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person_id IS 'идентификатор человека';


--
-- Name: COLUMN registryperson.person_surname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person_surname IS 'фамилия';


--
-- Name: COLUMN registryperson.person_firname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person_firname IS 'имя';


--
-- Name: COLUMN registryperson.person_secname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person_secname IS 'отчество';


--
-- Name: COLUMN registryperson.person_birthday; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person_birthday IS 'дата рождения';


--
-- Name: COLUMN registryperson.polis_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis_id IS 'идентификатор полиса';


--
-- Name: COLUMN registryperson.polis_ser; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis_ser IS 'серия полиса';


--
-- Name: COLUMN registryperson.polis_num; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis_num IS 'номер полиса';


--
-- Name: COLUMN registryperson.polis_begdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis_begdate IS 'дата начала действия полиса';


--
-- Name: COLUMN registryperson.polis_enddate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis_enddate IS 'дата окончания действия полиса';


--
-- Name: COLUMN registryperson.orgsmo_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.orgsmo_id IS 'идентификатор справочника страховых организаций';


--
-- Name: COLUMN registryperson.person2_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person2_id IS 'идентификатор человека (двойник)';


--
-- Name: COLUMN registryperson.person2_surname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person2_surname IS 'фамилия (двойник)';


--
-- Name: COLUMN registryperson.person2_firname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person2_firname IS 'Имя (двойник)';


--
-- Name: COLUMN registryperson.person2_secname; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person2_secname IS 'отчество (двойник)';


--
-- Name: COLUMN registryperson.person2_birthday; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.person2_birthday IS 'Дата рождения (двойник)';


--
-- Name: COLUMN registryperson.polis2_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis2_id IS 'идентификатор полиса (двойник)';


--
-- Name: COLUMN registryperson.polis2_ser; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis2_ser IS 'серия полиса (двойник)';


--
-- Name: COLUMN registryperson.polis2_num; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis2_num IS 'номер полиса (двойник)';


--
-- Name: COLUMN registryperson.polis2_begdate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis2_begdate IS 'дата начала действия полиса (двойник)';


--
-- Name: COLUMN registryperson.polis2_enddate; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.polis2_enddate IS 'дата окончания действия полиса (двойник)';


--
-- Name: COLUMN registryperson.orgsmo2_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.orgsmo2_id IS 'страховая организация (двойник)';


--
-- Name: COLUMN registryperson.registryperson_isdifferent; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.registryperson_isdifferent IS 'Различающиеся';


--
-- Name: COLUMN registryperson.registryperson_ismerge; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryperson.registryperson_ismerge IS 'Отправлены на объединение';


--
-- Name: registryqueue; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryqueue (
    registryqueue_id bigint NOT NULL,
    registry_id bigint,
    registrytype_id bigint NOT NULL,
    lpu_id bigint NOT NULL,
    registry_begdate timestamp without time zone NOT NULL,
    registry_enddate timestamp without time zone NOT NULL,
    orgsmo_id bigint,
    lpuunitset_id bigint,
    registry_num character varying(10) NOT NULL,
    registry_accdate timestamp without time zone NOT NULL,
    registrystatus_id bigint,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryqueue_insdt timestamp without time zone NOT NULL,
    registryqueue_upddt timestamp without time zone NOT NULL,
    org_mid bigint,
    orgrschet_mid bigint,
    katnasel_id bigint,
    dispclass_id bigint,
    orgrschet_id bigint,
    reform integer,
    registry_isrepeated bigint,
    registry_rid bigint,
    paytype_id bigint,
    registry_iszno bigint,
    registry_counterr bigint,
    lpubuilding_id bigint,
    lpu_cid bigint
);


ALTER TABLE r477.registryqueue OWNER TO developer_rep;

--
-- Name: COLUMN registryqueue.org_mid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.org_mid IS 'Организация, оплачивающая реестр';


--
-- Name: COLUMN registryqueue.orgrschet_mid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.orgrschet_mid IS 'Счет организации, оплачивающей реестр';


--
-- Name: COLUMN registryqueue.katnasel_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.katnasel_id IS 'категория населения';


--
-- Name: COLUMN registryqueue.dispclass_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.dispclass_id IS 'Вид диспансеризации';


--
-- Name: COLUMN registryqueue.orgrschet_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.orgrschet_id IS 'идентификатор расчетного счета';


--
-- Name: COLUMN registryqueue.registry_isrepeated; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.registry_isrepeated IS 'Флаг Повторная подача';


--
-- Name: COLUMN registryqueue.registry_rid; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.registry_rid IS 'Флаг Повторная подача';


--
-- Name: COLUMN registryqueue.paytype_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.paytype_id IS 'Тип оплаты';


--
-- Name: COLUMN registryqueue.registry_counterr; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryqueue.registry_counterr IS 'Количество записей с ошибками данных, не вошедших в реестр';


--
-- Name: registryqueue_registryqueue_id_seq; Type: SEQUENCE; Schema: r477; Owner: developer_rep
--

ALTER TABLE r477.registryqueue ALTER COLUMN registryqueue_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME r477.registryqueue_registryqueue_id_seq
    START WITH 4770101000000001
    INCREMENT BY 1
    MINVALUE 4770101000000001
    MAXVALUE 4770101999999999
    CACHE 1
);


--
-- Name: registryqueuehistory; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryqueuehistory (
    registryqueuehistory_id bigint NOT NULL,
    registry_id bigint,
    registrytype_id bigint NOT NULL,
    lpu_id bigint NOT NULL,
    registry_begdate timestamp without time zone NOT NULL,
    registry_enddate timestamp without time zone NOT NULL,
    orgsmo_id bigint,
    lpuunitset_id bigint,
    registry_num character varying(10) NOT NULL,
    registry_accdate timestamp without time zone NOT NULL,
    registryqueuehistory_isupdate bigint NOT NULL,
    registryqueue_position integer,
    registryqueuehistory_begdt timestamp without time zone,
    registryqueuehistory_enddt timestamp without time zone,
    error_code character varying(20),
    error_message character varying(4000),
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryqueuehistory_insdt timestamp without time zone NOT NULL,
    registryqueuehistory_upddt timestamp without time zone NOT NULL,
    katnasel_id bigint,
    orgrschet_id bigint,
    registry_isrepeated bigint,
    registry_rid bigint,
    paytype_id bigint,
    registry_iszno bigint,
    registry_counterr bigint,
    lpubuilding_id bigint,
    lpu_cid bigint
);


ALTER TABLE r477.registryqueuehistory OWNER TO developer_rep;

--
-- Name: registryusluga; Type: TABLE; Schema: r477; Owner: developer_rep
--

CREATE TABLE r477.registryusluga (
    evn_id bigint NOT NULL,
    maxevn_id bigint NOT NULL,
    registry_id bigint NOT NULL,
    usluga_id bigint,
    uslugasectiontariff_id bigint,
    registryusluga_ukl double precision,
    evnusluga_upddate timestamp without time zone,
    pmuser_insid bigint NOT NULL,
    pmuser_updid bigint NOT NULL,
    registryusluga_insdt timestamp without time zone NOT NULL,
    registryusluga_upddt timestamp without time zone NOT NULL,
    evnusluga_id bigint NOT NULL,
    uslugacomplex_id bigint,
    registryusluga_setdate timestamp without time zone,
    uslugacomplextariff_id bigint,
    registryusluga_tariff numeric(20,2),
    registryusluga_sum numeric(20,2),
    registryusluga_kol double precision,
    medstafffact_id bigint,
    diag_id bigint,
    lpusectionprofile_id bigint,
    lpusection_id bigint,
    registryusluga_codeusl character varying(50),
    region_data jsonb,
    registryusluga_disdate timestamp without time zone
);


ALTER TABLE r477.registryusluga OWNER TO developer_rep;

--
-- Name: TABLE registryusluga; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON TABLE r477.registryusluga IS 'Услуги в реестрах';


--
-- Name: COLUMN registryusluga.uslugacomplex_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryusluga.uslugacomplex_id IS 'Идентификатор комплексной услуги';


--
-- Name: COLUMN registryusluga.uslugacomplextariff_id; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON COLUMN r477.registryusluga.uslugacomplextariff_id IS 'Идентификатор комплексной услуги';


--
-- Name: v_militarycategory; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.v_militarycategory AS
 SELECT militarycategory.militarycategory_id,
    militarycategory.militarycategory_code,
    militarycategory.militarycategory_name,
    militarycategory.militarycategory_begdate,
    militarycategory.militarycategory_enddate,
    militarycategory.pmuser_insid,
    militarycategory.pmuser_updid,
    militarycategory.militarycategory_insdt,
    militarycategory.militarycategory_upddt
   FROM r477.militarycategory
  WHERE (1 = 1);


ALTER VIEW r477.v_militarycategory OWNER TO r477_role;

--
-- Name: VIEW v_militarycategory; Type: COMMENT; Schema: r477; Owner: r477_role
--

COMMENT ON VIEW r477.v_militarycategory IS 'Autogen';


--
-- Name: v_orgmilitarytype; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_orgmilitarytype AS
 SELECT orgmilitarytype.orgmilitarytype_id,
    orgmilitarytype.orgmilitarytype_code,
    orgmilitarytype.orgmilitarytype_name,
    orgmilitarytype.klcountry_id,
    orgmilitarytype.orgmilitarytype_begdate,
    orgmilitarytype.orgmilitarytype_enddate,
    orgmilitarytype.pmuser_insid,
    orgmilitarytype.pmuser_updid,
    orgmilitarytype.orgmilitarytype_insdt,
    orgmilitarytype.orgmilitarytype_upddt
   FROM r477.orgmilitarytype
  WHERE ((1 = 1) AND ((orgmilitarytype.orgmilitarytype_deleted = 1) OR (orgmilitarytype.orgmilitarytype_deleted IS NULL)));


ALTER VIEW r477.v_orgmilitarytype OWNER TO developer_rep;

--
-- Name: VIEW v_orgmilitarytype; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_orgmilitarytype IS 'Autogen';


--
-- Name: v_orgmilitarytypelink; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_orgmilitarytypelink AS
 SELECT orgmilitarytypelink.orgmilitarytypelink_id,
    orgmilitarytypelink.orgmilitarytype_id,
    orgmilitarytypelink.org_id,
    orgmilitarytypelink.pmuser_insid,
    orgmilitarytypelink.pmuser_updid,
    orgmilitarytypelink.orgmilitarytypelink_insdt,
    orgmilitarytypelink.orgmilitarytypelink_upddt
   FROM r477.orgmilitarytypelink
  WHERE (1 = 1);


ALTER VIEW r477.v_orgmilitarytypelink OWNER TO developer_rep;

--
-- Name: VIEW v_orgmilitarytypelink; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_orgmilitarytypelink IS 'Autogen';


--
-- Name: v_registry; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.v_registry AS
 SELECT registry.registry_id,
    registry.registrytype_id,
    registry.lpu_id,
    registry.registry_begdate,
    registry.registry_enddate,
    registry.orgsmo_id,
    registry.lpuunitset_id,
    lpuunitset.lpuunitset_code,
    orgsmo.orgsmo_nick AS orgsmo_name,
    registry.registry_num,
    registry.registry_accdate,
    registry.registrystatus_id,
    registry.registry_sum,
    registry.registry_isactive,
    registry.registry_errorcount,
    registry.registry_errorcommoncount,
    registry.registry_recordcount,
    registry.registry_isneedreform,
    registry.registry_downdt,
    registry.pmuser_insid,
    registry.pmuser_updid,
    registry.registry_insdt,
    registry.registry_upddt,
    registry.pmuser_downid,
    registry.paytype_id,
    registry.org_mid,
    registry.orgrschet_mid,
    registry.katnasel_id,
    registry.registry_filenum,
    registry.dispclass_id,
    registry.orgrschet_id,
    registry.registrycheckstatus_id,
    registry.registrygrouptype_id,
    registry.registry_isrepeated,
    registry.registry_rid,
    registry.registry_persfincount,
    registry.registry_persfinpaycount,
    registry.registry_persfinsum,
    registry.registry_exportsign,
    registry.registry_xmlexportpath,
    registry.registry_iszno,
    registry.registry_counterr,
    registry.lpubuilding_id,
    registry.registry_sumpaid,
    registry.registry_islocked,
    registry.registry_packnum,
    registrydata.registry_sumnoerr,
    registry.lpu_cid
   FROM (((r477.registry registry
     LEFT JOIN dbo.v_orgsmo orgsmo ON ((orgsmo.orgsmo_id = registry.orgsmo_id)))
     LEFT JOIN dbo.lpuunitset ON ((lpuunitset.lpuunitset_id = registry.lpuunitset_id)))
     LEFT JOIN LATERAL ( SELECT (sum(registrydata_1.registrydata_itogsum))::numeric AS registry_sumnoerr
           FROM r477.registrydata registrydata_1
          WHERE (registrydata_1.registry_id = registry.registry_id)) registrydata ON (true))
  WHERE ((registry.registry_deleted = 1) OR (registry.registry_deleted IS NULL));


ALTER VIEW r477.v_registry OWNER TO r477_role;

--
-- Name: v_registry_deleted; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.v_registry_deleted AS
 SELECT registry.registry_id,
    registry.registrytype_id,
    registry.lpu_id,
    registry.registry_begdate,
    registry.registry_enddate,
    registry.orgsmo_id,
    registry.lpuunitset_id,
    lpuunitset.lpuunitset_code,
    orgsmo.orgsmo_nick AS orgsmo_name,
    registry.registry_num,
    registry.registry_accdate,
    registry.registrystatus_id,
    registry.registry_sum,
    registry.registry_isactive,
    registry.registry_errorcount,
    registry.registry_errorcommoncount,
    registry.registry_recordcount,
    registry.registry_isneedreform,
    registry.registry_downdt,
    registry.pmuser_insid,
    registry.pmuser_updid,
    registry.registry_insdt,
    registry.registry_upddt,
    registry.pmuser_downid,
    registry.paytype_id,
    registry.org_mid,
    registry.orgrschet_mid,
    registry.dispclass_id,
    registry.registrycheckstatus_id,
    registry.katnasel_id,
    registry.orgrschet_id,
    registry.registry_isrepeated,
    registry.registry_sum AS registry_sumnoerr,
    registry.registry_sumpaid,
    registry.lpu_cid,
    registry.lpubuilding_id
   FROM ((r477.registry registry
     LEFT JOIN dbo.v_orgsmo orgsmo ON ((orgsmo.orgsmo_id = registry.orgsmo_id)))
     LEFT JOIN dbo.lpuunitset ON ((lpuunitset.lpuunitset_id = registry.lpuunitset_id)))
  WHERE (registry.registry_deleted = 2);


ALTER VIEW r477.v_registry_deleted OWNER TO r477_role;

--
-- Name: v_registrycmpnopolis; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrycmpnopolis AS
 SELECT registrycmpnopolis.registry_id,
    registrycmpnopolis.evn_id,
    registrycmpnopolis.person_id,
    registrycmpnopolis.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
   FROM r477.registrycmpnopolis
  WHERE (1 = 1);


ALTER VIEW r477.v_registrycmpnopolis OWNER TO developer_rep;

--
-- Name: VIEW v_registrycmpnopolis; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrycmpnopolis IS 'Autogen';


--
-- Name: v_registrydata; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.v_registrydata AS
 SELECT registrydata.evn_id,
    registrydata.registry_id,
    registrydata.server_id,
    registrydata.personevn_id,
    registrydata.evnclass_id,
    registrydata.numcard,
    registry.registrytype_id,
    registrytype.registrytype_name,
    registrytype.registrytype_sysnick,
    registrydata.lpusection_id,
    registrydata.registrydata_tariff,
    registrydata.registrydata_uklsum,
    registrydata.registrydata_kdfact,
    registrydata.registrydata_itogsum,
    registrydata.registrydata_ei2,
    registrydata.registrydata_g162,
    registrydata.diag_id,
    registrydata.medstafffact_id,
    registrydata.medpersonal_id,
    registrydata.medpersonal_fio,
    registry.lpu_id,
    registrydata.pmuser_insid,
    registrydata.pmuser_updid,
    registrydata.registrydata_insdt,
    registrydata.registrydata_upddt,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'surname'::text), ''::text)) AS person_surname,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'firname'::text), ''::text)) AS person_firname,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'secname'::text), ''::text)) AS person_secname,
    ((((btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'surname'::text), ''::text)) || ' '::text) || btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'firname'::text), ''::text))) || ' '::text) || btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'secname'::text), ''::text))) AS person_fio,
    (((registrydata.region_data -> 'person'::text) ->> 'birthday'::text))::timestamp without time zone AS person_birthday,
    NULL::bigint AS person_isbdz,
    ((rtrim((lpusection.lpusection_code)::text) || '. '::text) || (lpusection.lpusection_name)::text) AS lpusection_name,
    ((registrydata.evn_setdate)::date)::timestamp without time zone AS evn_setdate,
    ((registrydata.evn_disdate)::date)::timestamp without time zone AS evn_disdate,
    registrydata.registrydata_kdpay,
    registrydata.registrydata_kdplan,
    registrydata.evn_rid,
    registrydata.person_id,
    registrydata.lpusectionprofile_id,
    registrydata.lpusectionprofile_code,
    registrydata.paid_id,
    registrydata.usluga_id,
    registrydata.evnsection_isadultescort,
    registrydata.registrydata_double,
    registrydata.registrydata_deleted,
    registrydata.registrydata_ispaid,
    registrydata.uslugacomplex_id,
    registrydata.mestariff_id,
    registrydata.mesitog_id,
    registrydata.maxevn_id,
    registrydata.mestariff_value,
    registrydata.evnsection_numgroup,
    registrydata.number,
    registrydata.lpuunittype_id,
    registrydata.mesitog_value,
    registrydata.registrydata_coeffctp,
    registrydata.paymedtype_id,
    NULL::bigint AS cmpclosecard_sid,
    registrydata.registrydata_period,
    registrydata.socstatus_code,
    registrydata.mesolduslugacomplex_id,
    registrydata.koef_up,
    registrydata.koef_u,
    registrydata.registrydata_prer,
    registrydata.registrydata_iszno,
    registrydata.evn_disdate AS evnpl_lastvizitdt,
    btrim(((COALESCE(((registrydata.region_data -> 'polis'::text) ->> 'spolis'::text), ''::text) || ' '::text) || ((registrydata.region_data -> 'polis'::text) ->> 'npolis'::text))) AS snpolis,
    registrydata.orgsmo_id,
    COALESCE(dir.lpu_did, (((registrydata.region_data -> 'direction'::text) ->> 'lpu_did'::text))::bigint) AS lpu_did,
    NULL::text AS treatmentclass_name,
    concat((registrydata.region_data ->> 'tariff_code'::text), ' ', (registrydata.region_data ->> 'tariff_name'::text)) AS commentary,
    registrydata.needreform,
    vz.vizittype_id,
    vz.vizittype_name,
    ((registrydata.region_data -> 'polis'::text) ->> 'npolis'::text) AS polis_num,
        CASE
            WHEN ((registrydata.region_data ->> 'item_type'::text) = 'stac'::text) THEN ( SELECT string_agg(('K'::text || (v_evnsectionkslplink.evnsectionkslplink_code)::text), ','::text) AS string_agg
               FROM dbo.v_evnsectionkslplink
              WHERE (v_evnsectionkslplink.evnsection_id = registrydata.evn_id))
            ELSE NULL::text
        END AS kslp,
    (registrydata.region_data ->> 'n_ksg'::text) AS n_ksg,
    registrydata.parentevnclass_id
   FROM (((((r477.registrydata
     JOIN r477.registry ON ((registrydata.registry_id = registry.registry_id)))
     JOIN dbo.lpusection ON ((lpusection.lpusection_id = registrydata.lpusection_id)))
     JOIN dbo.registrytype ON ((registry.registrytype_id = registrytype.registrytype_id)))
     LEFT JOIN dbo.v_evndirection dir ON ((dir.evndirection_id = (((registrydata.region_data -> 'direction'::text) ->> 'direction_id'::text))::bigint)))
     LEFT JOIN dbo.vizittype vz ON ((registrydata.vizittype_id = vz.vizittype_id)));


ALTER VIEW r477.v_registrydata OWNER TO r477_role;

--
-- Name: v_registrydatacmp; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrydatacmp AS
 SELECT registrydatacmp.cmpclosecard_id,
    registrydatacmp.registry_id,
    registrydatacmp.numcard,
    registrydatacmp.person_id,
    registrydatacmp.lpusection_id,
    registrydatacmp.lpusectionprofile_id,
    registrydatacmp.medpersonal_id,
    registrydatacmp.registrydatacmp_tariff,
    registrydatacmp.registrydatacmp_ukl,
    registrydatacmp.registrydatacmp_uklsum,
    registrydatacmp.registrydatacmp_itogsum,
    registrydatacmp.omssprterr_id,
    registrydatacmp.address_id,
    registrydatacmp.registrydatacmp_isprev,
    registrydatacmp.registrydatacmp_isambul,
    registrydatacmp.pmuser_insid,
    registrydatacmp.pmuser_updid,
    registrydatacmp.registrydatacmp_insdt,
    registrydatacmp.registrydatacmp_upddt,
    registrydatacmp.diag_id,
    registrydatacmp.medpersonal_fio,
    registrydatacmp.medpersonal_snils,
    registrydatacmp.omssprterr_code,
    registrydatacmp.evn_disdate,
    registrydatacmp.lpusection_code,
    registrydatacmp.lpusectionprofile_code,
    registrydatacmp.medpersonal_code,
    registrydatacmp.polis_begdate,
    registrydatacmp.polis_enddate,
    registrydatacmp.orgsmo_id,
    registrydatacmp.medspec_id,
    registrydatacmp.cmpclosecard_upddate,
    registrydatacmp.polis_id,
    registrydatacmp.polis_ser,
    registrydatacmp.polis_num,
    registrydatacmp.evn_setdate,
    registrydatacmp.needreform,
    registrydatacmp.evnps_iscont,
    registrydatacmp.prehospdirect_id,
    registrydatacmp.registrydatacmp_isperev,
    registrydatacmp.cmpresult_id,
    registrydatacmp.registrydatacmp_rownum,
    registrydatacmp.registrydatacmp_double,
    registrydatacmp.evnsection_isadultescort,
    registrydatacmp.registrydatacmp_ispaid,
    registrydatacmp.uslugacomplex_id,
    registrydatacmp.registrydatacmp_tarif_r,
    registrydatacmp.registrydatacmp_tarif_f,
    registrydatacmp.registrydatacmp_sum_r,
    registrydatacmp.registrydatacmp_sum_f,
    registrydatacmp.registrydatacmp_ei2,
    registrydatacmp.paymedtype_id,
    registrydatacmp.number,
    registrydatacmp.registrydatacmp_kdfact,
    registrydatacmp.registrydatacmp_kdplan,
    registrydatacmp.registrydatacmp_kdpay,
    registrydatacmp.registrydatacmp_g162,
    registrydatacmp.maxevn_id,
    registrydatacmp.evnsection_numgroup,
    registrydatacmp.lpuunittype_id,
    registrydatacmp.registrydatacmp_coeffctp,
    registrydatacmp.registrydatacmp_ispersfin,
    registrydatacmp.cmpclosecard_sid
   FROM r477.registrydatacmp
  WHERE ((1 = 1) AND ((registrydatacmp.registrydatacmp_deleted = 1) OR (registrydatacmp.registrydatacmp_deleted IS NULL)));


ALTER VIEW r477.v_registrydatacmp OWNER TO developer_rep;

--
-- Name: VIEW v_registrydatacmp; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrydatacmp IS 'Autogen';


--
-- Name: v_registrydatasl; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrydatasl AS
 SELECT registrydatasl.registrydatasl_id,
    registrydatasl.registry_id,
    registrydatasl.registrydatasl_rownum,
    registrydatasl.evn_id,
    registrydatasl.evn_rid,
    registrydatasl.maxevn_id,
    registrydatasl.person_id,
    registrydatasl.lpu_id,
    registrydatasl.lpuunittype_id,
    registrydatasl.personevn_id,
    registrydatasl.evn_setdate,
    registrydatasl.evn_disdate,
    registrydatasl.omssprterr_id,
    registrydatasl.orgsmo_id,
    registrydatasl.registrydatasl_sum,
    registrydatasl.pmuser_insid,
    registrydatasl.pmuser_updid,
    registrydatasl.registrydatasl_insdt,
    registrydatasl.registrydatasl_upddt,
    registrydatasl.kd_z,
    registrydatasl.server_id,
    registrydatasl.numcard,
    registrydatasl.leavetype_id,
    registrydatasl.resultdesease_id,
    registrydatasl.vb_p
   FROM r477.registrydatasl
  WHERE (1 = 1);


ALTER VIEW r477.v_registrydatasl OWNER TO developer_rep;

--
-- Name: VIEW v_registrydatasl; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrydatasl IS 'Autogen';


--
-- Name: v_registrydatatemp; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrydatatemp AS
 SELECT registrydatatemp.evn_id,
    registrydatatemp.registry_id,
    registrydatatemp.numcard,
    registrydatatemp.evn_rid,
    registrydatatemp.person_id,
    registrydatatemp.lpusection_id,
    registrydatatemp.lpusectionprofile_id,
    registrydatatemp.medpersonal_id,
    registrydatatemp.medpersonal_fio,
    registrydatatemp.registrydata_tariff,
    registrydatatemp.registrydata_kdfact,
    registrydatatemp.registrydata_kdplan,
    registrydatatemp.registrydata_kdpay,
    registrydatatemp.registrydata_ukl,
    registrydatatemp.registrydata_uklsum,
    registrydatatemp.registrydata_itogsum,
    registrydatatemp.registrydata_ei2,
    registrydatatemp.registrydata_g162,
    registrydatatemp.omssprterr_id,
    registrydatatemp.omssprterr_code,
    registrydatatemp.address_id,
    registrydatatemp.person_address,
    registrydatatemp.person_surname,
    registrydatatemp.person_firname,
    registrydatatemp.person_secname,
    registrydatatemp.person_birthday,
    registrydatatemp.polis_id,
    registrydatatemp.polis_ser,
    registrydatatemp.polis_num,
    registrydatatemp.evndiagps_id,
    registrydatatemp.registrydata_isprev,
    registrydatatemp.leavetype_id,
    registrydatatemp.resultdesease_id,
    registrydatatemp.leavecause_id,
    registrydatatemp.registrydata_isambul,
    registrydatatemp.diag_id,
    registrydatatemp.vizittype_id,
    registrydatatemp.resultclass_id,
    registrydatatemp.pmuser_insid,
    registrydatatemp.pmuser_updid,
    registrydatatemp.registrydata_insdt,
    registrydatatemp.registrydata_upddt,
    registrydatatemp.registrydata_deleted,
    registrydatatemp.evn_disdate,
    registrydatatemp.lpusection_code,
    registrydatatemp.lpusectionprofile_code,
    registrydatatemp.medpersonal_code,
    registrydatatemp.polis_begdate,
    registrydatatemp.polis_enddate,
    registrydatatemp.orgsmo_id,
    registrydatatemp.medspec_id,
    registrydatatemp.evn_upddate,
    registrydatatemp.dopdispspec_id,
    registrydatatemp.err_firname,
    registrydatatemp.err_surname,
    registrydatatemp.err_birthday,
    registrydatatemp.err_personsex,
    registrydatatemp.err_socstatus,
    registrydatatemp.err_persondoc,
    registrydatatemp.err_personinn,
    registrydatatemp.err_result,
    registrydatatemp.err_dates,
    registrydatatemp.err_codes,
    registrydatatemp.err_lpusection,
    registrydatatemp.err_levelmes,
    registrydatatemp.err_codemes,
    registrydatatemp.err_codedrug,
    registrydatatemp.err_inonojob,
    registrydatatemp.err_doublepolis,
    registrydatatemp.err_inoterprmes,
    registrydatatemp.err_profilemes,
    registrydatatemp.err_maxsection,
    registrydatatemp.err_sopdesease,
    registrydatatemp.err_doubledate,
    registrydatatemp.err_nocorrres,
    registrydatatemp.err_terrisempty,
    registrydatatemp.err_uklnull,
    registrydatatemp.err_badorgsmo,
    registrydatatemp.err_omssprterr,
    registrydatatemp.err_uslinvizit,
    registrydatatemp.err_codediag,
    registrydatatemp.err_lpusectionclose,
    registrydatatemp.err_kladrcode,
    registrydatatemp.err_vizitplsetdate,
    registrydatatemp.err_medspecoms,
    registrydatatemp.err_meddolvrach,
    registrydatatemp.err_deseasetype,
    registrydatatemp.err_firstmedhelp,
    registrydatatemp.err_purvizit,
    registrydatatemp.err_koledmedhelp,
    registrydatatemp.err_edmedhelp,
    registrydatatemp.err_personcard_code,
    registrydatatemp.err_secname,
    registrydatatemp.err_inoterinrb,
    registrydatatemp.err_jobpolisold,
    registrydatatemp.err_nojobsmoaddr,
    registrydatatemp.err_diagoms,
    registrydatatemp.err_polisnum,
    registrydatatemp.err_statusage,
    registrydatatemp.err_jobchild,
    registrydatatemp.err_inodiag,
    registrydatatemp.err_sexusluga,
    registrydatatemp.err_diagcentr,
    registrydatatemp.err_doublevizit,
    registrydatatemp.err_doublevizitprev,
    registrydatatemp.err_doublevizitstac,
    registrydatatemp.err_childortoped,
    registrydatatemp.err_norgn,
    registrydatatemp.err_regcity,
    registrydatatemp.err_numpolis,
    registrydatatemp.err_endsmo,
    registrydatatemp.err_inosmo,
    registrydatatemp.err_subrgn,
    registrydatatemp.usluga_id,
    registrydatatemp.err_badusluga,
    registrydatatemp.err_nookato,
    registrydatatemp.registrydata_rownum,
    registrydatatemp.err_medpers_badsnils,
    registrydatatemp.evn_setdate,
    registrydatatemp.uslugacomplex_id,
    registrydatatemp.err_nevsostlech,
    registrydatatemp.err_nresult,
    registrydatatemp.err_nadres,
    registrydatatemp.err_oneevnpsdiag,
    registrydatatemp.err_reshosp,
    registrydatatemp.err_resdedease,
    registrydatatemp.err_lpusecprofcode,
    registrydatatemp.err_certificate,
    registrydatatemp.mestariff_id,
    registrydatatemp.mesitog_id,
    registrydatatemp.maxevn_id,
    registrydatatemp.mestariff_value,
    registrydatatemp.evnsection_numgroup,
    registrydatatemp.number,
    registrydatatemp.lpuunittype_id,
    registrydatatemp.mesitog_value,
    registrydatatemp.registrydatatemp_coeffctp,
    registrydatatemp.err_no_medcode_usl,
    registrydatatemp.err_no_snils,
    registrydatatemp.err_notuslugalpu,
    registrydatatemp.err_vidpom,
    registrydatatemp.server_id,
    registrydatatemp.personevn_id,
    registrydatatemp.registrydatatemp_ispersfin,
    registrydatatemp.err_nookatowarn,
    registrydatatemp.cmpclosecard_sid,
    registrydatatemp.registrydata_period,
    registrydatatemp.socstatus_code,
    registrydatatemp.mesolduslugacomplex_id,
    registrydatatemp.koef_up,
    registrydatatemp.koef_u,
    registrydatatemp.registrydata_prer,
    registrydatatemp.err_noevnsecksg,
    registrydatatemp.evnmax_id,
    registrydatatemp.registrydata_iszno,
    registrydatatemp.err_nofulldirection,
    registrydatatemp.err_direction,
    registrydatatemp.err_nodisp,
    registrydatatemp.err_noonkodiaginsmp,
    registrydatatemp.err_polis,
    registrydatatemp.err_notevnprescr,
    registrydatatemp.err_nocarddn,
    registrydatatemp.err_nonextvizit
   FROM r477.registrydatatemp
  WHERE (1 = 1);


ALTER VIEW r477.v_registrydatatemp OWNER TO developer_rep;

--
-- Name: VIEW v_registrydatatemp; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrydatatemp IS 'Autogen';


--
-- Name: v_registrydeleted_data; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.v_registrydeleted_data AS
 SELECT registrydata.evn_id,
    registrydata.registry_id,
    registrydata.evnclass_id,
    registrydata.server_id,
    registrydata.personevn_id,
    registrydata.numcard,
    registry.registrytype_id,
    registrytype.registrytype_name,
    registrytype.registrytype_sysnick,
    registrydata.lpusection_id,
    registrydata.registrydata_tariff,
    registrydata.registrydata_uklsum,
    registrydata.registrydata_kdfact,
    registrydata.registrydata_kdpay,
    registrydata.registrydata_kdplan,
    registrydata.registrydata_itogsum,
    registrydata.registrydata_ei2,
    registrydata.registrydata_g162,
    registrydata.diag_id,
    registrydata.medstafffact_id,
    registrydata.medpersonal_id,
    registrydata.medpersonal_fio,
    registrydata.medspec_id,
    registry.lpu_id,
    registrydata.pmuser_insid,
    registrydata.pmuser_updid,
    registrydata.registrydata_insdt,
    registrydata.registrydata_upddt,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'surname'::text), ''::text)) AS person_surname,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'firname'::text), ''::text)) AS person_firname,
    btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'secname'::text), ''::text)) AS person_secname,
    ((((btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'surname'::text), ''::text)) || ' '::text) || btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'firname'::text), ''::text))) || ' '::text) || btrim(COALESCE(((registrydata.region_data -> 'person'::text) ->> 'secname'::text), ''::text))) AS person_fio,
    (((registrydata.region_data -> 'person'::text) ->> 'birthday'::text))::timestamp without time zone AS person_birthday,
    NULL::bigint AS person_isbdz,
    ((rtrim((lpusection.lpusection_code)::text) || '. '::text) || (lpusection.lpusection_name)::text) AS lpusection_name,
    ((registrydata.evn_setdate)::date)::timestamp without time zone AS evn_setdate,
    ((registrydata.evn_disdate)::date)::timestamp without time zone AS evn_disdate,
    registrydata.evn_rid,
    registrydata.person_id,
    registrydata.lpusectionprofile_code,
    registrydata.orgsmo_id,
    registrydata.address_id,
    registrydata.omssprterr_id,
    registrydata.registrydata_ukl,
    registrydata.registrydata_isprev,
    registrydata.lpusectionprofile_id,
    registrydata.maxevn_id,
    registrydata.omssprterr_code,
    registrydata.medpersonal_code,
    registrydata.polis_begdate,
    registrydata.polis_enddate,
    registrydata.registrydata_rownum,
    registrydata.registrydata_deleted,
    registrydata.registrydata_double,
    registrydata.registrydata_ispaid,
    registrydata.paymedtype_id,
    registrydata.lpuunittype_id,
    registrydata.registrydata_iszno,
    registrydata.mesitog_id,
    COALESCE(dir.lpu_did, (((registrydata.region_data -> 'direction'::text) ->> 'lpu_did'::text))::bigint) AS lpu_did,
    btrim(((COALESCE(((registrydata.region_data -> 'polis'::text) ->> 'spolis'::text), ''::text) || ' '::text) || ((registrydata.region_data -> 'polis'::text) ->> 'npolis'::text))) AS snpolis,
    concat((registrydata.region_data ->> 'tariff_code'::text), ' ', (registrydata.region_data ->> 'tariff_name'::text)) AS commentary,
    NULL::text AS treatmentclass_name,
    vz.vizittype_id,
    vz.vizittype_name,
    registrydata.evn_disdate AS evnpl_lastvizitdt,
    ''::text AS kslp,
    (registrydata.region_data ->> 'n_ksg'::text) AS n_ksg,
    registrydata.parentevnclass_id
   FROM (((((r477.registrydata registrydata
     JOIN r477.v_registry_deleted registry ON ((registrydata.registry_id = registry.registry_id)))
     LEFT JOIN dbo.lpusection ON ((lpusection.lpusection_id = registrydata.lpusection_id)))
     JOIN dbo.registrytype ON ((registry.registrytype_id = registrytype.registrytype_id)))
     LEFT JOIN dbo.v_evndirection dir ON ((dir.evndirection_id = (((registrydata.region_data -> 'direction'::text) ->> 'direction_id'::text))::bigint)))
     LEFT JOIN dbo.vizittype vz ON ((registrydata.vizittype_id = vz.vizittype_id)));


ALTER VIEW r477.v_registrydeleted_data OWNER TO r477_role;

--
-- Name: v_registrydouble; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrydouble AS
 SELECT registrydouble.registry_id,
    registrydouble.evn_id,
    registrydouble.person_id,
    registrydouble.evn_code,
    registrydouble.person_surname,
    registrydouble.person_firname,
    registrydouble.person_secname,
    registrydouble.person_birthday,
    registrydouble.pmuser_insid,
    registrydouble.pmuser_updid,
    registrydouble.registrydouble_insdt,
    registrydouble.registrydouble_upddt
   FROM r477.registrydouble
  WHERE (1 = 1);


ALTER VIEW r477.v_registrydouble OWNER TO developer_rep;

--
-- Name: VIEW v_registrydouble; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrydouble IS 'Autogen';


--
-- Name: v_registryerrorclass; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryerrorclass AS
 SELECT registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_code,
    registryerrorclass.registryerrorclass_name,
    registryerrorclass.registryerrorclass_nick,
    registryerrorclass.registryerrorclass_sysnick,
    registryerrorclass.pmuser_insid,
    registryerrorclass.pmuser_updid,
    registryerrorclass.registryerrorclass_insdt,
    registryerrorclass.registryerrorclass_upddt
   FROM r477.registryerrorclass
  WHERE (1 = 1);


ALTER VIEW r477.v_registryerrorclass OWNER TO developer_rep;

--
-- Name: VIEW v_registryerrorclass; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registryerrorclass IS 'Autogen';


--
-- Name: v_registryerrorcmp; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryerrorcmp AS
 SELECT registryerrorcmp.registry_id,
    registryerrorcmp.cmpclosecard_id,
    registryerrorcmp.registryerrortype_id,
    registryerrorcmp.lpusection_id,
    registryerrorcmp.pmuser_insid,
    registryerrorcmp.pmuser_updid,
    registryerrorcmp.registryerrorcmp_insdt,
    registryerrorcmp.registryerrorcmp_upddt,
    registryerrorcmp.registryerror_desc
   FROM r477.registryerrorcmp
  WHERE (1 = 1);


ALTER VIEW r477.v_registryerrorcmp OWNER TO developer_rep;

--
-- Name: VIEW v_registryerrorcmp; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registryerrorcmp IS 'Autogen';


--
-- Name: v_registryerrorcom; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryerrorcom AS
 SELECT registryerrorcom.registry_id,
    registryerrorcom.registryerrortype_id,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrorclass.registryerrorclass_id,
    registryerrorclass.registryerrorclass_name,
    registryerrorcom.pmuser_insid,
    registryerrorcom.pmuser_updid,
    registryerrorcom.registryerrorcom_insdt,
    registryerrorcom.registryerrorcom_upddt
   FROM ((r477.registryerrorcom registryerrorcom
     JOIN r477.registryerrortype registryerrortype ON ((registryerrortype.registryerrortype_id = registryerrorcom.registryerrortype_id)))
     JOIN dbo.registryerrorclass_in_r59 registryerrorclass ON ((registryerrorclass.registryerrorclass_id = registryerrortype.registryerrorclass_id)));


ALTER VIEW r477.v_registryerrorcom OWNER TO developer_rep;

--
-- Name: v_registryerrortfoms; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryerrortfoms AS
 SELECT registryerrortfoms.registryerrortfoms_id,
    registryerrortfoms.registry_id,
    registryerrortfoms.evn_id,
    registryerrortfoms.registryerrortype_id,
    registryerrortfoms.registryerrortype_code,
    registryerrortfoms.registryerrortfoms_fieldname,
    registryerrortfoms.registryerrortfoms_baseelement,
    registryerrortfoms.registryerrortfoms_rownum,
    registryerrortfoms.registryerrortfoms_comment,
    registryerrortfoms.registryerrortfoms_idcase,
    registryerrortfoms.pmuser_insid,
    registryerrortfoms.pmuser_updid,
    registryerrortfoms.registryerrortfoms_insdt,
    registryerrortfoms.registryerrortfoms_upddt,
    registryerrortfoms.registry_task,
    registryerrortfoms.registryerrortfomstype_id,
    registryerrortfoms.registryerrortfoms_caseguid,
    registryerrortfoms.registryerrortfoms_severity,
    registryerrortfoms.registryerrortfomslevel_id,
    registryerrortfoms.registryerrorclass_id,
    registryerrortfoms.cmpclosecard_id
   FROM r477.registryerrortfoms;


ALTER VIEW r477.v_registryerrortfoms OWNER TO developer_rep;

--
-- Name: VIEW v_registryerrortfoms; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registryerrortfoms IS 'Autogen';


--
-- Name: v_registryerrortype; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryerrortype AS
 SELECT registryerrortype.registryerrortype_id,
    registryerrortype.registryerrortype_code,
    registryerrortype.registryerrortype_name,
    registryerrortype.registryerrortype_descr,
    registryerrortype.registryerrortype_sysnick,
    registryerrortype.registryerrorclass_id,
    registryerrortype.registryerrortype_isuser,
    registryerrortype.registryerrortype_iscrit,
    registryerrortype.registryfield_percent,
    registryerrortype.registrytype_id,
    registryerrortype.pmuser_insid,
    registryerrortype.pmuser_updid,
    registryerrortype.registryerrortype_insdt,
    registryerrortype.registryerrortype_upddt
   FROM r477.registryerrortype
  WHERE (1 = 1);


ALTER VIEW r477.v_registryerrortype OWNER TO developer_rep;

--
-- Name: VIEW v_registryerrortype; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registryerrortype IS 'Autogen';


--
-- Name: v_registrygrouplink; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrygrouplink AS
 SELECT registrygrouplink.registrygrouplink_id,
    registrygrouplink.registry_id,
    registrygrouplink.registry_pid,
    registrygrouplink.pmuser_insid,
    registrygrouplink.pmuser_updid,
    registrygrouplink.registrygrouplink_insdt,
    registrygrouplink.registrygrouplink_upddt
   FROM r477.registrygrouplink
  WHERE (1 = 1);


ALTER VIEW r477.v_registrygrouplink OWNER TO developer_rep;

--
-- Name: VIEW v_registrygrouplink; Type: COMMENT; Schema: r477; Owner: developer_rep
--

COMMENT ON VIEW r477.v_registrygrouplink IS 'Autogen';


--
-- Name: v_registrylpubuilding; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrylpubuilding AS
 SELECT registrylpubuilding.registrylpubuilding_id,
    registrylpubuilding.registry_id,
    registrylpubuilding.lpubuilding_id,
    registrylpubuilding.registryqueue_id,
    registrylpubuilding.pmuser_insid,
    registrylpubuilding.pmuser_updid,
    registrylpubuilding.registrylpubuilding_insdt,
    registrylpubuilding.registrylpubuilding_upddt
   FROM r477.registrylpubuilding;


ALTER VIEW r477.v_registrylpubuilding OWNER TO developer_rep;

--
-- Name: v_registrylpusection; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrylpusection AS
 SELECT registrylpusection.registrylpusection_id,
    registrylpusection.registry_id,
    registrylpusection.lpusection_id,
    registrylpusection.pmuser_insid,
    registrylpusection.pmuser_updid,
    registrylpusection.registrylpusection_insdt,
    registrylpusection.registrylpusection_upddt,
    registrylpusection.registryqueue_id
   FROM r477.registrylpusection;


ALTER VIEW r477.v_registrylpusection OWNER TO developer_rep;

--
-- Name: v_registrylpuunit; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registrylpuunit AS
 SELECT registrylpuunit.registrylpuunit_id,
    registrylpuunit.registry_id,
    registrylpuunit.lpuunit_id,
    registrylpuunit.pmuser_insid,
    registrylpuunit.pmuser_updid,
    registrylpuunit.registrylpuunit_insdt,
    registrylpuunit.registrylpuunit_upddt,
    registrylpuunit.registryqueue_id
   FROM r477.registrylpuunit;


ALTER VIEW r477.v_registrylpuunit OWNER TO developer_rep;

--
-- Name: v_registrynopolis; Type: VIEW; Schema: r477; Owner: r477_role
--

CREATE VIEW r477.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,
    mesold.mesold_num AS n_ksg,
    evn.evn_setdt
   FROM ((((((r477.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)))
     LEFT JOIN dbo.v_mestariff mestariff ON ((mestariff.mestariff_id = es.mestariff_id)))
     LEFT JOIN dbo.mesold ON ((mestariff.mes_id = mesold.mes_id)));


ALTER VIEW r477.v_registrynopolis OWNER TO r477_role;

--
-- Name: v_registryperson; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryperson AS
 SELECT registryperson.registry_id,
    registryperson.maxevnperson_id,
    registryperson.person_id,
    registryperson.person_surname,
    registryperson.person_firname,
    registryperson.person_secname,
    registryperson.person_birthday,
    registryperson.polis_id,
    registryperson.polis_ser,
    registryperson.polis_num,
    registryperson.polis_begdate,
    registryperson.polis_enddate,
    registryperson.orgsmo_id,
    registryperson.person2_id,
    registryperson.person2_surname,
    registryperson.person2_firname,
    registryperson.person2_secname,
    registryperson.person2_birthday,
    registryperson.polis2_id,
    registryperson.polis2_ser,
    registryperson.polis2_num,
    registryperson.polis2_begdate,
    registryperson.polis2_enddate,
    registryperson.orgsmo2_id,
    registryperson.maxevnperson_setdate,
    registryperson.polis_numint,
    registryperson.registryperson_isdifferent,
    registryperson.registryperson_ismerge
   FROM r477.registryperson
  WHERE (1 = 1);


ALTER VIEW r477.v_registryperson OWNER TO developer_rep;

--
-- Name: v_registryqueue; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryqueue AS
 SELECT registryqueue.registryqueue_id,
        CASE
            WHEN ((registryqueue.registry_num)::text = 'test_swan'::text) THEN ('-2'::integer)::bigint
            WHEN (registryqueue.lpu_id = 101) THEN ('-1'::integer)::bigint
            ELSE row_number() OVER (ORDER BY registryqueue.registryqueue_id)
        END AS registryqueue_position,
    registryqueue.registry_id,
    registryqueue.registrytype_id,
    registryqueue.lpu_id,
    registryqueue.registry_begdate,
    registryqueue.registry_enddate,
    registryqueue.orgsmo_id,
    registryqueue.lpuunitset_id,
    registryqueue.registry_num,
    registryqueue.registry_accdate,
    registryqueue.registrystatus_id,
    registryqueue.reform,
    registryqueue.pmuser_insid,
    registryqueue.pmuser_updid,
    registryqueue.registryqueue_insdt,
    registryqueue.registryqueue_upddt,
    registryqueue.org_mid,
    registryqueue.orgrschet_mid,
    registryqueue.katnasel_id,
    registryqueue.dispclass_id,
    registryqueue.orgrschet_id,
    registryqueue.registry_isrepeated,
    registryqueue.registry_rid,
    registryqueue.paytype_id,
    registryqueue.registry_iszno,
    registryqueue.registry_counterr,
    registryqueue.lpubuilding_id,
    registryqueue.lpu_cid
   FROM r477.registryqueue;


ALTER VIEW r477.v_registryqueue OWNER TO developer_rep;

--
-- Name: v_registryqueuehistory; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryqueuehistory AS
 SELECT registryqueuehistory.registryqueuehistory_id,
    registryqueuehistory.registry_id,
    registryqueuehistory.registrytype_id,
    registryqueuehistory.lpu_id,
    registryqueuehistory.registry_begdate,
    registryqueuehistory.registry_enddate,
    registryqueuehistory.orgsmo_id,
    registryqueuehistory.lpuunitset_id,
    registryqueuehistory.registry_num,
    registryqueuehistory.registry_accdate,
    registryqueuehistory.registryqueuehistory_isupdate,
    registryqueuehistory.registryqueue_position,
    registryqueuehistory.registryqueuehistory_begdt,
    registryqueuehistory.registryqueuehistory_enddt,
    registryqueuehistory.error_code,
    ('РћС€РёР±РєР° С„РѕСЂРјРёСЂРѕРІР°РЅРёСЏ: '::text || (registryqueuehistory.error_message)::text) AS error_message,
    registryqueuehistory.pmuser_insid,
    registryqueuehistory.pmuser_updid,
    registryqueuehistory.registryqueuehistory_insdt,
    registryqueuehistory.registryqueuehistory_upddt,
    registryqueuehistory.katnasel_id,
    registryqueuehistory.orgrschet_id,
    registryqueuehistory.registry_isrepeated,
    registryqueuehistory.registry_rid,
    registryqueuehistory.paytype_id,
    registryqueuehistory.registry_iszno,
    registryqueuehistory.registry_counterr,
    registryqueuehistory.lpubuilding_id,
    registryqueuehistory.lpu_cid
   FROM r477.registryqueuehistory;


ALTER VIEW r477.v_registryqueuehistory OWNER TO developer_rep;

--
-- Name: v_registryusluga; Type: VIEW; Schema: r477; Owner: developer_rep
--

CREATE VIEW r477.v_registryusluga AS
 SELECT registryusluga.evn_id,
    registryusluga.maxevn_id,
    registryusluga.registry_id,
    registryusluga.usluga_id,
    registryusluga.uslugasectiontariff_id,
    registryusluga.registryusluga_ukl,
    registryusluga.evnusluga_upddate,
    registryusluga.pmuser_insid,
    registryusluga.pmuser_updid,
    registryusluga.registryusluga_insdt,
    registryusluga.registryusluga_upddt,
    registryusluga.evnusluga_id,
    registryusluga.uslugacomplex_id,
    registryusluga.registryusluga_setdate,
    registryusluga.uslugacomplextariff_id,
    registryusluga.registryusluga_tariff,
    registryusluga.registryusluga_sum,
    registryusluga.registryusluga_kol,
    registryusluga.medstafffact_id,
    registryusluga.diag_id,
    registryusluga.lpusectionprofile_id,
    registryusluga.lpusection_id,
    registryusluga.registryusluga_codeusl
   FROM r477.registryusluga;


ALTER VIEW r477.v_registryusluga OWNER TO developer_rep;

--
-- Name: registryidentify registryidentify_id; Type: DEFAULT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryidentify ALTER COLUMN registryidentify_id SET DEFAULT nextval('r477.registryidentify_registryidentify_id_seq'::regclass);


--
-- Name: registryerrorclass ak_registryerrorclass_code; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorclass
    ADD CONSTRAINT ak_registryerrorclass_code UNIQUE (registryerrorclass_code);


--
-- Name: registryerrorclass ak_registryerrorclass_name; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorclass
    ADD CONSTRAINT ak_registryerrorclass_name UNIQUE (registryerrorclass_name);


--
-- Name: militarycategory pk_militarycategory_id; Type: CONSTRAINT; Schema: r477; Owner: r477_role
--

ALTER TABLE ONLY r477.militarycategory
    ADD CONSTRAINT pk_militarycategory_id PRIMARY KEY (militarycategory_id);


--
-- Name: orgmilitarytype pk_orgmilitarytype_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytype
    ADD CONSTRAINT pk_orgmilitarytype_id PRIMARY KEY (orgmilitarytype_id);


--
-- Name: orgmilitarytypelink pk_orgmilitarytypelink_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytypelink
    ADD CONSTRAINT pk_orgmilitarytypelink_id PRIMARY KEY (orgmilitarytypelink_id);


--
-- Name: registry pk_registry_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT pk_registry_id PRIMARY KEY (registry_id);


--
-- Name: registrycmpnopolis pk_registrycmpnopolis_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrycmpnopolis
    ADD CONSTRAINT pk_registrycmpnopolis_id PRIMARY KEY (registry_id, evn_id);


--
-- Name: registrydata pk_registrydata_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydata
    ADD CONSTRAINT pk_registrydata_id PRIMARY KEY (evn_id, registry_id);


--
-- Name: registrydatacmp pk_registrydatacmp_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT pk_registrydatacmp_id PRIMARY KEY (cmpclosecard_id, registry_id, cmpclosecard_sid);


--
-- Name: registrydatasl pk_registrydatasl_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT pk_registrydatasl_id PRIMARY KEY (registrydatasl_id);


--
-- Name: registrydatatemp pk_registrydatatemp_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatatemp
    ADD CONSTRAINT pk_registrydatatemp_id PRIMARY KEY (registry_id, evn_id);


--
-- Name: registrydouble pk_registrydouble_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydouble
    ADD CONSTRAINT pk_registrydouble_id PRIMARY KEY (registry_id, evn_id);


--
-- Name: registryerror pk_registryerror_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerror
    ADD CONSTRAINT pk_registryerror_id PRIMARY KEY (registryerror_id);


--
-- Name: registryerrorclass pk_registryerrorclass_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorclass
    ADD CONSTRAINT pk_registryerrorclass_id PRIMARY KEY (registryerrorclass_id);


--
-- Name: registryerrorcmp pk_registryerrorcmp_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcmp
    ADD CONSTRAINT pk_registryerrorcmp_id PRIMARY KEY (registry_id, cmpclosecard_id, registryerrortype_id);


--
-- Name: registryerrorcom pk_registryerrorcom_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcom
    ADD CONSTRAINT pk_registryerrorcom_id PRIMARY KEY (registry_id, registryerrortype_id);


--
-- Name: registryerrortfoms pk_registryerrortfoms_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT pk_registryerrortfoms_id PRIMARY KEY (registryerrortfoms_id);


--
-- Name: registryerrortype pk_registryerrortype_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortype
    ADD CONSTRAINT pk_registryerrortype_id PRIMARY KEY (registryerrortype_id);


--
-- Name: registrygrouplink pk_registrygrouplink_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrygrouplink
    ADD CONSTRAINT pk_registrygrouplink_id PRIMARY KEY (registrygrouplink_id);


--
-- Name: registrylpusection pk_registrylpusection_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrylpusection
    ADD CONSTRAINT pk_registrylpusection_id PRIMARY KEY (registrylpusection_id);


--
-- Name: registrylpuunit pk_registrylpuunit_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrylpuunit
    ADD CONSTRAINT pk_registrylpuunit_id PRIMARY KEY (registrylpuunit_id);


--
-- Name: registrynopolis pk_registrynopolis_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrynopolis
    ADD CONSTRAINT pk_registrynopolis_id PRIMARY KEY (registry_id, evn_id);


--
-- Name: registryperson pk_registryperson_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryperson
    ADD CONSTRAINT pk_registryperson_id PRIMARY KEY (registry_id, maxevnperson_id);


--
-- Name: registryqueue pk_registryqueue_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT pk_registryqueue_id PRIMARY KEY (registryqueue_id);


--
-- Name: registryqueuehistory pk_registryqueuehistory_id; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT pk_registryqueuehistory_id PRIMARY KEY (registryqueuehistory_id);


--
-- Name: registryusluga pk_registryusluga; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT pk_registryusluga PRIMARY KEY (registry_id, evn_id, evnusluga_id);


--
-- Name: registryerrorreturned registryerrorreturned_pkey; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorreturned
    ADD CONSTRAINT registryerrorreturned_pkey PRIMARY KEY (registryerrorreturned_id);


--
-- Name: registryexportnumber registryexportnumber_pkey; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryexportnumber
    ADD CONSTRAINT registryexportnumber_pkey PRIMARY KEY (registryexportnumber_id);


--
-- Name: registryidentify registryidentify_pkey; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryidentify
    ADD CONSTRAINT registryidentify_pkey PRIMARY KEY (registryidentify_id);


--
-- Name: registrylpubuilding registrylpubuilding_pkey; Type: CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrylpubuilding
    ADD CONSTRAINT registrylpubuilding_pkey PRIMARY KEY (registrylpubuilding_id);


--
-- Name: idx_orgmilitarytype_deleted; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_orgmilitarytype_deleted ON r477.orgmilitarytype USING btree (orgmilitarytype_deleted) WITH (fillfactor='75');


--
-- Name: idx_orgmilitarytype_klcountry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_orgmilitarytype_klcountry_id ON r477.orgmilitarytype USING btree (klcountry_id) WITH (fillfactor='75') WHERE ((orgmilitarytype_deleted = 1) OR (orgmilitarytype_deleted IS NULL));


--
-- Name: idx_orgmilitarytypelink_org_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_orgmilitarytypelink_org_id ON r477.orgmilitarytypelink USING btree (org_id) WITH (fillfactor='75');


--
-- Name: idx_orgmilitarytypelink_orgmilitarytype_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_orgmilitarytypelink_orgmilitarytype_id ON r477.orgmilitarytypelink USING btree (orgmilitarytype_id) WITH (fillfactor='75');


--
-- Name: idx_registry_isactive; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registry_isactive ON r477.registry USING btree (registry_isactive);


--
-- Name: idx_registry_katnasel_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registry_katnasel_id ON r477.registry USING btree (katnasel_id);


--
-- Name: idx_registry_lpu_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registry_lpu_id ON r477.registry USING btree (lpu_id);


--
-- Name: idx_registry_registry_upddt; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registry_registry_upddt ON r477.registry USING btree (registry_upddt);


--
-- Name: idx_registry_registrystatus_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registry_registrystatus_id ON r477.registry USING btree (registrystatus_id);


--
-- Name: idx_registrycmpnopolis_registrynopolis_upddt; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrycmpnopolis_registrynopolis_upddt ON r477.registrycmpnopolis USING btree (registrynopolis_upddt);


--
-- Name: idx_registrydata_lpuunittype_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrydata_lpuunittype_id ON r477.registrydata USING btree (lpuunittype_id);


--
-- Name: idx_registrydata_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrydata_registry_id ON r477.registrydata USING btree (registry_id);


--
-- Name: idx_registrydata_registry_id_paid_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrydata_registry_id_paid_id ON r477.registrydata USING btree (registry_id, paid_id);


--
-- Name: idx_registrydata_registry_id_registrydata_rownum; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrydata_registry_id_registrydata_rownum ON r477.registrydata USING btree (registry_id, registrydata_rownum);


--
-- Name: idx_registrydatatemp_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrydatatemp_registry_id ON r477.registrydatatemp USING btree (registry_id);


--
-- Name: idx_registryerror_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerror_registry_id ON r477.registryerror USING btree (registry_id);


--
-- Name: idx_registryerror_registry_id_evn_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerror_registry_id_evn_id ON r477.registryerror USING btree (registry_id, evn_id);


--
-- Name: idx_registryerrorreturned_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrorreturned_registry_id ON r477.registryerrorreturned USING btree (registry_id);


--
-- Name: idx_registryerrortfoms_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registry_id ON r477.registryerrortfoms USING btree (registry_id);


--
-- Name: idx_registryerrortfoms_registry_id_evn_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registry_id_evn_id ON r477.registryerrortfoms USING btree (registry_id, evn_id);


--
-- Name: idx_registryerrortfoms_registry_id_idcase; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registry_id_idcase ON r477.registryerrortfoms USING btree (registry_id, registryerrortfoms_idcase);


--
-- Name: idx_registryerrortfoms_registry_id_registry_task; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registry_id_registry_task ON r477.registryerrortfoms USING btree (registry_id, registry_task);


--
-- Name: idx_registryerrortfoms_registry_id_registryerrortfomstype_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registry_id_registryerrortfomstype_id ON r477.registryerrortfoms USING btree (registry_id, registryerrortfomstype_id, registryerrortfoms_id, registry_task);


--
-- Name: idx_registryerrortfoms_registryerrortype_code; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryerrortfoms_registryerrortype_code ON r477.registryerrortfoms USING btree (registryerrortype_code);


--
-- Name: idx_registryexportnumber_registry_id_registryaction_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryexportnumber_registry_id_registryaction_id ON r477.registryexportnumber USING btree (registry_id, registryaction_id);


--
-- Name: idx_registrygrouplink_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrygrouplink_registry_id ON r477.registrygrouplink USING btree (registry_id);


--
-- Name: idx_registrygrouplink_registry_pid; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrygrouplink_registry_pid ON r477.registrygrouplink USING btree (registry_pid);


--
-- Name: idx_registryidentify_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registryidentify_registry_id ON r477.registryidentify USING btree (registry_id);


--
-- Name: idx_registrylpusection_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrylpusection_registry_id ON r477.registrylpusection USING btree (registry_id);


--
-- Name: idx_registrylpuunit_registry_id; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrylpuunit_registry_id ON r477.registrylpuunit USING btree (registry_id);


--
-- Name: idx_registrynopolis_registrynopolis_upddt; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX idx_registrynopolis_registrynopolis_upddt ON r477.registrynopolis USING btree (registrynopolis_upddt);


--
-- Name: registryerrortype_upper_idx; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX registryerrortype_upper_idx ON r477.registryerrortype USING btree (upper((registryerrortype_sysnick)::text));


--
-- Name: registrylpubuilding_registry_id_idx; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX registrylpubuilding_registry_id_idx ON r477.registrylpubuilding USING btree (registry_id);


--
-- Name: registrylpubuilding_registryqueue_id_idx; Type: INDEX; Schema: r477; Owner: developer_rep
--

CREATE INDEX registrylpubuilding_registryqueue_id_idx ON r477.registrylpubuilding USING btree (registryqueue_id);


--
-- Name: orgmilitarytype fk_orgmilitarytype_deleted; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytype
    ADD CONSTRAINT fk_orgmilitarytype_deleted FOREIGN KEY (orgmilitarytype_deleted) REFERENCES dbo.yesno(yesno_id);


--
-- Name: orgmilitarytype fk_orgmilitarytype_klcountry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytype
    ADD CONSTRAINT fk_orgmilitarytype_klcountry_id FOREIGN KEY (klcountry_id) REFERENCES dbo.klcountry(klcountry_id);


--
-- Name: orgmilitarytypelink fk_orgmilitarytypelink_org_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytypelink
    ADD CONSTRAINT fk_orgmilitarytypelink_org_id FOREIGN KEY (org_id) REFERENCES dbo.org(org_id);


--
-- Name: orgmilitarytypelink fk_orgmilitarytypelink_orgmilitarytype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.orgmilitarytypelink
    ADD CONSTRAINT fk_orgmilitarytypelink_orgmilitarytype_id FOREIGN KEY (orgmilitarytype_id) REFERENCES r477.orgmilitarytype(orgmilitarytype_id);


--
-- Name: registry fk_registry_drugfinance_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT fk_registry_drugfinance_id FOREIGN KEY (drugfinance_id) REFERENCES dbo.drugfinance(drugfinance_id);


--
-- Name: registry fk_registry_iszno; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT fk_registry_iszno FOREIGN KEY (registry_iszno) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registry fk_registry_org_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT fk_registry_org_id FOREIGN KEY (org_id) REFERENCES dbo.org(org_id);


--
-- Name: registry fk_registry_registry_rid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT fk_registry_registry_rid FOREIGN KEY (registry_rid) REFERENCES r477.registry(registry_id);


--
-- Name: registry fk_registry_whsdocumentcostitemtype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registry
    ADD CONSTRAINT fk_registry_whsdocumentcostitemtype_id FOREIGN KEY (whsdocumentcostitemtype_id) REFERENCES dbo.whsdocumentcostitemtype(whsdocumentcostitemtype_id);


--
-- Name: registrycmpnopolis fk_registrycmpnopolis_evn_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrycmpnopolis
    ADD CONSTRAINT fk_registrycmpnopolis_evn_id FOREIGN KEY (evn_id) REFERENCES dbo.cmpclosecard(cmpclosecard_id) ON DELETE CASCADE;


--
-- Name: registrycmpnopolis fk_registrycmpnopolis_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrycmpnopolis
    ADD CONSTRAINT fk_registrycmpnopolis_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registrydata fk_registrydata_ispersfin; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydata
    ADD CONSTRAINT fk_registrydata_ispersfin FOREIGN KEY (registrydata_ispersfin) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registrydata fk_registrydata_mesolduslugacomplex_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydata
    ADD CONSTRAINT fk_registrydata_mesolduslugacomplex_id FOREIGN KEY (mesolduslugacomplex_id) REFERENCES dbo.mesolduslugacomplex(mesolduslugacomplex_id);


--
-- Name: registrydata fk_registrydata_mestariff_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydata
    ADD CONSTRAINT fk_registrydata_mestariff_id FOREIGN KEY (mestariff_id) REFERENCES dbo.mestariff(mestariff_id);


--
-- Name: registrydata fk_registrydata_paymedtype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydata
    ADD CONSTRAINT fk_registrydata_paymedtype_id FOREIGN KEY (paymedtype_id) REFERENCES dbo.paymedtype(paymedtype_id);


--
-- Name: registrydatacmp fk_registrydatacmp_cmpclosecard_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT fk_registrydatacmp_cmpclosecard_id FOREIGN KEY (cmpclosecard_id) REFERENCES dbo.cmpclosecard(cmpclosecard_id);


--
-- Name: registrydatacmp fk_registrydatacmp_ispersfin; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT fk_registrydatacmp_ispersfin FOREIGN KEY (registrydatacmp_ispersfin) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registrydatacmp fk_registrydatacmp_medpersonal_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT fk_registrydatacmp_medpersonal_id FOREIGN KEY (medpersonal_id) REFERENCES persis.medworker(id);


--
-- Name: registrydatacmp fk_registrydatacmp_paymedtype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT fk_registrydatacmp_paymedtype_id FOREIGN KEY (paymedtype_id) REFERENCES dbo.paymedtype(paymedtype_id);


--
-- Name: registrydatacmp fk_registrydatacmp_uslugacomplex_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatacmp
    ADD CONSTRAINT fk_registrydatacmp_uslugacomplex_id FOREIGN KEY (uslugacomplex_id) REFERENCES dbo.uslugacomplex(uslugacomplex_id);


--
-- Name: registrydatasl fk_registrydatasl_leavetype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_leavetype_id FOREIGN KEY (leavetype_id) REFERENCES dbo.leavetype(leavetype_id);


--
-- Name: registrydatasl fk_registrydatasl_lpu_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_lpu_id FOREIGN KEY (lpu_id) REFERENCES dbo.lpu(lpu_id);


--
-- Name: registrydatasl fk_registrydatasl_lpuunittype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_lpuunittype_id FOREIGN KEY (lpuunittype_id) REFERENCES dbo.lpuunittype(lpuunittype_id);


--
-- Name: registrydatasl fk_registrydatasl_omssprterr_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_omssprterr_id FOREIGN KEY (omssprterr_id) REFERENCES dbo.omssprterr(omssprterr_id);


--
-- Name: registrydatasl fk_registrydatasl_orgsmo_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_orgsmo_id FOREIGN KEY (orgsmo_id) REFERENCES dbo.orgsmo(orgsmo_id);


--
-- Name: registrydatasl fk_registrydatasl_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id);


--
-- Name: registrydatasl fk_registrydatasl_resultdesease_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatasl
    ADD CONSTRAINT fk_registrydatasl_resultdesease_id FOREIGN KEY (resultdesease_id) REFERENCES dbo.resultdesease(resultdesease_id);


--
-- Name: registrydatatemp fk_registrydatatemp_ispersfin; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatatemp
    ADD CONSTRAINT fk_registrydatatemp_ispersfin FOREIGN KEY (registrydatatemp_ispersfin) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registrydatatemp fk_registrydatatemp_mesolduslugacomplex_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatatemp
    ADD CONSTRAINT fk_registrydatatemp_mesolduslugacomplex_id FOREIGN KEY (mesolduslugacomplex_id) REFERENCES dbo.mesolduslugacomplex(mesolduslugacomplex_id);


--
-- Name: registrydatatemp fk_registrydatatemp_uslugacomplex_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydatatemp
    ADD CONSTRAINT fk_registrydatatemp_uslugacomplex_id FOREIGN KEY (uslugacomplex_id) REFERENCES dbo.uslugacomplex(uslugacomplex_id);


--
-- Name: registrydouble fk_registrydouble_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrydouble
    ADD CONSTRAINT fk_registrydouble_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryerror fk_registryerror_lpusection_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerror
    ADD CONSTRAINT fk_registryerror_lpusection_id FOREIGN KEY (lpusection_id) REFERENCES dbo.lpusection(lpusection_id);


--
-- Name: registryerror fk_registryerror_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerror
    ADD CONSTRAINT fk_registryerror_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryerror fk_registryerror_registryerrortype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerror
    ADD CONSTRAINT fk_registryerror_registryerrortype_id FOREIGN KEY (registryerrortype_id) REFERENCES r477.registryerrortype(registryerrortype_id);


--
-- Name: registryerrorcmp fk_registryerrorcmp_cmpclosecard_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcmp
    ADD CONSTRAINT fk_registryerrorcmp_cmpclosecard_id FOREIGN KEY (cmpclosecard_id) REFERENCES dbo.cmpclosecard(cmpclosecard_id);


--
-- Name: registryerrorcmp fk_registryerrorcmp_lpusection_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcmp
    ADD CONSTRAINT fk_registryerrorcmp_lpusection_id FOREIGN KEY (lpusection_id) REFERENCES dbo.lpusection(lpusection_id);


--
-- Name: registryerrorcmp fk_registryerrorcmp_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcmp
    ADD CONSTRAINT fk_registryerrorcmp_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryerrorcmp fk_registryerrorcmp_registryerrortype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcmp
    ADD CONSTRAINT fk_registryerrorcmp_registryerrortype_id FOREIGN KEY (registryerrortype_id) REFERENCES r477.registryerrortype(registryerrortype_id);


--
-- Name: registryerrorcom fk_registryerrorcom_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcom
    ADD CONSTRAINT fk_registryerrorcom_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryerrorcom fk_registryerrorcom_registryerrortype; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrorcom
    ADD CONSTRAINT fk_registryerrorcom_registryerrortype FOREIGN KEY (registryerrortype_id) REFERENCES r477.registryerrortype(registryerrortype_id);


--
-- Name: registryerrortfoms fk_registryerrortfoms_cmpclosecard_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_cmpclosecard_id FOREIGN KEY (cmpclosecard_id) REFERENCES dbo.cmpclosecard(cmpclosecard_id);


--
-- Name: registryerrortfoms fk_registryerrortfoms_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryerrortfoms fk_registryerrortfoms_registryerrorclass_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_registryerrorclass_id FOREIGN KEY (registryerrorclass_id) REFERENCES r477.registryerrorclass(registryerrorclass_id);


--
-- Name: registryerrortfoms fk_registryerrortfoms_registryerrortfomslevel_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_registryerrortfomslevel_id FOREIGN KEY (registryerrortfomslevel_id) REFERENCES dbo.registryerrortfomslevel_in_r59(registryerrortfomslevel_id);


--
-- Name: registryerrortfoms fk_registryerrortfoms_registryerrortfomstype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_registryerrortfomstype_id FOREIGN KEY (registryerrortfomstype_id) REFERENCES dbo.registryerrortfomstype(registryerrortfomstype_id);


--
-- Name: registryerrortfoms fk_registryerrortfoms_registryerrortype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortfoms
    ADD CONSTRAINT fk_registryerrortfoms_registryerrortype_id FOREIGN KEY (registryerrortype_id) REFERENCES r477.registryerrortype(registryerrortype_id);


--
-- Name: registryerrortype fk_registryerrortype_iscrit; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortype
    ADD CONSTRAINT fk_registryerrortype_iscrit FOREIGN KEY (registryerrortype_iscrit) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryerrortype fk_registryerrortype_registryerrorclass; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortype
    ADD CONSTRAINT fk_registryerrortype_registryerrorclass FOREIGN KEY (registryerrorclass_id) REFERENCES dbo.registryerrorclass_in_r59(registryerrorclass_id);


--
-- Name: registryerrortype fk_registryerrortype_registrytype; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortype
    ADD CONSTRAINT fk_registryerrortype_registrytype FOREIGN KEY (registrytype_id) REFERENCES dbo.registrytype(registrytype_id);


--
-- Name: registryerrortype fk_registryerrortype_yesno; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryerrortype
    ADD CONSTRAINT fk_registryerrortype_yesno FOREIGN KEY (registryerrortype_isuser) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registrygrouplink fk_registrygrouplink_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrygrouplink
    ADD CONSTRAINT fk_registrygrouplink_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id);


--
-- Name: registrygrouplink fk_registrygrouplink_registry_pid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrygrouplink
    ADD CONSTRAINT fk_registrygrouplink_registry_pid FOREIGN KEY (registry_pid) REFERENCES r477.registry(registry_id) ON DELETE CASCADE;


--
-- Name: registrylpusection fk_registrylpusection_lpusection_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrylpusection
    ADD CONSTRAINT fk_registrylpusection_lpusection_id FOREIGN KEY (lpusection_id) REFERENCES dbo.lpusection(lpusection_id);


--
-- Name: registrylpuunit fk_registrylpuunit_lpuunit_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrylpuunit
    ADD CONSTRAINT fk_registrylpuunit_lpuunit_id FOREIGN KEY (lpuunit_id) REFERENCES dbo.lpuunit(lpuunit_id);


--
-- Name: registrynopolis fk_registrynopolis_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registrynopolis
    ADD CONSTRAINT fk_registrynopolis_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryperson fk_registryperson_isdifferent; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryperson
    ADD CONSTRAINT fk_registryperson_isdifferent FOREIGN KEY (registryperson_isdifferent) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryperson fk_registryperson_ismerge; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryperson
    ADD CONSTRAINT fk_registryperson_ismerge FOREIGN KEY (registryperson_ismerge) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryqueue fk_registryqueue_dispclass_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_dispclass_id FOREIGN KEY (dispclass_id) REFERENCES dbo.dispclass(dispclass_id);


--
-- Name: registryqueue fk_registryqueue_iszno; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_iszno FOREIGN KEY (registry_iszno) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryqueue fk_registryqueue_katnasel_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_katnasel_id FOREIGN KEY (katnasel_id) REFERENCES dbo.katnasel(katnasel_id);


--
-- Name: registryqueue fk_registryqueue_lpu_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_lpu_id FOREIGN KEY (lpu_id) REFERENCES dbo.lpu(lpu_id);


--
-- Name: registryqueue fk_registryqueue_org_mid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_org_mid FOREIGN KEY (org_mid) REFERENCES dbo.org(org_id);


--
-- Name: registryqueue fk_registryqueue_orgrschet_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_orgrschet_id FOREIGN KEY (orgrschet_id) REFERENCES dbo.orgrschet(orgrschet_id);


--
-- Name: registryqueue fk_registryqueue_orgrschet_mid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_orgrschet_mid FOREIGN KEY (orgrschet_mid) REFERENCES dbo.orgrschet(orgrschet_id);


--
-- Name: registryqueue fk_registryqueue_paytype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_paytype_id FOREIGN KEY (paytype_id) REFERENCES dbo.paytype(paytype_id);


--
-- Name: registryqueue fk_registryqueue_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id);


--
-- Name: registryqueue fk_registryqueue_registry_isrepeated; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_registry_isrepeated FOREIGN KEY (registry_isrepeated) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryqueue fk_registryqueue_registry_rid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_registry_rid FOREIGN KEY (registry_rid) REFERENCES r477.registry(registry_id);


--
-- Name: registryqueue fk_registryqueue_registrystatus_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueue
    ADD CONSTRAINT fk_registryqueue_registrystatus_id FOREIGN KEY (registrystatus_id) REFERENCES dbo.registrystatus(registrystatus_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_katnasel_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_katnasel_id FOREIGN KEY (katnasel_id) REFERENCES dbo.katnasel(katnasel_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_orgrschet_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_orgrschet_id FOREIGN KEY (orgrschet_id) REFERENCES dbo.orgrschet(orgrschet_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_paytype_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_paytype_id FOREIGN KEY (paytype_id) REFERENCES dbo.paytype(paytype_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_registry_isrepeated; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_registry_isrepeated FOREIGN KEY (registry_isrepeated) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_registry_rid; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_registry_rid FOREIGN KEY (registry_rid) REFERENCES r477.registry(registry_id);


--
-- Name: registryqueuehistory fk_registryqueuehistory_registryqueuehistory_isupdate; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryqueuehistory
    ADD CONSTRAINT fk_registryqueuehistory_registryqueuehistory_isupdate FOREIGN KEY (registryqueuehistory_isupdate) REFERENCES dbo.yesno(yesno_id);


--
-- Name: registryusluga fk_registryusluga_diag_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_diag_id FOREIGN KEY (diag_id) REFERENCES dbo.diag(diag_id);


--
-- Name: registryusluga fk_registryusluga_lpusection_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_lpusection_id FOREIGN KEY (lpusection_id) REFERENCES dbo.lpusection(lpusection_id);


--
-- Name: registryusluga fk_registryusluga_lpusectionprofile_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_lpusectionprofile_id FOREIGN KEY (lpusectionprofile_id) REFERENCES dbo.lpusectionprofile(lpusectionprofile_id);


--
-- Name: registryusluga fk_registryusluga_medstafffact_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_medstafffact_id FOREIGN KEY (medstafffact_id) REFERENCES persis.workplace(id);


--
-- Name: registryusluga fk_registryusluga_registry_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_registry_id FOREIGN KEY (registry_id) REFERENCES r477.registry(registry_id) ON UPDATE CASCADE ON DELETE CASCADE;


--
-- Name: registryusluga fk_registryusluga_uslugacomplex_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_uslugacomplex_id FOREIGN KEY (uslugacomplex_id) REFERENCES dbo.uslugacomplex(uslugacomplex_id);


--
-- Name: registryusluga fk_registryusluga_uslugacomplextariff_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_uslugacomplextariff_id FOREIGN KEY (uslugacomplextariff_id) REFERENCES dbo.uslugacomplextariff(uslugacomplextariff_id);


--
-- Name: registryusluga fk_registryusluga_uslugasectiontariff_id; Type: FK CONSTRAINT; Schema: r477; Owner: developer_rep
--

ALTER TABLE ONLY r477.registryusluga
    ADD CONSTRAINT fk_registryusluga_uslugasectiontariff_id FOREIGN KEY (uslugasectiontariff_id) REFERENCES dbo.uslugasectiontariff(uslugasectiontariff_id);


--
--

