-- FUNCTION: public.widget_Table_NewPatientAppointment(date, integer, integer)

DROP FUNCTION IF EXISTS public."widget_Table_NewPatientAppointment"(date, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_Table_NewPatientAppointment"(
	"fromDate" date DEFAULT NULL::date,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Salutation" character varying, "PatientName" text, "UMRNo" character varying, "AppointmentNo" character varying, "AppointmentTime" text) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

select  Pa."Salutation",Pa."FullName" as "PatientName",Pa."UMRNo",
apt."AppointmentNo" ,-- apt."AppointmentTime"::text
 TO_CHAR(apt."AppointmentTime", 'hh12:mi AM')
from "Appointment" apt
--join "AppointmentType" AT on AT."AppointmentTypeId" =apt."AppointmentTypeId"
join "Patient" Pa on Pa."PatientId"  = apt."PatientId" 
join "Provider" Pr on Pr."ProviderId"  = apt."ProviderId" 
where apt."AppointmentDate"::date="fromDate" and apt."Active" is true and apt."VisitTypeId" =43
and Pa."CreatedDate"::date="fromDate" and Pa."Active" is true
and case when "referenceId" is null then 1=1 else apt."ProviderId"= "referenceId" end
and case when "locationId" is null then 1=1 else apt."LocationId"= "locationId" end
 
-- select * from "AppointmentType";
-- select * from "VisitType"
;

end
$BODY$;

ALTER FUNCTION public."widget_Table_NewPatientAppointment"(date, integer, integer)
    OWNER TO postgres;
