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

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

CREATE OR REPLACE FUNCTION public."widget_BarChart_Pharmacy_LowSellingProducts"(
	"fromDate" date,
	"filterType" text,
	"displayCount" integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Date" date, "Name" text, "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 
( ddate date, 
  dname text,
  countdata numeric
 ) ON COMMIT DELETE ROWS;
 filtervalue=  "displayCount"||' '|| "filterType";
 intervaldata= '1 '|| "filterType";
 raise notice 'filtervalue %', filtervalue;
 
if "displayCount"=2 then "displayCount"=5;
elsif "displayCount"=3 then "displayCount"=7;
elsif "displayCount"=4 then "displayCount"=9;
else "displayCount"=15; end if;

--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 
	raise notice 'fromdate %', "fromDate"-filtervalue;
	raise notice 'todate %', "fromDate"+filtervalue;
	insert into temp_table (ddate,dname,countdata)
--------------------------------------------------

with lowSellingData as(
select psd."PharmacyProductId",PP."ProductName",  count(psd."PharmacyProductId") "Count" 
from "PharmacySaleDetail" psd
	
	join "PharmacyProduct" pp on pp."PharmacyProductId" = psd."PharmacyProductId"	
	join "PharmacySaleHeader" psh on psh."PharmacySaleHeaderId" = psd."PharmacySaleHeaderId"
	where   psh."CreatedDate"::date >= f.weeks::text::date and psh."CreatedDate"::date <= (f.weeks+ intervaldata)::text::date  
	and case when ("locationId" is null) or ("locationId"=0) then 1=1 else psh."LocationId"= "locationId" end
	group by psd."PharmacyProductId" ,PP."ProductName" 
	
)
,perlowSellingData as (
select a.weeks,a."ProductName",round(a."Count"/sum(a."Count") over()*100,2) "Count" from(
select f.weeks, lsd."ProductName", lsd."Count"
from lowSellingData lsd)a)

select f.weeks, lsd."ProductName", lsd."Count"
from perlowSellingData lsd
order by "Count" asc 
	limit "displayCount";

----------

		
end loop;
	RETURN QUERY
	
	select A.ddate,A.dname,A.countdata from temp_table A
	order by A.countData asc
	limit "displayCount";
	drop table temp_table;
	--drop table temp_date_table;				
	
END;
$BODY$;

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