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

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

CREATE OR REPLACE FUNCTION public."widget_BarChart_Lab_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 
( labdate date,
  labamount 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 (labdate,labamount)
	
	select f.weeks,coalesce(sum(coalesce(ar."NetAmount",0)),0) "LabAmount" 
from "LabBookingHeader" ar
left join "Provider" pr on pr."ProviderId"= ar."ProviderId"
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 ar."Active" <> false and (ar."CreatedDate"::date >= f.weeks::text::date and ar."CreatedDate"::date < (f.weeks+ intervaldata)::text::date)
and case when ("locationId" is null) or ("locationId"=0) then 1=1 else ar."LocationId"= "locationId" end
and case when ("referenceId" is null) or ("referenceId"=0) then 1=1 else PA."ReferenceId"= "referenceId" end
;
	
	
	
   
    end loop;
	RETURN QUERY
	select A.labdate,A.labamount from temp_table A;
	drop table temp_table;
END;
$BODY$;

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