DROP PROCEDURE IF EXISTS sp_n001protload;
DROP FUNCTION IF EXISTS sp_n001protload;

CREATE PROCEDURE public.sp_n001protload("Xml" bytea, "FileName" character varying)
LANGUAGE 'plpgsql'
AS $BODY$
	
declare T xml;
declare tempStrXml text;
BEGIN
	select convert_from("Xml", 'WIN1251') into tempStrXml;
	
	select replace(tempStrXml, 'encoding="windows-1251"','')::xml into T; 
	
	DROP TABLE IF EXISTS temp_n001;

	CREATE TEMP TABLE temp_n001 as
	SELECT 
		ID_PrOt::int, 
		PrOt_NAME, 
		CASE WHEN  DATEBEG  = '' THEN NULL ELSE DATEBEG::TIMESTAMP END , 
		CASE WHEN  DATEEND  = '' THEN NULL ELSE DATEEND::TIMESTAMP END 
	FROM
	XMLTABLE ('/packet/zap' PASSING T 
	COLUMNS 
		ID_PrOt text path './ID_PrOt' null, 
		PrOt_NAME text path './PrOt_NAME' null, 
		DATEBEG text path './DATEBEG' null, 
		DATEEND text path './DATEEND' null );
	
	update IES.T_N001_PrOt t2 
	set  PrOt_NAME=t1.PrOt_NAME
		,DATEEND=t1.DATEEND
	from temp_n001 t1
	where (t1.ID_PrOt=t2.ID_PrOt and t1.DATEBEG = t2.DATEBEG);

	insert into IES.T_N001_PrOt(N001PrOtID,ID_PrOt,PrOt_NAME,DATEBEG,DATEEND)
	select gen_random_uuid(),t1.ID_PrOt,t1.PrOt_NAME,t1.DATEBEG,t1.DATEEND
	from temp_n001 t1
	left join IES.T_N001_PrOt t2 on (t1.ID_PrOt=t2.ID_PrOt and t1.DATEBEG = t2.DATEBEG)
	where t2.N001PrOtID is null;
		
	drop table if exists temp_n001;
	
	return;
END
$BODY$;
