-- FUNCTION: public.widget_Table_PharmacyRetailStockProducts_ExpiryInMonths(date, integer, text)

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

CREATE OR REPLACE FUNCTION public."widget_Table_PharmacyRetailStockProducts_ExpiryInMonths"(
	"selectDate" date DEFAULT NULL::date,
	"locationId" integer DEFAULT NULL::integer,
	"retailStore" text DEFAULT NULL::text)
    RETURNS TABLE("ProductName" character varying, "GenericName" character varying, "RetailName" text, "BatchNumber" character varying, "ExpiryDate" date) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
begin
return query

SELECT
	PP."ProductName",
	PP."GenericName",
	RP."RetailName",
	PS."BatchNumber",
	PS."ExpiryDate"
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"
WHERE
	(PS."QuantityIn" - PS."QuantityOut") <> 0
	and case when "retailStore" is null then 1=1 else RP."RetailName"="retailStore" end
	AND case when "selectDate" is null then 1=1 else PS."ExpiryDate" <="selectDate"::date  end
	AND case when "locationId" is null then 1=1 else PW."LocationId" = "locationId" end
	order by PS."ExpiryDate"
;

end
$BODY$;

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