USE [FastMoneyPro_Remit]
GO

/****** Object:  StoredProcedure [dbo].[proc_CouponOperation]    Script Date: 7/4/2019 11:35:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER   PROC [dbo].[proc_CouponOperation]
(
 @schemeId VARCHAR(20)=NULL,
 @flag VARCHAR(20)=NULL,
 @serviceCharge MONEY = NULL
)
AS 
BEGIN
IF(@flag='SearchCoupon')
BEGIN
 DECLARE @CurrentCount int = 0,
 @discountvalue MONEY = 0,
 @discountType VARCHAR(2) = NULL
	IF ISNULL(@schemeId,'') <> ''				
				
	BEGIN
		IF EXISTS (SELECT '1' 
		FROM CouponIssue(NOLOCK) AS CI
		INNER JOIN CouponSetup(NOLOCK) AS CS
		ON CI.couponId = CS.rowId
		WHERE CI.rowId = @schemeId
		AND CI.endDate >= GETDATE()
		AND CI.isActive = 'Y'
		AND CS.endDate >= GETDATE()
		AND CS.isActive = 'Y'	
		AND CS.couponType = '1'					   					  
		AND (ISNULL(CS.usageLimit,0) = 0 
		OR ISNULL(CS.usageLimit,0) > ISNULL(CI.usedCount,0))	
		)
		BEGIN
						  
			SELECT TOP(1) 						  
			(CASE CS.discountType WHEN '1' THEN @serviceCharge * (CS.discountValue/100)
			WHEN '2' THEN CS.discountValue END) AS discountValue						 
			FROM CouponIssue(NOLOCK) CI
			INNER JOIN CouponSetup CS
			ON CI.couponId = CS.rowId
			WHERE CI.isActive = 'Y'					   
			AND CI.endDate >= GETDATE()
			AND CS.endDate >= GETDATE()
			AND CS.isActive = 'Y'	
			AND CS.couponType = '1'
			AND CI.rowId = @schemeId					   						   
			AND (ISNULL(CS.usageLimit,0) = 0 
			OR ISNULL(CS.usageLimit,0) > ISNULL(CI.usedCount,0))	
			ORDER BY CI.rowId ASC
		END	
	ELSE
		SELECT 0 AS discountValue			
	END
	ELSE 
		SELECT 0 AS discountValue
END
ELSE IF @flag = 'GetCouponList'
BEGIN
	SELECT CI.rowId, CS.endDate, CS.couponName, CS.couponType, CS.discountType,
	CAST(CS.discountValue AS INT) AS discountValue, CI.startDate
	FROM CouponIssue CI (NOLOCK)
	INNER JOIN CouponSetup AS CS
	ON CI.couponId = CS.rowId
	WHERE CI.customerId = @customerId
	AND   CI.endDate > GETDATE()
	AND   CS.endDATE > GETDATE()
	AND   CI.isActive = 'Y'
	AND   CS.isActive = 'Y'
	AND   CS.usageLimit > CI.usedCount
	RETURN
END

END
GO
