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

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

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

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

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