Загрузка данных


-- DROP FUNCTION smev.f3_send_register_to_sfr();

CREATE OR REPLACE FUNCTION smev.f3_send_register_to_sfr()
 RETURNS integer
 LANGUAGE plpgsql
AS $function$
	declare
		smev_register_file record; 
		sid text; 
		smev_processes record;
		query_text text;
		process_j json;
		process_result_stack json[];
		metadata text[];
		v_response_content bytea;
		v_cookies text;
		v_base varchar(255);
		v_file_j json;
		v_oper_code varchar(50);
	
		max_cycle int;
		current_cycle int;
		v_condition bool;
		v_cycle_model_id int;
	
		-- Идентификаторы отправленных реестров
		cycle_model json;
		cycle_model_list json;
		cycle_model_list_elem text[];
		arr_length integer;
		item text;
		result_str text := '';
		fullPath text;
	
		v_robot text;
	
		-- Пользовательская функция (тест)
		parts text[];
		v_next_run timestamptz;
		
		-- Технические переменные для формировании ошибок при сбое в системе (не в процессе формирования реестра)
		err_code text; -- код ошибки
		msg_text text; -- текст ошибки
    	exc_context text; -- контекст исключения
 		msg_detail text; -- подробный текст ошибки
 		exc_hint text; -- текст подсказки к исключению
 		
	begin
		begin -- exception
			sid := uuid_generate_v4()::text;
			select web_base into v_base from tools.settings limit 1; 
			v_robot:= 'bb_robot';
			-- ******
			-- LOGIN:
			perform curl.curl_easy_setopt_timeout_ms(1000000);
			-- LOOP
			for smev_register_file in 
				select 
					id, name, description, waiting_time, deadline_for_report_generation, countdown_date, day_type,
					started_at, do_function -- добавлено для теста aa.pinaev
				from report.conf_scheduler_sfr 
				where 
					is_active = true 
				
			loop
				
				perform robot.log_message('Запуск', 'Отправляем реестр в СФР id = ' || smev_register_file.id::text , sid);
				RAISE NOTICE 'Next id from conf_scheduler_sfr %', smev_register_file.id;
			
				-- добавление пользовательской функции в расписание (тест)
				begin
					if smev_register_file.do_function is not null and smev_register_file.do_function <> '' then 
						-- схема и имя функции пользователя
						parts := array[]::text[];
						parts := parse_ident(smev_register_file.do_function);
						raise notice 'parse_ident: % %', parts[1], parts[2];
						
						-- когда запускать
						v_next_run := (current_date + smev_register_file.started_at)::timestamptz; -- v_target_time
						if v_next_run <= now() then 
							v_next_run := v_next_run + interval '1 day';
						end if;
						raise notice 'v_next_run: %', v_next_run;
					
						perform schedule.submit_job(format('select %I.%I()', parts[1], parts[2]), run_after := v_next_run::timestamp); -- run_after := '2026-06-08 15:59:00'				
						perform robot.log_message('Работа', 'Задание ' || smev_register_file.do_function || ' успешно добавлено в расписание, будет выполнено ' || to_char(v_next_run, 'DD.MM.YYYY HH24:MI'), sid);								
					else 
						perform robot.log_message('Работа', 'Поле do_function не заполнено, пропуск добавления разового задания', sid);
					end if;
				exception when others then 
					perform robot.log_message('Работа', 'Ошибка при добавлении разового задания', sid);
					raise warning 'Ошибка при добавлении разового задания, %', sqlerrm;
				end;
				--
				--commit;
				perform pg_sleep(0.03);
			
				metadata:= null;
				v_cookies:= null;
				process_result_stack:= null;
				v_condition := true;
				max_cycle:=0;
				current_cycle:=0;
				v_cycle_model_id:= 0;
				
				v_cookies := robot.login_ex2(v_base, v_robot);
				
				if coalesce(v_cookies, '') = '' then
					RAISE EXCEPTION 'Err get cookies postprocess';
				end if;
				
				RAISE NOTICE '-Post process login ok %', sid;
				
				-- **********************************************************************
				while (v_condition) loop
				
					-- smev_processes
					for smev_processes in
						select id_etl, id_process, process_type, load_id_var, load_post_process, process_description, operation_type
						from smev.smev_report_create_register_processes  
						where 
							id_etl = smev_register_file.id 
							and operation_type = 1 
							and active_task is true 
							and case when current_cycle <> 0 then id_process > v_cycle_model_id else true end 
							-- and case when current_cycle <> max_cycle then id_process < id_S6

					loop 
					
						RAISE notice 'smev_processes.id_process %,  %,  %,  %, % ', 
							smev_processes.id_etl, 
							smev_processes.id_process, 
							smev_processes.process_type, 
							smev_processes.load_post_process, 
							smev_processes.process_description;			
									
						v_oper_code:= smev_processes.load_post_process;
						process_j:= Null;
						v_file_j:= Null;
						
						-- check load_id_var 
						if (smev_processes.load_id_var is not null) then 
							metadata:= smev.f_smev_data_json_build2(smev_processes.load_id_var, process_result_stack, current_cycle, sid);
						end if;
						
						-- 1,3-модели , 2-операции, 4-модель цикла

						if smev_processes.process_type in (1, 3, 4) then 
							-- **********************	
							-- process is queryModel:
							query_text:= 'queryModel?queryModelCode=' || utils.urlencode(v_oper_code);
							if (cardinality(metadata) <> 0 and cardinality(metadata) is not null) then
								process_j:= json_object(metadata);
							else
								-- empty data object {}
								process_j:= json_build_object();
							end if;
						
						elsif smev_processes.process_type = 2 then
							-- ***********************
							-- process is queryAction:
							query_text:= 'queryAction/action';
							metadata:= array_prepend(v_oper_code, metadata);
							metadata:= array_prepend('queryActionCode', metadata); 
							process_j:= json_object(metadata);
						end if;
				
						v_response_content:= robot.get_page_data(v_base, query_text, v_cookies, process_j);	
						v_file_j:= convert_from(v_response_content, 'UTF8')::json;					
						
						if (smev_processes.process_type = 4) then 
								v_cycle_model_id:= smev_processes.id_process; 
								select jsonb_array_length((v_file_j::jsonb)->'list') into max_cycle;
								cycle_model := v_file_j::json;
								if (max_cycle > 0) then 
									-- cycle initialization(!):
									current_cycle:= 1; 
								end if; 
							end if; 
							
							if (smev_processes.process_type = 5) then 
								if(current_cycle < max_cycle) then 
									exit;  -- Мы выходим из внутреннего цикла 
								else 
									max_cycle:=0; 
									current_cycle:=0; 
								end if; 
							end if;
						
						process_result_stack[smev_processes.id_process::int] := v_file_j;
						perform array_append(process_result_stack, v_file_j);

						-- Проверки перед отправкой
						-- 1 (ВСПН-П)
						if smev_register_file.name = 'ВСПН-П' then 
						
							if smev_processes.id_process = 7 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ВСПН-П';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ВСПН-П, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						
							if smev_processes.id_process = 8 then
								-- Записываем все айди отправленных реестров 
								if (v_file_j->>'result' = 'true') then
									
									cycle_model_list := cycle_model->'list';
									select array_agg(elem->>'register_id') 
									into cycle_model_list_elem 
									from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								
									arr_length := array_length(cycle_model_list_elem::int[], 1);
								end if;
							end if;	
						
						end if;
						-- END 1 (ВСПН-П)
					
						-- 2 (ЗННЧ-НП)
						if smev_register_file.name = 'ЗННЧ-НП' then 
						
							if smev_processes.id_process = 8 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗННЧ-НП';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗННЧ-НП, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						
							if smev_processes.id_process = 9 then
								-- Записываем все айди отправленных реестров 
								if (v_file_j->>'result' = 'true') then
									
									cycle_model_list := cycle_model->'list';
									select array_agg(elem->>'register_id') 
									into cycle_model_list_elem 
									from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								
									arr_length := array_length(cycle_model_list_elem::int[], 1);
								end if;
							end if;	
						
						end if;
						-- END 2 (ЗННЧ-НП)
					
						-- 4 (ЗСПННПФ-ЗЛ)
						if smev_register_file.name = 'ЗСПННПФ-ЗЛ' then 
							if smev_processes.id_process = 6 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗСПННПФ-ЗЛ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗСПННПФ-ЗЛ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
					
						-- 8 (РНПФ)
						if smev_register_file.name = 'РНПФ' then 
							if smev_processes.id_process = 7 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра РНПФ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра РНПФ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						--
						if smev_processes.id_process = 8 then
							-- Записываем все айди отправленных реестров 
							if (v_file_j->>'result' = 'true') then
								cycle_model_list := cycle_model->'list';
								select array_agg(elem->>'register_id') 
								into cycle_model_list_elem 
								from jsonb_array_elements(cycle_model_list::jsonb) as elem;	
								arr_length := array_length(cycle_model_list_elem::int[], 1);
							end if;
						end if;
					
						-- 9 (РНПФ-М)
						if smev_register_file.name = 'РНПФ-М' then 
							if smev_processes.id_process = 7 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра РНПФ-М';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра РНПФ-М, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						--
						if smev_processes.id_process = 8 then
							-- Записываем все айди отправленных реестров 
							if (v_file_j->>'result' = 'true') then
								cycle_model_list := cycle_model->'list';
								select array_agg(elem->>'register_id') 
								into cycle_model_list_elem 
								from jsonb_array_elements(cycle_model_list::jsonb) as elem;	
								arr_length := array_length(cycle_model_list_elem::int[], 1);
							end if;
						end if;
						
						-- 12 (РНПФ-У)
						if smev_register_file.name = 'РНПФ-У' then 
							if smev_processes.id_process = 7 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра РНПФ-У';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра РНПФ-У, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						--
						if smev_processes.id_process = 8 then
							-- Записываем все айди отправленных реестров 
							if (v_file_j->>'result' = 'true') then
								cycle_model_list := cycle_model->'list';
								select array_agg(elem->>'register_id') 
								into cycle_model_list_elem 
								from jsonb_array_elements(cycle_model_list::jsonb) as elem;	
								arr_length := array_length(cycle_model_list_elem::int[], 1);
							end if;
						end if;
						
						-- 14 (РСПННПФ)
						if smev_register_file.name = 'РСПННПФ' then 
							if smev_processes.id_process = 6 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра РСПННПФ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра РСПННПФ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
					
						-- 15 (СФВ-ЕВ)
						if smev_register_file.name = 'СФВ-ЕВ' then 
							if smev_processes.id_process = 6 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра СФВ-ЕВ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра СФВ-ЕВ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						--
						if smev_processes.id_process = 7 then
							-- Записываем все айди отправленных реестров 
							if (v_file_j->>'result' = 'true') then
								cycle_model_list := cycle_model->'list';
								select array_agg(elem->>'register_id') 
								into cycle_model_list_elem 
								from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								arr_length := array_length(cycle_model_list_elem::int[], 1);
							end if;
						end if;
						
						-- 20 (УЗЕВ-ДДС-НПФ)
						if smev_register_file.name = 'УЗЕВ-ДДС-НПФ' then 
							if smev_processes.id_process = 5 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра УЗЕВ-ДДС-НПФ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра УЗЕВ-ДДС-НПФ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						
						-- 21 (УЗЕВО-ДДС-НПФ)
						if smev_register_file.name = 'УЗЕВО-ДДС-НПФ' then 
							if smev_processes.id_process = 5 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра УЗЕВО-ДДС-НПФ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра УЗЕВО-ДДС-НПФ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
					
						-- 22 (УОПЕВДДС-НПФ)
						if smev_register_file.name = 'УОПЕВДДС-НПФ' then 
							if smev_processes.id_process = 6 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра УОПЕВДДС-НПФ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра УОПЕВДДС-НПФ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						
						-- 24 (ЗСПННПФ-ПП)
						if smev_register_file.name = 'ЗСПННПФ-ПП' then 
							if smev_processes.id_process = 6 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗСПННПФ-ПП';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗСПННПФ-ПП, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						
						-- 25 (СФВ-НП)
						if smev_register_file.name = 'СФВ-НП' then 
							if smev_processes.id_process = 6 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра СФВ-НП';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра СФВ-НП, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						end if;
						--
						if smev_processes.id_process = 7 then
							-- Записываем все айди отправленных реестров 
							if (v_file_j->>'result' = 'true') then
								cycle_model_list := cycle_model->'list';
								select array_agg(elem->>'register_id') 
								into cycle_model_list_elem 
								from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								arr_length := array_length(cycle_model_list_elem::int[], 1);
							end if;
						end if;
						
						-- 36 (ЗННЧ-СПВ)
						if smev_register_file.name = 'ЗННЧ-СПВ' then 
							if smev_processes.id_process = 8 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗННЧ-СПВ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗННЧ-СПВ, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						
							if smev_processes.id_process = 9 then
								-- Записываем все айди отправленных реестров 
								if (v_file_j->>'result' = 'true') then
									
									cycle_model_list := cycle_model->'list';
									select array_agg(elem->>'register_id') 
									into cycle_model_list_elem 
									from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								
									arr_length := array_length(cycle_model_list_elem::int[], 1);
								end if;
							end if;	
						
						end if;
						-- END 36 (ЗННЧ-СПВ)
						
						-- 37 (УЗЕВ-ДДС-НПФ-ЕПГУ)
						if smev_register_file.name = 'УЗЕВ-ДДС-НПФ-ЕПГУ' then 
							if smev_processes.id_process = 5 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра УЗЕВ-ДДС-НПФ-ЕПГУ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра УЗЕВ-ДДС-НПФ-ЕПГУ, id = ' || smev_register_file.id::text , sid);
									exit; 
								end if; 
							end if; 
						end if;	
					
						-- 40 (ФНС-ВЧТ)
						if smev_register_file.name = 'ФНС-ВЧТ' then 
							if smev_processes.id_process = 8 then 
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ФНС-ВЧТ';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ФНС-ВЧТ, id = ' || smev_register_file.id::text , sid);
									exit; 
								end if; 
							end if; 
						end if;
					
						-- 41 (ЗННЧ-НП повторные) 
						if smev_register_file.name = 'ЗННЧ-НП повторные' then 
							if smev_processes.id_process = 8 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗННЧ-НП повторные';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗННЧ-НП повторные, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						
							if smev_processes.id_process = 8 then
								-- Записываем все айди отправленных реестров 
								if (v_file_j->>'result' = 'true') then
									
									cycle_model_list := cycle_model->'list';
									select array_agg(elem->>'register_id') 
									into cycle_model_list_elem 
									from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								
									arr_length := array_length(cycle_model_list_elem::int[], 1);
								end if;
							end if;	
						
						end if;
						-- END 41 (ЗННЧ-НП повторные)
					
						-- 42 (ЗННЧ-СПВ повторные)
						if smev_register_file.name = 'ЗННЧ-СПВ повторные' then 
							if smev_processes.id_process = 8 then
								if (json_serialize(v_file_j) = '{}') then 
									raise notice 'Нет данных для отправки в СФР реестра ЗННЧ-СПВ повторные';
									perform robot.log_message('Работа', 'Нет данных для отправки в СФР реестра ЗННЧ-СПВ повторные, id = ' || smev_register_file.id::text , sid);
									exit;
								end if;
							end if;
						
							if smev_processes.id_process = 8 then
								-- Записываем все айди отправленных реестров 
								if (v_file_j->>'result' = 'true') then
									
									cycle_model_list := cycle_model->'list';
									select array_agg(elem->>'register_id') 
									into cycle_model_list_elem 
									from jsonb_array_elements(cycle_model_list::jsonb) as elem;
								
									arr_length := array_length(cycle_model_list_elem::int[], 1);
								end if;
							end if;	
						
						end if;
						-- END 42 (ЗННЧ-СПВ повторные)
					
						-- END Проверки перед отправкой
					
						--***
						-- Обновить дату выполнения отправки реестров
						update report.conf_scheduler_sfr 
						set last_processed = now()
						where is_active = true;
						
					end loop; 
					-- END smev_processes
					
					if(current_cycle >= max_cycle) then 
						v_condition:= false; 
					else 
						current_cycle:= current_cycle + 1; 
						v_condition:= true; 
					end if;
					
				end loop;  -- while loop
				--************************************	
				
				--************************************************************
					-- Результа отправки реестра - РАБОТА (логирование в таблицу robot.log)
						if (json_serialize(v_file_j) = '{}') then
								perform robot.log_message('Работа', 'Ошибка при отправке в СФР реестра id = ' || smev_register_file.id::text , sid);
								 
								perform mail.api_new_message_group (
									'Реестры СМЭВ'::text, 
									'Ошибка при отправке реестра ' || smev_register_file.name::text || ' в СФР'::text, 
									(select id from mail.list_group_recipients where code = 'code 12'),
									NULL::text,
									(now() + '1 minute'::interval)::text,
									1,
									'text'
								);
						else 
							if (v_file_j->>'result' = 'true') then 
								perform robot.log_message('Работа', 'Успех при отправке в СФР реестра id = ' || smev_register_file.id::text , sid);
								
								-- Пройти по массиву и создать строку
								if (arr_length is not null) then 
									
									-- очистка переменных
									fullPath := '';
									result_str := '';
								
									foreach item in array cycle_model_list_elem 
									loop
										if (smev_register_file.name = 'ВСПН-П') then 
											fullPath := v_base || 'view?viewCode=HI9P4ZAR' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'ЗННЧ-НП') then 
											fullPath := v_base || 'view?viewCode=TgEftDoN' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'ЗННЧ-СПВ') then 
											fullPath := v_base || 'view?viewCode=TgEftDoN' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'ЗННЧ-НП повторные') then 
											fullPath := v_base || 'view?viewCode=TgEftDoN' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'ЗННЧ-СПВ повторные') then 
											fullPath := v_base || 'view?viewCode=TgEftDoN' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'РНПФ') then 
											fullPath := v_base || 'view?viewCode=ZuCKldI1' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'РНПФ-М') then 
											fullPath := v_base || 'view?viewCode=JKwvm0Po' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'РНПФ-У') then 
											fullPath := v_base || 'view?viewCode=GlvwavQA' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'СФВ-ЕВ') then 
											fullPath := v_base || 'view?viewCode=5mp5OxLP' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'СФВ-НП') then 
											fullPath := v_base || 'view?viewCode=5mp5OxLP' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
									
										if (smev_register_file.name = 'УОПЕВДДС-НПФ') then 
											fullPath := v_base || 'view?viewCode=ytHMKTYM' || '&id=' || item;
											result_str := result_str || fullPath || ' ' || CHR(10);
										end if;
										
									end loop;
								end if;
							
								-- Отправка уведомления на почту
								perform mail.api_new_message_group (
									'Реестры СМЭВ'::text,
									'Реестр СМЭВ ' || smev_register_file.name::text || ' отправлен в СФР.' || CHR(10) || 
									'Ссылки на реестры: ' || CHR(10) || result_str::text, 
									(select id from mail.list_group_recipients where code = 'code 12'), 
									NULL, 
									(now() + '1 minute'::interval)::text
								);
							end if;
						end if;
				--************************************************************
					--logout
					if not robot.logout_ex(v_base, v_cookies) then
						RAISE EXCEPTION 'Post process Logout error';
					else
						RAISE NOTICE '-Post process logout ok %', sid;
					end if;	

					perform pg_sleep(1);
				
					-- Результа формирования реестра - ФИНИШ (логирование в таблицу robot.log) 
					perform robot.log_message('Финиш', 'Отправка реестра в СФР завершена id = ' || smev_register_file.id::text , sid);			
						
			end loop;
		
			-- EXCEPTIONS:
			exception when others
			THEN
				GET STACKED DIAGNOSTICS
		    	err_code = RETURNED_SQLSTATE, -- код ошибки
				msg_text = MESSAGE_TEXT, -- текст ошибки
		    	exc_context = PG_CONTEXT, -- контекст исключения
		 		msg_detail = PG_EXCEPTION_DETAIL, -- подробный текст ошибки
		 		exc_hint = PG_EXCEPTION_HINT; -- текст подсказки к исключению
			
			    RAISE NOTICE 'ERROR CODE: % MESSAGE TEXT: % CONTEXT: % DETAIL: % HINT: %', 
			   	err_code, msg_text, exc_context, msg_detail, exc_hint;
			   
			    -- Результа формирования реестра - ФИНИШ (логирование в таблицу robot.log)
			   	perform robot.log_message('Финиш', err_code || ' ; ' || msg_text || ' ; ' || msg_detail , sid);
			    
			end;
		
	return 0;

	END;
$function$
;