-- FUNCTION: public.widget_BarChart_Appointment_Revenue(date, text, integer,integer,integer)

-- DROP FUNCTION IF EXISTS public."widget_BarChart_Appointment_Revenue"(date, text, integer,integer,integer);

CREATE OR REPLACE FUNCTION public."widget_BarChart_Appointment_Revenue"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
declare
f record;
filtervalue interval;
intervaldata interval;
fromdate date;
begin
create  Temp TABLE temp_table 
( appointmentdate date,
  appointmentamount numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";
 raise notice ' %', filtervalue;
 --fromdate:=case when "filterType"='day' then "fromDate" 
 --else date_trunc('month', "fromDate"::date) end;
for f in SELECT generate_series("fromDate" -  filtervalue , "fromDate" +   filtervalue,  intervaldata) weeks
    loop 
	
	insert into temp_table (appointmentdate,appointmentamount)

with actappointmentamount as (
	
	select  A.appointmentamount::bigint appointmentamount from (
   select    sum(coalesce(AP."Total",0)) appointmentamount
		
from "Appointment" ap
		--left join "Provider" pr on pr."ProviderId"= ap."ProviderId" and ap."Active" =true
						--left join "ProviderLocation" PL on PL."ProviderId"=pr."ProviderId" and case when "locationId" is null then 1=1 else  PL."LocationId"= "locationId" end
						--left join "Account" PA on PA."ReferenceId"=pr."ProviderId" and PA."RoleId"=3
   where ap."Status" <> 'C' 
	and	(Ap."AppointmentDate" >= f.weeks::text::date and Ap."AppointmentDate" < (f.weeks+ intervaldata)::text::date)
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else AP."LocationId"= "locationId" end
	--and case when ("referenceId" is null) or ("referenceId"=0) then 1=1 else PA."ReferenceId"= "referenceId" end
	  	)a
)
select  f.weeks,coalesce((select (coalesce(appointmentamount,0))  :: numeric as "AppointmentAmount" 
						 from actappointmentamount A),0) ;
   
    end loop;
	RETURN QUERY
	select A.appointmentdate,A.appointmentamount from temp_table A;
	drop table temp_table;
END;
$BODY$;

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