-- FUNCTION: public.udf_PharmacySales_Report(timestamp without time zone, timestamp without time zone, integer, character varying, text)

--
DROP FUNCTION public."udf_PharmacySales_Report"(timestamp without time zone, timestamp without time zone, integer, character varying, text);

CREATE OR REPLACE FUNCTION public."udf_PharmacySales_Report"(
	"fromDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"toDate" timestamp without time zone DEFAULT (now())::timestamp without time zone,
	"createdBy" integer DEFAULT NULL::integer,
	"payTypeId" integer DEFAULT NULL::integer,
	"locationId" text DEFAULT NULL::text)
    RETURNS TABLE("SaleDate" timestamp without time zone, "TotalAmount" numeric,
				  "TotalTaxes" numeric, "TotalDiscount" numeric, "TotalNetAmount" numeric,
				  "PaidVia" character varying,"PaymentNumber" character varying, "LocationName" character varying) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN
return query

select PH."SaleDate" , sum(PH."Total") "Total", sum(PH."OverallTaxes") "OverallTaxes",
sum(PH."OverallDiscount") "OverallDiscount", 
sum(PH."OverallNetAmount") "OverallNetAmount", PT."PayTypeName" as "PaidVia",PH."PaymentNumber",
L."Name" as "LocationName"

from "PharmacySaleHeader" PH
join "Location" L on L."LocationId" = PH."LocationId"
left join "PayType" PT on PT."PayTypeId"=PH."PayTypeId"

where case when "fromDate" is null then 1=1 else PH."SaleDate" >= "fromDate" end
and case when "toDate" is null then 1=1 else  PH."SaleDate" <= "toDate" end 
and case when "createdBy" is null then 1=1 else PH."CreatedBy"="createdBy" end   

and case when "payTypeId" is null then 1=1 else PT."PayTypeId" ="payTypeId" end
and case when "locationId" is null then 1=1 else PH."LocationId" = "locationId"::int end
group by PH."SaleDate",PT."PayTypeName",PH."PaymentNumber" ,L."Name" 
order by PH."SaleDate" desc;
END
$BODY$;

--ALTER FUNCTION public."udf_PharmacySales_Report"(timestamp without time zone, timestamp without time zone, integer, character varying, text)
   -- OWNER TO postgres;
