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

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

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

AS $BODY$
begin
return query

with accountdata as (
select a."AccountId",a."FullName" "EmployeeName",rol."RoleName"
from "Account" a
join "Role" rol on rol."RoleId" = a."RoleId" and LOWER(rol."RoleName")<>LOWER('Patient')
join "LocationAccountMap" LA on LA."AccountId"=a."AccountId"
where
 case when "locationId" is null then 1=1 else LA."LocationId"= "locationId" end
)

,PharmaSaleAmount as (	
select a."AccountId", sum(a."Paytm") "PharmaSalePaytm"
	from (
select a."AccountId", 		
	 case when ar."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm"
from "Account" a
left join "PharmacySaleHeader" ar on ar."CreatedBy" = a."AccountId"
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 case when "fromDate" is null then 1=1 else ar."SaleDate"::date = "fromDate" end
	and case when "locationId" is null then 1=1 else ar."LocationId"= "locationId" end
	and case when "referenceId" is null then 1=1 else PA."ReferenceId"= "referenceId" end 
	)a
group by a."AccountId"
)
,PharmaReturnAmount as (
select a."AccountId", sum(a."Paytm") "PharmaReturnPaytm"
	from(
		select a."AccountId",
		case when srh."PayTypeId"=6 then  coalesce(ar."OverallNetAmount",0) else 0 end "Paytm"			
from "Account" a
left join "SaleReturnHeader" ar on ar."CreatedBy" = a."AccountId"
left join "PharmacySaleHeader" srh on srh."PharmacySaleHeaderId" = ar."PharmacySaleHeaderId"
where case when "fromDate" is null then 1=1 else ar."ReturnDate"::date = "fromDate" end	
)a
group by a."AccountId"
)

,PharmaAmount as (
select a."AccountId", 
	 coalesce(a."PharmaSalePaytm",0) - coalesce(b. "PharmaReturnPaytm",0) as  "PharmaSalePaytm" 
from PharmaSaleAmount a
	left join PharmaReturnAmount b on a."AccountId"=b."AccountId"
)

select distinct 
sum(coalesce(pa."PharmaSalePaytm",0)) "TotalPaytm"
from  accountdata a
left join PharmaAmount pa on pa."AccountId"=a."AccountId"
;
end
$BODY$;

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