DROP PROCEDURE IF EXISTS sp_ConvertTickets;
CREATE PROCEDURE sp_ConvertTickets("LpuMain" uuid)
AS
$BODY$
DECLARE	_d timestamp;
	_pt int;
	_st int;
	_et int;
	_tt int;
Begin
	_d := current_timestamp::timestamp;
	_d := case	when date_part('hour', _d) > 7
			then date_trunc('day', _d) + interval '1 day'
			else date_trunc('day', _d)
		end;

	_pt := (select EntityID from VCLib.T_ENTITIES where EntName = 'PRIMARY_TICKET' and Schema = 'AKUZ' limit 1);
	_st := (select EntityID from VCLib.T_ENTITIES where EntName = 'SECONDARY_TICKET' and Schema = 'AKUZ' limit 1);
	_et := (select EntityID from VCLib.T_ENTITIES where EntName = 'EXAM_TICKET' and Schema = 'AKUZ' limit 1);
	_tt := (select EntityID from VCLib.T_ENTITIES where EntName = 'TELECONSULTATION_TICKET' and Schema = 'AKUZ' limit 1);
	
	update AKUZ.T_TICKET t
	set type_ = _pt -- primary
	from AKUZ.T_WORK_SCHEDULE_ITEM wsi 
	inner join 
		AKUZ.T_WORK_SCHEDULE ws 
		on ws.WorkScheduleID = wsi.WorkSchedule
	inner join 
		AKUZ.T_RESOURCE r 
		on r.ResourceID = ws.Resource
	inner join 
		AKUZ.T_DIVISION d 
		on d.DivisionID = r.Division
	inner join 
		AKUZ.T_BRANCH b 
		on b.LpuID = d.Branch
	where wsi.WorkScheduleItemID = t.WorkScheduleItem
	and t.type_ in (_st, _et, _tt) -- secondary, exam, teleconsultation
	and wsi.WorkDate = _d
	and t.EntryBase is null
	and b.LpuMain = "LpuMain";
End;
$BODY$
  LANGUAGE plpgsql;