-- =============================================
-- Author:  Timur R. Khakimov  2015
-- Create date: 2015-07-05
-- Description: Заполнение заявки о расчете стоимости посещения
-- =============================================
DROP PROCEDURE IF EXISTS sp_AddGetBillRequest;
CREATE PROCEDURE sp_AddGetBillRequest("ID" UUID, "IsNew" bit, "LpuID" UUID, "PatientID" UUID, "RequestType" varchar(255))
As 
$$
DECLARE		
		_RequestTypeGroupID UUID;
		_RequestText Text;
Begin
	IF "IsNew" = '1'
	then
		SELECT rtg.RequestTypeGroupID 
		from akuz.T_REQUEST_TYPE_GROUP rtg
		into _RequestTypeGroupID
		where rtg.Code = "RequestType"
		Limit 1;
		IF _RequestTypeGroupID IS NOT NULL
		then	
			_RequestText := '<?xml version="1.0" encoding="utf-8"?><data name="get_bill_request"><attr name="ID">' || "ID"::varchar(255) || '</attr></data>';
			INSERT INTO akuz.T_REQUEST_RECIEVED(RequestRecievedID, CreationDT, RequestText, LpuMain, RequestTypeGroup, BaseEntityID, PatientID)
			VALUES(uuid_generate_v4(), Current_TimeStamp::TIMESTAMP, _RequestText, "LpuID", _RequestTypeGroupID, "ID", "PatientID");
		END if;
	 ELSE 
		DELETE FROM akuz.T_REQUEST_RECIEVED where BaseEntityID = "ID" and Status IS NULL;
	end if;
End;
$$ Language plpgsql;