-- =============================================
-- Author:  Timur R. Khakimov  2015
-- Create date: 2015-02-15
-- Description: Заполнение таблицы информацией о посещении врача
-- =============================================
DROP PROCEDURE IF EXISTS sp_adddoctorvisitnotifyshort;
CREATE PROCEDURE sp_adddoctorvisitnotifyshort
(
	"VisitID" uuid
,	"IsNew" boolean
)
AS
$BODY$
DECLARE	DoctorVisitNotifyServiceStatus boolean;
Begin
	IF "IsNew" = '1'
	then
		SELECT vs.Status 
		from akuz.T_VCSN_SERVICES vs
		into DoctorVisitNotifyServiceStatus
		where vs.VCSNServiceName = 'DoctorVisitNotify'
		limit 1;
		IF DoctorVisitNotifyServiceStatus = '1'
		then
			INSERT INTO akuz.T_DOCTOR_VISIT_NOTIFY(DoctorVisitNotifyID, PatientID, SpecName, DoctorFIO, LpuCode, BranchCode, CreationDT, PostID, VisitDate, VisitID)
			select uuid_generate_v4(), AmbulanceCard.Patient, Speciality.Name, Worker.FIO, LpuMain.Code, Branch.BranchCode, Current_TimeStamp::TIMESTAMP
				, PResource.ResourceIdGuid, Visit.VisitDate, "VisitID"
			FROM akuz.T_VISIT Visit
 			inner JOIN 
				akuz.T_EVENT_BASE EventBase 
				on EventBase.EventID = Visit.AmbulanceEvent
 			inner JOIN 
				akuz.T_AMBULANCE_CARD AmbulanceCard 
				on AmbulanceCard.AmbulanceCardID = EventBase.AmbulanceCard
 			inner JOIN 
				akuz.T_RESOURCE PResource 
				on PResource.ResourceID = Visit.Post
 			inner JOIN 
				akuz.T_SPECIALITY Speciality 
				on Speciality.SpecialityID = PResource.Speciality
 			inner JOIN 
				akuz.T_POST Post 
				on Post.ResourceID = Visit.Post
 			inner JOIN 
				akuz.T_WORKER Worker 
				on Worker.WorkerID = Post.Worker
 			inner JOIN 
				akuz.T_DIVISION Division 
				on Division.DivisionID = PResource.Division
 			inner JOIN 
				akuz.T_BRANCH Branch 
				on Branch.LpuID = Division.Branch
 			inner JOIN 
				akuz.T_LPU_MAIN LpuMain 
				on LpuMain.LpuID = Branch.LpuMain
			inner JOIN
				AKUZ.T_LPU_SETTINGS LpuSettings 
				on LpuSettings.LpuMain = Branch.LpuMain
 			WHERE Visit.VisitID = "VisitID"
 			and 
 			(
				LpuSettings.Preferences & 128 > 0
				or
				exists
				(
					select 1
					from AKUZ.T_ENTRY_BASE eb 
					join AKUZ.T_RESOURCE rr on rr.ResourceID = eb.Resource
					where eb.AmbulanceEvent = Visit.AmbulanceEvent
					and eb.EntryDate = Visit.VisitDate
					and rr.ResourceIdGuid = PResource.ResourceID
				)
			)
			limit 1;
END if;
ELSE 
		DELETE FROM akuz.T_DOCTOR_VISIT_NOTIFY d where d.VisitID = "VisitID" AND d.CreationDT > (Current_TimeStamp::TIMESTAMP - interval '1 day');
end if;
End;
$BODY$
  LANGUAGE plpgsql;
