-- FUNCTION: public.widget_Table_PharmacyRetailStockProducts_UnderROL(integer, integer, text)

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

CREATE OR REPLACE FUNCTION public."widget_Table_PharmacyRetailStockProducts_UnderROL"(
	"accountId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer,
	"retailStore" text DEFAULT NULL::text)
    RETURNS TABLE("ProductName" character varying, "GenericName" character varying, "RetailName" text, "AvailableQty" bigint) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

SELECT
	PP."ProductName",
	PP."GenericName",
	RP."RetailName",
	SUM(PS."QuantityIn" - PS."QuantityOut") AS "AvailableQty"
FROM
	"PharmacyRetailStock" PS
	JOIN "RetailWareHouseLink" PWL ON PWL."RetailWareHouseLinkId" = PS."RetailWareHouseLinkId"
	JOIN "PharmacyWareHouse" PW ON PW."PharmacyWareHouseId" = PWL."PharmacyWareHouseId"
	JOIN "RetailPharmacy" RP ON RP."RetailPharmacyId" = PWL."RetailPharmacyId"
	JOIN "PharmacyProduct" PP ON PP."PharmacyProductId" = PS."PharmacyProductId"
	JOIN "PharmacyRetailUser" PRU ON PRU."RetailPharmacyId"=RP."RetailPharmacyId"
WHERE
	PP."RolQuantity" > ( PS."QuantityIn" - PS."QuantityOut" )
	and (PS."QuantityIn" - PS."QuantityOut") <> 0
	and case when "retailStore" is null then 1=1 else RP."RetailName"="retailStore" end
	AND case when "accountId" is null then 1=1 else PRU."AccountId"="accountId" end
	AND case when "locationId" is null then 1=1 else PW."LocationId" = "locationId" end
	group by PS."PharmacyProductId",PP."ProductName",PP."GenericName",RP."RetailName"
;

end
$BODY$;

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