
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[proc_InsertReferralRewardPoints] (
	@Flag VARCHAR(20)
	,@TranId BIGINT = NULL
	,@CustomerId BIGINT = NULL
	,@ReferralId VARCHAR(100) = NULL
	,@rewardPoints INT  = NULL
	,@rewardValue MONEY  = NULL
	,@type VARCHAR(200) = NULL
	,@pageSize    VARCHAR(50)  = NULL   
    ,@pageNumber   VARCHAR(50)  = NULL    
    ,@sortBy    VARCHAR(50)  = NULL    
    ,@sortOrder    VARCHAR(50)  = NULL
	,@newPoints INT = NULL
	,@oldPoints INT = NULL
	,@promotionType VARCHAR(50) = NULL
	,@user VARCHAR(50) = NULL
	,@isActive BIT = NULL
	,@rowId INT = NULL
	)
AS
BEGIN
	
	SET NOCOUNT ON;
	DECLARE  @table    VARCHAR(MAX)    
    ,@select_field_list VARCHAR(MAX)    
    ,@extra_field_list VARCHAR(MAX)    
    ,@sql_filter  VARCHAR(MAX)    
    ,@agentId INT
	,@regPoint INT
	,@txnPoint INT

    IF @flag = 'REGISTER'
	BEGIN
		SELECT @agentId = BRANCH_ID, @rowId = ROW_ID FROM REFERRAL_AGENT_WISE WHERE REFERRAL_CODE = @ReferralId

		SELECT @regPoint = COMM_PCNT FROM INCENTIVE_SETUP_REFERRAL_WISE WHERE REFERRAL_ID = @rowId

		IF NOT EXISTS (SELECT 'X' FROM REFERRAL_INCENTIVE_TRANSACTION_WISE WHERE CUSTOMER_ID = @CustomerId)
		BEGIN
			INSERT INTO REFERRAL_INCENTIVE_TRANSACTION_WISE (REFERRAL_ID, PARTNER_ID, COMMISSION_PCNT, FX_PCNT, CUSTOMER_ID, CREATED_DATE, REFERRAL_TYPE, TRAN_ID, IS_CANCEL )
		VALUES (@ReferralId, @agentId, @regPoint, 0,  @CustomerId, GETDATE(), 'REGISTRATION', 0, 0)
		END
	END
	ELSE IF @flag = 'TRANSACTION'
	BEGIN
	
		SELECT @agentId = BRANCH_ID, @rowId = ROW_ID FROM REFERRAL_AGENT_WISE WHERE REFERRAL_CODE = @ReferralId

		SELECT @txnPoint = FLAT_TXN_WISE FROM INCENTIVE_SETUP_REFERRAL_WISE WHERE REFERRAL_ID = @rowId
		
		IF NOT EXISTS(SELECT 'X' FROM REFERRAL_INCENTIVE_TRANSACTION_WISE WHERE TRAN_ID = @TranId)
		BEGIN
			INSERT INTO REFERRAL_INCENTIVE_TRANSACTION_WISE (REFERRAL_ID, PARTNER_ID, COMMISSION_PCNT, FX_PCNT, CUSTOMER_ID, CREATED_DATE, REFERRAL_TYPE , TRAN_ID, TXN_DATE, IS_CANCEL )
			VALUES (@ReferralId, @agentId, 0, @txnPoint,  @CustomerId, GETDATE(), 'REF_TRANSACTION', @TranId, GETDATE(), 0)
		END		
	END
END
GO
