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

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

CREATE OR REPLACE FUNCTION public."widget_Pharmacy_OverAll_OnlinePaymentTotal"(
	"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."OnlinePayment") "PharmaSaleOnlinePayment"
	from (
select a."AccountId", 		
	 case when ar."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "OnlinePayment"
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."OnlinePayment") "PharmaReturnOnlinePayment"
	from(
		select a."AccountId",
		case when srh."PayTypeId"=4 then  coalesce(ar."OverallNetAmount",0) else 0 end "OnlinePayment"			
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."PharmaSaleOnlinePayment",0) - coalesce(b. "PharmaReturnOnlinePayment",0) as  "PharmaSaleOnlinePayment" 
from PharmaSaleAmount a
	left join PharmaReturnAmount b on a."AccountId"=b."AccountId"
)

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

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