
drop procedure if exists sp_GetSetLpuOverRequest;
-- ==================================================
-- Author:      Vitacore (с)
-- Create date: 2016-02-29
-- Description: Синхронизация превышения заявки по МО
-- ==================================================
CREATE PROCEDURE sp_GetSetLpuOverRequest
(
	"Xml" text DEFAULT NULL
	,"IsNew" integer = 1
	,"ID" uuid DEFAULT NULL::uuid
	,"QueueName" character varying DEFAULT null::character varying
	,"dateTime" timestamp without time zone DEFAULT NULL::timestamp without time zone
	,"User" uuid DEFAULT NULL::uuid
)
language plpgsql
as
$$
Begin
	declare 
			_Result text;
			_ContentEncoding varchar(255);
			_Type varchar(255);
			_OperationType varchar(255); 
			_OwnerID uuid; 

	Begin 
		"dateTime" := Coalesce("dateTime", Current_TimeStamp::TIMESTAMP);
		_OperationType := 'FTLoad';

		if ("Xml" is null)
		then
			select
			xmlelement
			(
				name "LPU_OVER_REQUEST",
				xmlelement
				(
					name header,
					xmlforest
					(
						_OperationType as "TYPE"
					)
				),
				xmlelement
				(
					name body,
					xmlelement
					(
						name "LPU_OVER_REQUESTS",
						xmlforest
						(
							lor.LpuOverRequestID as "ID",
							lor.DrugApplicationListItem as "DrugApplicationListItemID",
							lpu.MCOD as "LpuMainID"
						)
					)
				)
			)
			into _Result
			from RDS.T_LPU_OVER_REQUEST lor
				left join RDS.T_LPU_MAIN lpu ON lpu.MCOD = lor.LpuMain;

			INSERT INTO RDS.T_RABBIT_SEND_OBJECT
			(
				RabbitSendObjectID,
				QueueName,
				Content,
				MessageID,
				Headers,
				ContentEncoding,
				Type,
				UserID,
				State,
				CreateDateTime,
				OwnerID
			)
			SELECT uuid_generate_v4(), --(<RabbitSendObjectID, uniqueidentifier,>
				   s.ServerName, --,<QueueName, varchar(255),>
				   ConvertTextToBinaryZip(_Result, ''), --,<Content, text,>
				   NULL, --,<MessageID, varchar(255),>
				   NULL, --,<Headers, varchar(255),>
				   _ContentEncoding, --,<ContentEncoding, varchar(255),>
				   _Type, --,<Type, varchar(255),>
				   "User", --,<UserID, varchar(255),>
				   0, --,<State, int,>)
				   "dateTime", --,<CreateDateTime, datetime,>)
				   _OwnerID				--,<OwnerID, varchar(255),>
			FROM   RDS.T_SYNC_SERVERS AS s
			WHERE  
				("QueueName" IS NOT NULL AND s.ServerName = "QueueName")
				OR ("QueueName" IS NULL AND s.ServerType IN(0, 1)); -- Рассылаем пакет всем подписанным серверам AKUZ-а и APS, если не указана очередь
		end if;
	End;
End;
$$;