-- =============================================
-- Author:		Marat Zigangaraev
-- Create date: 2011/06/28
-- Description:	Обработка ENTRY_LOG
-- =============================================
drop procedure if exists sp_processentrylog2;
CREATE procedure sp_processentrylog2
(
	"Action" integer	-- 1-insert, 2-update, 3-delete
,	"EntryID" uuid
,	"PerformerMO" uuid default NULL::uuid
,	"PerformerResource" integer default NULL::integer
,	"PerformerDivision" uuid default NULL::uuid
,	"PerformerSpeciality" uuid default NULL::uuid
,	"PerformerBranch" uuid default NULL::uuid
,	"EntryPlace" int default NULL::int
,	"EntryKind" int default NULL::int
,	"Channel" int default NULL::int
,	"PayType" int default NULL::int
,	"WorkDate" timestamp default NULL::timestamp
,	"Year" int default NULL::int
,	"Month" int default NULL::int
,	"Week" int default NULL::int
,	"Day" int default NULL::int
,	"Kv" int default NULL::int
,	"DirectorRemoteUser" uuid default NULL::uuid
,	"DirectorPost" integer default NULL::integer
,	"DirectorDivision" uuid default NULL::uuid
,	"DirectorLpuMain" uuid default NULL::uuid
,	"DirectorSpeciality" uuid default NULL::uuid
,	"DirectorGroup" uuid default NULL::uuid
,	"UserID" uuid default NULL::uuid
)
AS
$BODY$
Begin	
	If "Action" = 1
	then
		insert into AKUZ.T_ENTRY_LOG2(EntryLogID, RuleID, QuotaKey, EntryID, PerformerMO, PerformerResource, PerformerDivision, PerformerSpeciality, PerformerBranch
			, Year, Month, Week, Day, Kv, DirectorRemoteUser, DirectorPost, DirectorDivision, DirectorLpuMain, DirectorSpeciality, EntryPlace, EntryKind, Channel
			, PayType, WorkDate, DirectorGroup, UserID)
		VALUES(uuid_generate_v4(), null, null, "EntryID", "PerformerMO", "PerformerResource", "PerformerDivision", "PerformerSpeciality", "PerformerBranch"
			, "Year", "Month", "Week", "Day", "Kv", "DirectorRemoteUser", "DirectorPost", "DirectorDivision", "DirectorLpuMain", "DirectorSpeciality"
			, "EntryPlace", "EntryKind", "Channel", "PayType", "WorkDate", "DirectorGroup", "UserID");
	elsif "Action" = 2
	then
		if "DirectorRemoteUser" is not null
	    then
			-- смена идентификатора
			Update AKUZ.T_ENTRY_LOG2
			Set EntryID = "DirectorRemoteUser"
			Where EntryID = "EntryID";
		else
			-- перезапись
			Update AKUZ.T_ENTRY_LOG2 
			Set	WorkDate = "WorkDate"
			,	PerformerMO = "PerformerMO"
			,	PerformerResource = "PerformerResource"
			,	PerformerDivision = "PerformerDivision"
			,	PerformerSpeciality = "PerformerSpeciality"
			,	PerformerBranch = "PerformerBranch"
			,	EntryPlace = "EntryPlace"
			,	Year = "Year"
			,	Month = "Month"
			,	Week = "Week"
			,	Day = "Day"
			,	Kv = "Kv"
			Where EntryID = "EntryID"; 
		end if;
	elsif "Action" = 3
	then
		Delete From AKUZ.T_ENTRY_LOG2 Where EntryID = "EntryID";
	end if;
	return;
End;
$BODY$
  LANGUAGE plpgsql;