USE [FastMoneyPro_Remit]
GO
/****** Object:  StoredProcedure [dbo].[proc_sendIRHTP]    Script Date: 7/4/2019 11:35:48 AM ******/
-- DROP PROCEDURE [dbo].[proc_sendIRHTP]
GO
/****** Object:  StoredProcedure [dbo].[proc_sendIRHTP]    Script Date: 7/4/2019 11:35:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


ALTER PROC [dbo].[proc_sendIRHTP] (
	 @flag				VARCHAR(50)
	,@user				VARCHAR(30)
	,@txnPWD			VARCHAR(100)	= NULL
	,@agentRefId		VARCHAR(20)		= NULL
	,@senderId			VARCHAR(50)		= NULL
	,@sfName			VARCHAR(100)	= NULL
	,@smName			VARCHAR(100)	= NULL
	,@slName			VARCHAR(100)	= NULL
	,@slName2			VARCHAR(100)	= NULL
	,@sIdType			VARCHAR(100)	= NULL
	,@sIdNo				VARCHAR(50)		= NULL
	,@sIdValid			DATETIME		= NULL
	,@sdob				DATETIME		= NULL
	,@sTel				VARCHar(20)		= NULL
	,@sMobile			varchar(20)		= NULL
	,@sNaCountry		VARCHAR(50)		= NULL
	,@scity				VARCHAR(100)	= NULL
	,@sPostCode			VARCHAR(50)		= NULL
	,@sAdd1				VARCHAR(150)	= NULL
	,@sAdd2				VARCHAR(150)	= NULL
	,@sEmail			VARCHAR(100)	= NULL
	,@sgender			VARCHAR(100)	= NULL
	,@smsSend			CHAR(1)			= NULL
	,@sCompany			VARCHAR(100)	= NULL
	,@sDcInfo			VARCHAR(50)		= NULL
	,@sIpAddress		VARCHAR(50)		= NULL
	
	,@benId				VARCHAR(50)		= NULL
	,@rfName			VARCHAR(100)	= NULL
	,@rmName			VARCHAR(100)	= NULL
	,@rlName			VARCHAR(100)	= NULL
	,@rlName2			VARCHAR(100)	= NULL
	,@rIdType			VARCHAR(100)	= NULL
	,@rIdNo				VARCHAR(50)		= NULL
	,@rIdValid			DATETIME		= NULL
	,@rdob				DATETIME		= NULL
	,@rTel				VARCHar(20)		= NULL
	,@rMobile			varchar(20)		= NULL
	,@rNaCountry		VARCHAR(50)		= NULL
	,@rcity				VARCHAR(100)	= NULL
	,@rPostCode			VARCHAR(50)		= NULL
	,@rAdd1				VARCHAR(150)	= NULL
	,@rAdd2				VARCHAR(150)	= NULL
	,@rEmail			VARCHAR(100)	= NULL
	,@raccountNo		VARCHAR(50)		= NULL
	,@rgender			VARCHAR(100)	= NULL
    ,@salaryRange	    VARCHAR(150)	= NULL
	
	,@pCountry			VARCHAR(50)		= NULL -- pay country
	,@pCountryId		INT				= NULL -- PAY COUNTRY ID
	,@pSuperAgent		INT				= NULL  --payout Super Agent
	,@deliveryMethod	VARCHAR(50)		= NULL -- payment mode
	,@deliveryMethodId	INT				= NULL -- payment mode ID
	,@pBank				INT				= NULL
	,@pBankName			VARCHAR(100)	= NULL
	,@pBankBranch		INT				= NULL
	,@pBankBranchName	VARCHAR(100)	= NULL
	
	,@pAgent			INT				= NULL
	,@pAgentName		VARCHAR(100)	= NULL
	,@pBranch			INT				= NULL
	,@pBranchName		VARCHAR(100)	= NULL
	,@pBankType			CHAR(1)			= NULL
	
	,@pCurr				VARCHAR(3)		= NULL
	,@collCurr			VARCHAR(3)		= NULL
	,@cAmt				MONEY			= NULL
	,@pAmt				MONEY			= NULL
	,@tAmt				MONEY			= NULL
	,@serviceCharge		MONEY			= NULL
	,@discount			MONEY			= NULL	
	,@exRate			FLOAT			= NULL
	,@schemeType		VARCHAR(50)		= NULL
	,@couponTranNo		VARCHAR(20)		= NULL
	,@purpose			VARCHAR(150)	= NULL
	,@sourceOfFund		VARCHAR(150)	= NULL
	,@relationship		VARCHAR(100)	= NULL
	,@occupation		VARCHAR(100)	= NULL
	,@payMsg			VARCHAR(1000)	= NULL
	,@company			VARCHAR(200)	= NULL
	,@nCust				CHAR(1)			= NULL
	,@enrollCust		CHAR(1)			= NULL
	
	,@controlNo			VARCHAR(20)		= NULL
	,@agentId			INT				= NULL  --payout
	,@sCountryId	     INT			= NULL 
	,@sCountry			VARCHAR(100)	= NULL 
	,@sBranch			INT				= NULL
	,@sBranchName		VARCHAR(100)	= NULL
	,@sAgent			INT				= NULL
	,@sAgentName		VARCHAR(100)	= NULL
	,@sSuperAgent		INT				= NULL
	,@sSuperAgentName	VARCHAR(100)	= NULL
	,@settlingAgent		INT				= NULL
	,@branchMapCode		VARCHAR(10)		= NULL
	,@agentMapCode		VARCHAR(10)		= NULL
	,@collMode			VARCHAR(50)		= NULL
	,@id				BIGINT			= NULL	
	,@sessionId			VARCHAR(50)		= NULL	
	,@cancelrequestId	INT				= NULL
	,@salary			VARCHAR(10)		= NULL		
	,@memberCode		VARCHAR(20)		= NULL	
	,@schemeCode		VARCHAR(20)		= NULL
	,@cwPwd				VARCHAR(10)		= NULL
	,@ttName			VARCHAR(200)	= NULL
	,@ofacRes			VARCHAR(MAX)	= NULL
	,@ofacReason		VARCHAR(200)	= NULL
	,@voucherDetails	XML				= NULL

	,@RBATxnRisk		VARCHAR(15)		= NULL
	,@RBACustomerRisk	VARCHAR(15)		= NULL
	,@RBACustomerRiskValue MONEY		= NULL

	,@pLocation				BIGINT		= NULL
	,@pLocationText			VARCHAR(100)= NULL
	,@pSubLocation			BIGINT		= NULL
	,@pSubLocationText		VARCHAR(100)= NULL
	,@tpExRate				money		= null
	,@tpPCurr				varchar(10) = null
	,@tpRefNo				varchar(30) = null
	,@tpTranId				varchar(30) = null
	,@tpRefNo2				varchar(30) = null
)

AS
--------------------------------------------------------------------------------
		-- @flag = 'success' , For Broadcast Notification
--------------------------------------------------------------------------------
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
BEGIN
	DECLARE
		 @sCurrCostRate				FLOAT
		,@sCurrHoMargin				FLOAT
		,@pCurrCostRate				FLOAT
		,@pCurrHoMargin				FLOAT
		,@sCurrAgentMargin			FLOAT
		,@pCurrAgentMargin			FLOAT
		,@sCurrSuperAgentMargin		FLOAT
		,@pCurrSuperAgentMargin		FLOAT
		,@customerRate				FLOAT
		,@sAgentSettRate			FLOAT
		,@pDateCostRate				FLOAT
		,@agentCrossSettRate		FLOAT
		,@treasuryTolerance			FLOAT
		,@customerPremium			FLOAT
		,@schemePremium				FLOAT
		,@sharingValue				MONEY
		,@sharingType				CHAR(1)
		,@sAgentComm				MONEY
		,@sAgentCommCurrency		VARCHAR(3)
		,@sSuperAgentComm			MONEY
		,@sSuperAgentCommCurrency	VARCHAR(3)
		,@pAgentComm				MONEY
		,@pAgentCommCurrency		VARCHAR(3)
		,@pSuperAgentComm			MONEY
		,@pSuperAgentCommCurrency	VARCHAR(3)
		,@promotionCode				INT
		,@promotionType				INT		
		
		,@pSuperAgentName			VARCHAR(100)
		,@pStateId					INT
		,@agentType					INT
		,@senderName				VARCHAR(100)
		,@pAgentMapCode				VARCHAR(10)
		,@pBranchMapCode			VARCHAR(10)
		,@F_ANYWHERE				CHAR(1)
		,@TRN_TYPE					VARCHAR(100)
		,@complienceMessage			VARCHAR(500)
		,@complienceErrorCode		TINYINT
		,@shortMsg					VARCHAR(100)
	--## USED TO BIND DATA FOR MTRADE
	DECLARE @sederNationalityCode VARCHAR(3)
		, @receiverNationalityCode varchar(3)
		, @rBankCode varchar(20)
		, @rBankBranchCode varchar(20)
		, @pBankCode varchar(20)
		, @pBankBranchCode varchar(20)
		,@pAgentCode varchar(20)

	DECLARE
		 @xAmt			MONEY
		,@baseCurrency	VARCHAR(3)
		,@limitBal				MONEY
		,@sendingCustType		INT
		,@msg					VARCHAR(200)
	DECLARE @iServiceCharge		MONEY, @iTAmt MONEY, @iPAmt MONEY, @iScDiscount MONEY, @iCustomerRate FLOAT, @iCollDetailAmt MONEY
	DECLARE @place INT, @currDecimal INT
	DECLARE @cisMasterId		INT, @compIdResult VARCHAR(300),@perDayCustomerLimit money
	
	DECLARE @controlNoEncrypted VARCHAR(20)
	DECLARE @csMasterId INT, @complianceRes VARCHAR(20), @totalRows INT, @count INT, @compFinalRes VARCHAR(20)
	DECLARE @csMasterRec TABLE (rowId INT IDENTITY(1,1), masterId INT)
	
	SELECT @sBranch = agentId FROM applicationUsers WITH(NOLOCK) WHERE userName = @user
	
	DECLARE @customerTotalAmt2 MONEY = 0

	DECLARE 
		 @tellerBalance MONEY
		,@tellerLimit MONEY
		,@sendPerTransaction MONEY
		,@vaultBalance MONEY
		,@vaultLimit MONEY

	DECLARE @scValue MONEY, @scAction CHAR(2), @scOffer MONEY, @exRateOffer FLOAT, @scDiscount MONEY, @limit money

	IF @salary = 'undefined'
		set @salary = null

	IF @salaryRange = 'undefined'
		set @salaryRange = null
	
	if @pBankBranchName in ('Select','undefined')
		set @pBankBranchName = 'Any Branch'

	IF @senderId IS NOT NULL
		SELECT @senderId = customerId FROM customerMaster WITH(NOLOCK) WHERE idNumber = @sIdNo
	SET @sAgentCommCurrency = 'KRW'
	IF @flag = 'exRate'
	BEGIN
		DECLARE @rowId INT,@errorCode CHAR(1) = 0
		SELECT @scValue = 0, @scOffer = 0, @exRateOffer = 0, @scDiscount = 0

		--1. Get payout currency
		SELECT @pCurr = pCurrency FROM dbo.exRateTreasury WITH(NOLOCK) WHERE pCountry = @pCountryId AND pAgent = @pAgent 
		IF @pCurr IS NULL
			SELECT @pCurr = pCurrency FROM dbo.exRateTreasury WITH(NOLOCK) WHERE pCountry = @pCountryId AND pAgent IS NULL

		--2. Find Decimal Mask for payout amount rounding
		SELECT @currDecimal = rateMaskAd
		FROM crossRateDecimalMask WITH(NOLOCK) 
		WHERE cCurrency = @collCurr and pCurrency = @pCurr

		SET @currDecimal = ISNULL(@currDecimal, 0)

		IF @pCurr IS NULL
		BEGIN
			SELECT '1' ErrCode, 'Currency not been defined yet for receiving country' Msg
			RETURN
		END
		
		SELECT @sAgentSettRate = sAgentSettRate FROM DBO.FNAGetExRate(@sCountryId,@sAgent,@sBranch,@collCurr,@pCountryId,@pAgent,@pCurr,@deliveryMethodId)

		IF ISNULL(@sAgentSettRate, 0) = 0
		BEGIN
			SELECT '1' ErrCode, 'Exchange rate not defined yet for sending currency (' + @collCurr + ')' Msg
			RETURN
		END

		IF ISNULL(@tpExRate, 0) = 0
		BEGIN
			SELECT '1' ErrCode, 'Third Party Exchange rate fetching error for currency (' + @pCurr + ')' Msg
			RETURN
		END

		SELECT @exRate = round(@tpExRate/@sAgentSettRate, 8)

		IF @exRate IS NULL 
		BEGIN
			SELECT '1' ErrCode, 'Exchange rate not defined yet for receiving currency (' + @pCurr + ')' Msg
			RETURN
		END

		IF ISNULL(@cAmt, 0.00) <> 0.00
		BEGIN
			SELECT @serviceCharge = amount FROM [dbo].FNAGetServiceCharge(
						@sCountryId, @sSuperAgent, @sAgent, @sBranch 
						,@pCountryId, @pSuperAgent, @pAgent, @pBranch 
						,@deliveryMethod, @cAmt, @collCurr
						)

			IF @serviceCharge IS NULL 
			BEGIN
				SELECT '1' ErrCode, 'Service charge not defined yet for receiving country' Msg
				RETURN;
			END
				
			IF @scAction = 'PD' -- Percent Discount
			BEGIN
				SET @scOffer = (@scValue/100) * @serviceCharge
				SET @scDiscount = (@scValue/100) * @serviceCharge
			END
			ELSE IF @scAction = 'FD' -- Flat Discount
			BEGIN
				SET @scDiscount = @scValue
			END
			ELSE IF @scAction = 'FV' -- Fixed Value
			BEGIN
				SET @scOffer = @scValue
				SET @scDiscount = @serviceCharge - @scValue
			END
				
			SET @tAmt = @cAmt - @serviceCharge + @scDiscount
				
			SET @pAmt = @tAmt * (@exRate + @exRateOffer)	
			
			SET @pAmt = ROUND(@pAmt, 0)
			
		END
		ELSE
		BEGIN
			SET @tAmt = ROUND(@pAmt/(@exRate + @exRateOffer),0)
			SELECT  @serviceCharge = amount FROM [dbo].FNAGetServiceCharge(
						@sCountryId, @sSuperAgent, @sAgent, @sBranch 
					,@pCountryId, @pSuperAgent, @pAgent, @pBranch 
					,@deliveryMethod, @tAmt, @collCurr
			)

			IF @serviceCharge IS NULL 
			BEGIN
				SELECT '1' ErrCode, 'Service charge not defined yet for receiving country' Msg
				RETURN;
			END
				
			IF @scAction = 'PD'
			BEGIN
				SET @scOffer = (@scValue/100) * @serviceCharge
				SET @scDiscount = (@scValue/100) * @serviceCharge
			END
			ELSE IF @scAction = 'FD'
			BEGIN
				SET @scDiscount = @scValue
			END
			ELSE IF @scAction = 'FV'
			BEGIN
				SET @scOffer = @scValue
				SET @scDiscount = @serviceCharge - @scValue
			END
				
			SET @cAmt = (@tAmt + @serviceCharge - @scDiscount)
			SET @cAmt = ROUND(@cAmt, @currDecimal)
			--IF @place IS NOT NULL
			--	SET @cAmt = ROUND(@cAmt, -@place)			
		END		

		--3. Get Agent Send Per Txn
		IF EXISTS(SELECT 'X' FROM sendTranLimit
					WHERE agentId = @sAgent
					AND ISNULL(receivingCountry, ISNULL(@pCountryId, 0)) = ISNULL(@pCountryId, 0)
					AND ISNULL(tranType, ISNULL(@deliveryMethod, 0)) = ISNULL(@deliveryMethod, 0)
					AND currency = @collCurr AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N'
				)
		BEGIN
			IF EXISTS(SELECT 'X' FROM sendTranLimit WITH(NOLOCK) WHERE agentId = @sAgent AND receivingCountry = @pCountryId 
						AND tranType = @deliveryMethod AND currency = @collCurr 
						AND @cAmt < minLimitAmt
						AND @cAmt > maxLimitAmt
						AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N')
			BEGIN
				SELECT '1' ErrCode, 'Agent Sending limit is exceeded.' Msg
				RETURN
			END
			IF EXISTS(SELECT 'X' FROM sendTranLimit WITH(NOLOCK) WHERE agentId = @sAgent AND receivingCountry = @pCountryId 
						AND tranType IS NULL AND currency = @collCurr 
						AND @cAmt < minLimitAmt
						AND @cAmt > maxLimitAmt
						AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N')
			BEGIN
				SELECT '1' ErrCode, 'Agent Sending limit is exceeded.' Msg
				RETURN
			END
			IF EXISTS(SELECT 'X' FROM sendTranLimit WITH(NOLOCK) WHERE agentId IS NULL AND receivingCountry = @pCountryId 
						AND tranType = @deliveryMethod AND currency = @collCurr 
						AND @cAmt < minLimitAmt
						AND @cAmt > maxLimitAmt
						AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N')
			BEGIN
				SELECT '1' ErrCode, 'Agent Sending limit is exceeded.' Msg
				RETURN
			END
			IF EXISTS(SELECT 'X' FROM sendTranLimit WITH(NOLOCK) WHERE agentId = @sAgent AND receivingCountry = @pCountryId 
						AND tranType IS NULL AND currency = @collCurr 
						AND @cAmt < minLimitAmt
						AND @cAmt > maxLimitAmt
						AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N')
			BEGIN
				SELECT '1' ErrCode, 'Agent Sending limit is exceeded.' Msg
				RETURN
			END
		END

		--4. Validate Country Sending Limit 
        EXEC PROC_CHECKCOUNTRYLIMIT @flag = 's-limit', @cAmt = @cAmt, @pAmt = @pAmt, @sCountryId = @sCountryId, @collMode = @collMode
			,@deliveryMethod = @deliveryMethod,@sendingCustType = @sendingCustType,@pCountryId = @pCountryId,@pCurr = @pCurr, @collCurr = @collCurr
			,@pAgent = @pAgent, @sAgent = @sAgent, @sBranch = @sBranch
			,@msg = @msg OUT, @errorCode = @errorCode OUT

		IF @errorCode <> '0'
		BEGIN
			SELECT @errorCode ErrCode, @msg Msg
			RETURN;
		END
		--Validate Country Sending Limit END

		--5. Validate Country Receiving Limit
        EXEC PROC_CHECKCOUNTRYLIMIT @flag = 'r-limit', @cAmt = @cAmt, @pAmt = @pAmt, @sCountryId = @sCountryId, @collMode = @collMode
			,@deliveryMethod = @deliveryMethod,@sendingCustType = @sendingCustType,@pCountryId = @pCountryId,@pCurr = @pCurr, @collCurr = @collCurr
			,@pAgent = @pAgent, @sAgent = @sAgent, @sBranch = @sBranch
			,@msg = @msg OUT, @errorCode = @errorCode OUT
			
		IF @errorCode <> '0'
		BEGIN
			SELECT @errorCode ErrCode, @msg Msg
			RETURN;
		END
		--Validate Country Receiving Limit

		SET @msg = 'Success'
		SELECT 
			@errorCode ErrCode, @msg Msg, scCharge = @serviceCharge
			,exRate = @exRate, place = @place
			,pCurr = @pCurr, currDecimal = @currDecimal
			,pAmt =@pAmt, sAmt = @tAmt
			,disc = 0.00, collAmt = @cAmt
			,exRateOffer = @sAgentSettRate, scOffer = @scDiscount, scAction = @scAction, scValue = @scValue, scDiscount = @scDiscount, tpExRate = @tpExRate
	END

	ELSE IF  @flag = 'v'
	BEGIN
		IF isnull(@rMobile, '')=''
		BEGIN
			EXEC proc_errorHandler 1, 'Receiver mobile number is required!', NULL
			RETURN
		END
		IF isnull(@rAdd1, '')=''
		BEGIN
			EXEC proc_errorHandler 1, 'Receiver address is required!', NULL
			RETURN
		END

		IF isnull(@sAdd1, '')=''
		BEGIN
			EXEC proc_errorHandler 1, 'Sender address is required!', NULL
			RETURN
		END

		if isnull(@purpose,'') = ''
		BEGIN
			EXEC proc_errorHandler 1, 'Purpose of Remittance is required!', NULL
			RETURN
		END
		if isnull(@sourceOfFund,'') = ''
		BEGIN
			EXEC proc_errorHandler 1, 'Source of Fund is required!', NULL
			RETURN
		END
		IF @sfName IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Sender First Name missing', NULL
			RETURN
		END
		IF (select COUNT(1) from  dbo.Split(' ',@sfName) where len(value) >2)<2
		BEGIN
			EXEC proc_errorHandler 1, 'Sender full Name is missing', NULL
			RETURN
		END

		IF @sNaCountry IS NULL
		BEGIN
			EXEC proc_errorHandler 1, ' Sender Native Country missing', NULL
			RETURN
		END	
		IF @rfName IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Receiver full Name is missing', NULL
			RETURN
		END
		
		IF (select COUNT(1) from  dbo.Split(' ',@rfName) where len(value) >2)<2
		BEGIN
			EXEC proc_errorHandler 1, 'Receiver full Name is missing', NULL
			RETURN
		END

		IF @sIdType = 'Alien Registration Card'
		BEGIN
			IF LEN(@sIdNo) <> 14 OR @sIdNo NOT LIKE '%-%'
			BEGIN
				EXEC proc_errorHandler 1, 'Invalid Alian Card number found', NULL
				RETURN
			END
		END
		
		IF ISNULL(@deliveryMethod, '') = ''
		BEGIN
			EXEC proc_errorHandler 1, 'Please choose payment mode', NULL
			RETURN
		END
		IF @serviceCharge IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Service Charge missing', NULL
			RETURN
		END
		IF ISNULL(@tAmt, 0) = 0
		BEGIN
			EXEC proc_errorHandler 1, 'Transfer Amount missing', NULL
			RETURN
		END
		IF ISNULL(@exRate, 0) = 0
		BEGIN
			EXEC proc_errorHandler 1, 'Exchange Rate missing', NULL
			RETURN
		END
		
		IF ISNULL(@cAmt, 0) = 0
		BEGIN
			EXEC proc_errorHandler 1, 'Collection Amount is missing. Cannot send transaction', NULL
			RETURN	
		END 
		IF @serviceCharge > @cAmt
		BEGIN
			EXEC proc_errorHandler 1, 'Collection Amount is less than service charge.', NULL
			RETURN	
		END 

		--*****Payout Agent*****
		IF @deliveryMethod = 'Cash Payment'
		BEGIN
			IF @pBank IS NOT NULL
			BEGIN
				SELECT @pAgent = @pBank, @pAgentName = @pBankName
				IF @pBankBranch IS NOT NULL
					SELECT @pBranch = @pBankBranch, @pBranchName = @pBankBranchName
			END
		END
		ELSE IF @deliveryMethod = 'Bank Deposit'
		BEGIN
				
			IF @pBank IS NULL
			BEGIN
				EXEC proc_errorHandler 1, 'Please select bank', NULL
				RETURN
			END
			IF @pBankBranch IS NULL
			BEGIN
				EXEC proc_errorHandler 1, 'Please select bank Branch', NULL
				RETURN
			END
			IF @raccountNo IS NULL
			BEGIN
				EXEC proc_errorHandler 1, 'Account number cannot be blank', NULL
				RETURN
			END
		END
		
		IF (@pBankBranch IS NOT NULL)
		BEGIN
			SELECT @pBank = parentId, @pBankBranchName = agentName FROM agentMaster WITH(NOLOCK) WHERE agentId = @pBankBranch
			SELECT @pBankName = agentName FROM agentMaster WITH(NOLOCK) WHERE agentId = @pBank
		END
		
		--3. Limit Checking---------------------------------------------------------------------------------------------------------------------
		SELECT @sendingCustType = customerType FROM dbo.customerMaster WITH(NOLOCK) WHERE customerId = @senderId
		
		--END of Credit Limit Section
		
		SELECT @place = place, @currDecimal = currDecimal
		FROM currencyPayoutRound WITH(NOLOCK) WHERE ISNULL(isDeleted, 'N') = 'N' 
		AND currency = @pCurr AND ISNULL(tranType,@deliveryMethodId) = @deliveryMethodId

		SET @currDecimal = ISNULL(@currDecimal, 0)

		SELECT @sAgentSettRate = sAgentSettRate FROM DBO.FNAGetExRate(@sCountryId,@sAgent,@sBranch,@collCurr,@pCountryId,@pAgent,@pCurr,@deliveryMethodId)

		IF ISNULL(@sAgentSettRate, 0) = 0
		BEGIN
			SELECT '1' ErrCode, 'Exchange rate not defined yet for sending currency (' + @collCurr + ')' Msg
			RETURN
		END

		IF ISNULL(@tpExRate, 0) = 0
		BEGIN
			SELECT '1' ErrCode, 'Third Party Exchange rate fetching error for currency (' + @pCurr + ')' Msg
			RETURN
		END
		
		SELECT @exRate = round(@tpExRate/@sAgentSettRate, 8)

		IF @exRate IS NULL 
		BEGIN
			SELECT '1' ErrCode, 'Exchange rate not defined yet for receiving currency (' + @pCurr + ')' Msg
			RETURN
		END

		--End of Exchange Rate Checking
		SELECT @pSuperAgent = sSuperAgent,@pSuperAgentName = sSuperAgentName,
				@pAgent = sAgent,@pAgentName = sAgentName ,@pBranch = sBranch,@pBranchName = sBranchName
		FROM dbo.FNAGetBranchFullDetails(2129)
		--5. Service Charge Checking
		SELECT @iServiceCharge = ISNULL(amount, -1) FROM [dbo].FNAGetServiceCharge(
							@sCountryId, @sSuperAgent, @sAgent, @sBranch, 
							@pCountryId, @pSuperAgent, @pAgent, @pBranch, 
							@deliveryMethodId, @cAmt, @collCurr
						) 
		
		IF @iServiceCharge = -1
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Service Charge is not defined', NULL
			RETURN
		END
		
		SET @iServiceCharge = ROUND(@iServiceCharge, 2)
		IF @iServiceCharge <> @serviceCharge
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Amount detail not match. Please check service charge', NULL
			RETURN
		END

		SET @iCustomerRate = @exRate + ISNULL(@schemePremium, 0)
		SET @iTAmt = @cAmt - @iServiceCharge

		SET @place = ISNULL(@place, 0)
		
		SET @iPAmt = @iTAmt * @iCustomerRate

		IF @pCurr = 'USD'
			SET @iPAmt = ROUND(@iPAmt, @currDecimal)
		ELSE 
			SET @iPAmt = ROUND(@iPAmt, 0)
		

		IF @iPAmt <> @pAmt
		BEGIN
			EXEC proc_errorHandler 1, 'Amount detail not match. Please re-calculate the amount again.', NULL
			RETURN
		END
		--End of service charge Checking
		
		--START OFAC Checking 
		DECLARE @receiverName VARCHAR(200)
		
		IF(ISNULL(@senderId, '') = '')
			SELECT @senderName = @sfName + ISNULL(' ' + @smName, '') + ISNULL(' ' + @slName, '') + ISNULL(' ' + @slName2, '')
		ELSE
			SELECT @senderName = firstName + ISNULL(' ' + middleName, '') + ISNULL(' ' + lastName1, '') + ISNULL(' ' + lastName2, '') 
			FROM dbo.customerMaster WITH(NOLOCK) WHERE customerId = @senderId
		
		SELECT @receiverName = @rfName + ISNULL(' ' + @rmName, '') + ISNULL(' ' + @rlName, '') + ISNULL(' ' + @rlName2, '')

		DECLARE @receiverOfacRes VARCHAR(MAX)
		EXEC proc_ofacTracker @flag = 't', @name = @senderName, @Result = @ofacRes OUTPUT
		EXEC proc_ofacTracker @flag = 't', @name = @receiverName, @Result = @receiverOfacRes OUTPUT
		
		DECLARE @result VARCHAR(MAX)
		IF ISNULL(@ofacRes, '') <> ''
		BEGIN
			SET @ofacReason = 'Matched by sender name'
		END
		IF ISNULL(@receiverOfacRes, '') <> ''
		BEGIN
			SET @ofacRes = ISNULL(@ofacRes + ',' + @receiverOfacRes, '' + @receiverOfacRes)
			SET @ofacReason = 'Matched by receiver name'
		END
		IF ISNULL(@ofacRes, '') <> '' AND ISNULL(@receiverOfacRes, '') <> ''
		BEGIN
			SET @ofacReason = 'Matched by both sender name and receiver name'
		END
		
		--******************BEGINING OF NEW CUSTOMER CREATION AND ENROLLMENT********************************
		DECLARE @sIdTypeId INT
		SELECT @sIdTypeId = valueId from staticDataValue WITH(NOLOCK) WHERE detailTitle = @sIdType AND typeID = 1300
		
		SELECT @sfName = UPPER(@sfName), @smName = UPPER(@smName), @slName = UPPER(@slName), @slName2 = UPPER(@slName2)
		SELECT @rfName = UPPER(@rfName), @rmName = UPPER(@rmName), @rlName = UPPER(@rlName), @rlName2 = UPPER(@rlName2)
		--2. Begining of New customer Creation and enrollment or updating existing customer data---
		SET @senderName = @sfName + ISNULL(' ' + @smName, '') + ISNULL(' ' + @slName, '') + ISNULL(' ' + @slName2, '')
		SET @receiverName = @rfName + ISNULL(' ' + @rmName, '') + ISNULL(' ' + @rlName, '') + ISNULL(' ' + @rlName2, '')

		DECLARE @sNaCountryId INT = (SELECT countryId FROM COUNTRYMASTER (NOLOCK) WHERE COUNTRYNAME = @sNaCountry)

		--------#Register Customer if not registered#---------------
		EXEC PROC_CHECK_CUSTOMER_REGISTRATION @flag = 'i', @customerName = @senderName, @customerIdNo = @sIdNo, @customerIdType = @sIdTypeId, 
			@nativeCountryId = @sNaCountryId, @customerId = @senderId OUT, @user = @user, @custAdd = @sAdd1, @custCity = @scity, @custEmail = @sEmail,
			@custMobile = @sMobile, @custDOB = @sdob, @custIdValidDate = @sIdValid, @occupation = @occupation, @ipAddress = @sIpAddress

		IF @senderId = '0000'
		BEGIN
			EXEC proc_errorHandler 1, 'Sender Email can not be blank.', NULL
			RETURN
		END

		--START Compliance Checking
		DECLARE @complianceRuleId INT, @cAmtUSD MONEY
  
		SELECT 
			@sCurrCostRate			= sCurrCostRate
			,@sCurrHoMargin			= sCurrHoMargin
		FROM dbo.FNAGetExRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, @pAgent, @pCurr, @deliveryMethodId)

		IF @sCurrCostRate IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Exchange Rate not defined!', NULL
			RETURN
		END
			
		SET @cAmtUSD = @cAmt / (@sCurrCostRate + ISNULL(@sCurrHoMargin, 0))
		
		SELECT @sCountry = countryName FROM dbo.countryMaster(nolock) WHERE countryId = @sCountryId
		
		EXEC [proc_complianceRuleDetail]
				 @flag			= 'core'
				,@user			= @user
				,@sIdType		= @sIdType
				,@sIdNo			= @sIdNo
				,@receiverName  = @rfName
				,@cAmt			= @cAmt
				,@cAmtUSD		= @cAmtUSD
				,@customerId	= @senderId
				,@pCountryId	= @pCountryId
				,@deliveryMethod= @deliveryMethodId
				,@message		= @complienceMessage OUTPUT
				,@shortMessage  = @shortMsg    OUTPUT
				,@errCode		= @complienceErrorCode OUTPUT
				,@ruleId		= @complianceRuleId  OUTPUT
		
		IF(@complienceErrorCode <> 0 OR ISNULL(@ofacRes, '') <> '')
		BEGIN		
			IF @@TRANCOUNT > 0
			COMMIT TRANSACTION
			IF(@ofacRes <> '')
			BEGIN
				SET @result = @ofacRes + '|' + ISNULL(@ofacReason, '')
				SELECT errorCode = 100, msg = 'WARNING!!! This customer is listed on OFAC List', id = @result
				EXEC proc_sendPageLoadData @flag = 'ofac', @user = @user, @blackListIds = @ofacRes
			END
			IF(@complienceErrorCode = 1)
			BEGIN
				SELECT 101 errorCode,@msg msg, @complienceErrorCode id, @complienceMessage compApproveRemark,'compliance' vtype
			END 
			IF(@complienceErrorCode = 2)
			BEGIN
				INSERT remitTranComplianceTemp(csDetailTranId, matchTranId, agentRefId)
				SELECT @complianceRuleId, NULL, @agentRefId

				SELECT 102 errorCode,@msg msg, @complienceErrorCode id, @complienceMessage compApproveRemark,'compliance' vtype
			END
			IF (@complienceErrorCode <> 0)
			BEGIN
			    INSERT INTO ComplianceLog(senderName, senderCountry, senderIdType, senderIdNumber, senderMobile, receiverName, receiverCountry, payOutAmt,
				complianceId, complianceReason, complainceDetailMessage, createdBy, createdDate)

				SELECT @senderName, @sCountry, @sIdType, @sIdNo, @sMobile, @receiverName, @pCountry, @cAmt, @complianceRuleId, @shortMsg, @complienceMessage, @user, GETDATE()

				DECLARE @tempRowId INT = @@IDENTITY

				SELECT
					 id
					,csDetailRecId = ''
					,[S.N.]		= ROW_NUMBER()OVER(ORDER BY id)	
					,[Remarks]	= complianceReason
					,[Action]	= CASE WHEN @complienceErrorCode=2 THEN 'HOLD' ELSE 'Blocked' END
					--,[Matched Tran ID] = ''
				FROM ComplianceLog (nolock)
				WHERE id = @tempRowId
			END
			RETURN
		END 

		--END OFAC/Compliance data
		
		EXEC proc_errorHandler 0, 'Validation successful', NULL
		
		--*****Check For Same Name*****
		SELECT tranId = rt.id, senderName, sIdType = sen.idType, sIdNo = sen.idNumber, cAmt, pCountry 
		FROM remitTran rt WITH(NOLOCK)
		INNER JOIN tranSenders sen WITH(NOLOCK) ON rt.id = sen.tranId 
		WHERE senderName = @senderName AND createdDate BETWEEN CONVERT(VARCHAR, GETDATE(), 101) AND CONVERT(VARCHAR, GETDATE(), 101) + ' 23:59:59'
		
		--*****Check For Same Id*****
		SELECT tranId = rt.id, senderName, sIdType = sen.idType, sIdNo = sen.idNumber, cAmt, pCountry 
		FROM remitTran rt WITH(NOLOCK)
		INNER JOIN tranSenders sen WITH(NOLOCK) ON rt.id = sen.tranId 
		WHERE idType = @sIdType AND idNumber = @sIdNo 
		AND createdDate BETWEEN CONVERT(VARCHAR, GETDATE(), 101) AND CONVERT(VARCHAR, GETDATE(), 101) + ' 23:59:59'

	END

	ELSE IF @flag = 'i'					--Send Transaction
	BEGIN
		--1. Field Validation-----------------------------------------------------------
		IF @user IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Your session has expired. Cannot send transaction', NULL
			RETURN
		END
		IF @sIdType = 'Alien Registration Card'
		BEGIN
			IF LEN(@sIdNo) <> 14 OR @sIdNo NOT LIKE '%-%'
			BEGIN
				EXEC proc_errorHandler 1, 'Invalid Alian Card number found', NULL
				RETURN
			END
		END
		IF NOT EXISTS(SELECT 'X' FROM applicationUsers WITH(NOLOCK) WHERE PWD = [REDACTED] AND userName = @user)
		BEGIN
			EXEC proc_errorHandler 1, 'TXN password is invalid !', @user
			RETURN
		END

		IF (ISNULL(@deliveryMethod, '') = ''
			OR @serviceCharge IS NULL
			OR ISNULL(@cAmt, 0) = 0
			OR ISNULL(@tAmt,0) = 0
			OR ISNULL(@exRate, 0) = 0)
		BEGIN
			EXEC proc_errorHandler 1, 'Mandatory Field(s) missing', NULL
			RETURN
		END
		
		--******************BEGINING OF NEW CUSTOMER CREATION AND ENROLLMENT********************************
		SELECT @sIdTypeId = valueId from staticDataValue WITH(NOLOCK) WHERE detailTitle = @sIdType AND typeID = 1300
		
		SELECT @sfName = UPPER(@sfName), @smName = UPPER(@smName), @slName = UPPER(@slName), @slName2 = UPPER(@slName2)
		SELECT @rfName = UPPER(@rfName), @rmName = UPPER(@rmName), @rlName = UPPER(@rlName), @rlName2 = UPPER(@rlName2)
		--2. Begining of New customer Creation and enrollment or updating existing customer data---
		SET @senderName = @sfName + ISNULL(' ' + @smName, '') + ISNULL(' ' + @slName, '') + ISNULL(' ' + @slName2, '')
		SET @receiverName = @rfName + ISNULL(' ' + @rmName, '') + ISNULL(' ' + @rlName, '') + ISNULL(' ' + @rlName2, '')

		SET @sNaCountryId = (SELECT countryId FROM COUNTRYMASTER (NOLOCK) WHERE COUNTRYNAME = @sNaCountry)

		--------#Register Customer if not registered#---------------
		EXEC PROC_CHECK_CUSTOMER_REGISTRATION @flag = 'i', @customerName = @senderName, @customerIdNo = @sIdNo, @customerIdType = @sIdTypeId, 
			@nativeCountryId = @sNaCountryId, @customerId = @senderId OUT, @user = @user, @custAdd = @sAdd1, @custCity = @scity, @custEmail = @sEmail,
			@custMobile = @sMobile, @custDOB = @sdob, @custIdValidDate = @sIdValid, @occupation = @occupation, @ipAddress = @sIpAddress

		SET @nCust = 'Y'

		IF @nCust = 'N' AND @senderId IS NULL 
		BEGIN
			EXEC proc_errorHandler 1, 'Mandatory Field(s) missing', NULL
			RETURN
		END	
	
		IF ISNULL(@cAmt, 0) = 0
		BEGIN
			EXEC proc_errorHandler 1, 'Collection Amount is missing', NULL
			RETURN	
		END 
		
		IF @serviceCharge > @cAmt
		BEGIN
			EXEC proc_errorHandler 1, 'Collection Amount is less than service charge.', NULL
			RETURN	
		END 

		SET @controlNo = '80' + LEFT(CAST(ABS(CHECKSUM(NEWID())) AS VARCHAR(10)) + '0000000000', 9)
		
		IF EXISTS(SELECT 'X' FROM controlNoList WITH(NOLOCK) WHERE controlNo = @controlNo)
		BEGIN
			SET @controlNo = '80' + LEFT(CAST(ABS(CHECKSUM(NEWID())) AS VARCHAR(10)) + '0000000000', 9)
			IF EXISTS(SELECT 'X' FROM controlNoList WITH(NOLOCK) WHERE controlNo = @controlNo)
			BEGIN
				EXEC proc_errorHandler 1, 'Technical error occurred. Please try again', NULL
				RETURN
			END
		END
		
		SELECT @controlNoEncrypted = dbo.FNAEncryptString(@controlNo)
		
		IF @deliveryMethod IN ('Cash Payment', 'Door to Door')
		BEGIN
			IF @deliveryMethod = 'Door to Door'
			BEGIN
				SET @payMsg = ' [Door To Door Location:' + @pBankBranchName + ', ' + @pBankBranchName + ' ]'
			END
			IF @pBank IS NOT NULL
			BEGIN
				SELECT @pAgent = @pBank, @pAgentName = @pBankName
				IF @pBankBranch IS NOT NULL
					SELECT @pBranch = @pBankBranch, @pBranchName = @pBankBranchName
			END
		END
		ELSE IF @deliveryMethod = 'Bank Deposit'
		BEGIN
			IF @pBank IS NULL 
			BEGIN
				EXEC proc_errorHandler 1, 'Bank is required for Bank Deposit ', NULL
				RETURN
			END
			
		END

		--3. Check Limit starts
	
		--Credit Limit Section
		SELECT @limitBal = dbo.FNAGetLimitBalIRH(@settlingAgent)
		IF @tAmt > @limitBal
		BEGIN
			EXEC [proc_errorHandler] 1, 'Transfer amount exceeds Limit. Please, Check your available limit.', @controlNo
			RETURN		
		END

		SELECT @pSuperAgent = sSuperAgent,@pSuperAgentName = sSuperAgentName,
				@pAgent = sAgent,@pAgentName = sAgentName ,@pBranch = sBranch,@pBranchName = sBranchName
		FROM dbo.FNAGetBranchFullDetails(2129)
		--Get Service Charge----------------------------------------------------------------------------------------------------------------------
		SELECT @iServiceCharge = ISNULL(amount, -1) FROM [dbo].FNAGetServiceCharge(
							@sCountryId, @sSuperAgent, @sAgent, @sBranch, 
							@pCountryId, @pSuperAgent, @pAgent, @pBranch, 
							@deliveryMethodId, @cAmt, @collCurr
						) 
		IF @iServiceCharge = -1
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Service Charge is not defined', NULL
			RETURN
		END
		
		IF @iServiceCharge <> @serviceCharge
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Amount detail not match', NULL
			RETURN
		END

		--End-------------------------------------------------------------------------------------------------------------------------------------
		
		SELECT @place = place, @currDecimal = currDecimal
		FROM currencyPayoutRound WITH(NOLOCK) WHERE ISNULL(isDeleted, 'N') = 'N' 
		AND currency = @pCurr AND ISNULL(tranType,@deliveryMethodId) = @deliveryMethodId

		SET @currDecimal = ISNULL(@currDecimal, 0)

		--4. Get Exchange Rate Details------------------------------------------------------------------------------------------------------------------
		SELECT 
			 @customerRate			= round(@tpExRate/sAgentSettRate, 8)
			,@sCurrCostRate			= sCurrCostRate
			,@sCurrHoMargin			= sCurrHoMargin
			,@sCurrAgentMargin		= sCurrAgentMargin
			,@pCurrCostRate			= @tpExRate
			,@pCurrHoMargin			= 0
			,@pCurrAgentMargin		= 0
			,@agentCrossSettRate	= round(@tpExRate/sAgentSettRate, 8)
			,@treasuryTolerance		= 0
			,@customerPremium		= 0
			,@sharingValue			= 0
		FROM dbo.FNAGetExRate(@sCountryId,@sAgent,@sBranch,@collCurr,@pCountryId,@pAgent,@pCurr,@deliveryMethodId)
		
		IF @customerRate IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Exchange Rate not defined', NULL
			RETURN
		END
		
		SET @serviceCharge = @serviceCharge - ISNULL(@scDiscount, 0)
		SET @iServiceCharge = @iServiceCharge - ISNULL(@iScDiscount, 0)
		
		SET @tAmt = @cAmt - @serviceCharge

		SET @iCustomerRate = @customerRate + ISNULL(@schemePremium, 0)
		SET @iTAmt = @cAmt - @iServiceCharge
		
		SET @iPAmt = @iTAmt * @iCustomerRate

		IF @pCurr = 'USD'
			SET @iPAmt = ROUND(@iPAmt, @currDecimal)
		ELSE 
			SET @iPAmt = ROUND(@iPAmt, 0)


		IF @iPAmt <> @pAmt
		BEGIN
			EXEC proc_errorHandler 1, 'Amount detail not match. Please re-calculate the amount again.', NULL
			RETURN
		END

		DECLARE @agentFxGain MONEY
		SET @agentFxGain = ((@tAmt) *(@agentCrossSettRate - (@customerRate + ISNULL(@schemePremium, 0))))/@agentCrossSettRate

		--**********Customer Per Day Limit Checking**********
		DECLARE @remitTranTemp TABLE(tranId BIGINT, controlNo VARCHAR(20), cAmt MONEY, receiverName VARCHAR(200), receiverIdType VARCHAR(100), receiverIdNumber VARCHAR(50), dot DATETIME)
		DECLARE @moneySendTemp TABLE(tranNo BIGINT, refno VARCHAR(20), paidAmt MONEY, receiverName VARCHAR(200), receiverIdDescription VARCHAR(100), receiverIdDetail VARCHAR(50), dot DATETIME)
		
		INSERT INTO @remitTranTemp(tranId, controlNo, cAmt, receiverName, receiverIdType, receiverIdNumber, dot)
		SELECT rt.id, rt.controlNo, rt.cAmt, rt.receiverName, rec.idType, rec.idNumber, rt.createdDateLocal
		FROM vwRemitTran rt WITH(NOLOCK)
		INNER JOIN vwTranSenders sen WITH(NOLOCK) ON rt.id = sen.tranId
		INNER JOIN vwTranReceivers rec WITH(NOLOCK) ON rt.id = rec.tranId
		WHERE sen.idNumber = @sIdNo 
		AND (tranStatus <> 'CancelRequest' AND tranStatus <> 'Cancel')
		AND (rt.approvedDate BETWEEN CONVERT(VARCHAR, GETDATE(), 101) AND CONVERT(VARCHAR, GETDATE(), 101) + ' 23:59:59'
		OR (approvedBy IS NULL AND cancelApprovedBy IS NULL))
		
		IF EXISTS(SELECT 'X' FROM @remitTranTemp WHERE cAmt = @cAmt 
					AND (receiverName = @receiverName OR (ISNULL(receiverIdType, '0') = @rIdType AND ISNULL(receiverIdNumber, '0') = @rIdNo))
					AND DATEDIFF(MI, dot, GETDATE()) <= 5
				)
		BEGIN
			EXEC proc_errorHandler 1, 'Similar transaction found. You can process similar transaction after 5 minutes.', NULL
			RETURN
		END
	
		DECLARE @customerTotalSentAmt MONEY = 0, @txnSumTobeDeducted MONEY = 0
		
		SELECT @customerTotalSentAmt = SUM(cAmt) FROM @remitTranTemp
		SELECT @customerTotalAmt2 = SUM(paidAmt) FROM @moneySendTemp
		SELECT @txnSumTobeDeducted = ISNULL(SUM(paidAmt), 0)
		FROM @moneySendTemp mst
		INNER JOIN @remitTranTemp rtt ON mst.refno = rtt.controlNo
		
		IF (ISNULL(@customerTotalAmt2, 0) + ISNULL(@customerTotalSentAmt, 0) + @cAmt - @txnSumTobeDeducted) > dbo.FNAGetPerDayCustomerLimit(@settlingAgent)
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Customer Limit exceeded.', NULL
			RETURN
		END

		-- #########country and occupation  risk point
		DECLARE @countryRisk INT,@OccupationRisk INT,@isFirstTran CHAR(1)
		
		SET @isFirstTran = CASE WHEN @nCust='Y' THEN 'Y' END
		
		SELECT @sNaCountry = CASE WHEN @nCust='Y' THEN @sNaCountry ELSE nativeCountry END
		FROM tranSenders WITH(NOLOCK) WHERE customerId = @senderId
		
		IF NOT EXISTS(SELECT 'Z' FROM tranSenders WITH(NOLOCK) WHERE customerId = @senderId)
			SET @isFirstTran ='Y'
			
	    SELECT @countryRisk = ISNULL(fatfRating, 0) FROM countryMaster C WITH(NOLOCK) WHERE countryName = @sNaCountry AND ISNULL(C.isActive,'Y') = 'Y' AND ISNULL(C.isDeleted,'N') = 'Y'
	    SELECT @OccupationRisk = ISNULL(riskFactor,0) FROM occupationMaster WITH(NOLOCK) WHERE occupationId = @occupation AND ISNULL(isActive,'Y')='Y' AND ISNULL(isDeleted,'N')='Y'
		
		--##Get Voucher Details into temp table START##--

		SELECT voucherNo = p.value('@voucherNo', 'varchar(30)')
			,voucherDate = p.value('@voucherDate', 'date')
			,voucherAmount = p.value('@voucherAmount', 'varchar(25)')
			,bankId = p.value('@bankId', 'int')
				
		INTO #tempVoucherData
		FROM @voucherDetails.nodes('/root/row') AS tmp(p)

		--RBA 
		DECLARE @RBAScoreTxn MONEY, @RBAScoreCustomer MONEY
		SELECT
			 @RBAScoreCustomer	= @RBACustomerRiskValue
			,@RBAScoreTxn		= CASE WHEN @RBATxnRisk = 'LOW RISK' THEN 40
									WHEN @RBATxnRisk  = 'MEDIUM RISK' THEN 50 
									WHEN @RBATxnRisk  = 'HIGH RISK' THEN 51 
								 ELSE 100 END
		

		SELECT @pSuperAgent = sSuperAgent,@pSuperAgentName = sSuperAgentName,
				@pAgent = sAgent,@pAgentName = sAgentName ,@pBranch = sBranch,@pBranchName = sBranchName
		FROM dbo.FNAGetBranchFullDetails(2129)
		--##Get Voucher Details into temp table END##--

		select @pAgentCommCurrency = 'USD'
		select 
			@pAgentComm = (SELECT amount FROM FastMoneyPro_Remit.dbo.FNAGetPayComm(
			 @sAgent,@sCountryId,NULL, NULL, @pCountryId
			, null, @pAgent, @pAgentCommCurrency,@deliveryMethodId, @cAmt, @pAmt, @serviceCharge, NULL, NULL)
			)

		BEGIN TRANSACTION
			INSERT INTO remitTranTemp(
				 controlNo
				,sCurrCostRate,sCurrHoMargin,sCurrSuperAgentMargin,sCurrAgentMargin
				,pCurrCostRate,pCurrHoMargin,pCurrSuperAgentMargin,pCurrAgentMargin
				,agentCrossSettRate,customerRate,sAgentSettRate,pDateCostRate
				,treasuryTolerance,customerPremium,schemePremium,sharingValue
				--,sharingType
				,serviceCharge,handlingFee, agentFxGain
				,sAgentComm,sAgentCommCurrency,sSuperAgentComm,sSuperAgentCommCurrency
				,pAgentComm,pAgentCommCurrency,pSuperAgentComm,pSuperAgentCommCurrency
				,promotionCode,promotionType
				,pMessage
				,sSuperAgent,sSuperAgentName,sAgent,sAgentName,sBranch,sBranchName,sCountry
				,pSuperAgent,pSuperAgentName,pAgent,pAgentName,pBranch,pBranchName,pCountry
				,paymentMethod
				,pBank,pBankName,pBankBranch,pBankBranchName,accountNo,pBankType
				,expectedPayoutAgent
				,collMode,collCurr,tAmt,cAmt,pAmt,payoutCurr
				,relWithSender,purposeOfRemit,sourceOfFund
				,tranStatus,payStatus
				,createdDate,createdDateLocal,createdBy	
				,tranType,voucherNo	
				,senderName
				,receiverName	
				,pState
				,pDistrict
				,controlNo2
			)				
						
			SELECT
				 @controlNoEncrypted
				,@sCurrCostRate,@sCurrHoMargin,@sCurrSuperAgentMargin,@sCurrAgentMargin
				,@pCurrCostRate,@pCurrHoMargin,@pCurrSuperAgentMargin,@pCurrAgentMargin
				,@agentCrossSettRate,@customerRate,@sAgentSettRate,@pDateCostRate
				,@treasuryTolerance,@customerPremium,ISNULL(@schemePremium,0),@sharingValue
				--,@sharingType
				,@serviceCharge,ISNULL(@scDiscount,0), @agentFxGain
				,@sAgentComm,@sAgentCommCurrency,@sSuperAgentComm,@sSuperAgentCommCurrency
				,@pAgentComm,@pAgentCommCurrency,@pSuperAgentComm,@pSuperAgentCommCurrency
				,@promotionCode,@promotionType
				,@payMsg
				,@sSuperAgent,@sSuperAgentName,@sAgent,@sAgentName,@sBranch,@sBranchName,@sCountry
				,@pSuperAgent,@pSuperAgentName,@pAgent,@pAgentName,@pBranch,@pBranchName,@pCountry
				,@deliveryMethod
				,@pBank,@pBankName,@pBankBranch,@pBankBranchName,@raccountNo,@pBankType
				,@pAgentName
				,@collMode,@collCurr,@tAmt,@cAmt,@pAmt,@pCurr
				,@relationship,@purpose,@sourceOfFund
				,'Hold','Unpaid'
				,DBO.FNADateFormatTZ(GETDATE(), @user),GETDATE(),@user
				,'I',''
				,@senderName
				,@receiverName
				,@pLocation, @pSubLocation
				,@controlNoEncrypted
				
			SET @id = SCOPE_IDENTITY()	
			
			INSERT INTO bankCollectionVoucherDetail( tempTranId ,voucherNo ,voucherDate ,voucherAmt ,bankId)
			SELECT @id, voucherNo, voucherDate, voucherAmount, bankId FROM #tempVoucherData
			
			INSERT INTO controlNoList(controlNo)
			SELECT @controlNo

			
			INSERT INTO tranSendersTemp(
				 tranId,customerId,membershipId
				,firstName,middleName,lastName1,lastName2
				,fullName
				,country,[address],address2,zipCode,city,email
				,homePhone,mobile,nativeCountry
				,dob,placeOfIssue,idType,idNumber,validDate
				,occupation
				,countryRiskPoint,customerRiskPoint
				,isFirstTran
				,salary,companyName
				,cwPwd,ttName
				,dcInfo,ipAddress,RBA
				
			)
			SELECT 
					 @id,@senderId,@memberCode,@sfName,@smName,@slName,@slName2
					,@senderName,@sCountry
					,@sAdd1,@sAdd2,@sPostCode,@scity,@sEmail,@sTel,@sMobile,@sNaCountry,@sdob
					,@sIdTypeId,@sIdType,@sIdNo,@sIdValid,@occupation,@countryRisk,@RBAScoreCustomer
					,@isFirstTran,@salaryRange
					,@company,@cwPwd,@ttName,@sDcInfo,@sIpAddress, @RBAScoreTxn
					
				
			
			INSERT INTO tranReceiversTemp(
				 tranId,customerId,membershipId
				,firstName,middleName,lastName1,lastName2
				,fullName
				,country,[address],zipCode,city,email
				,homePhone,workPhone,mobile,nativeCountry,dob,placeOfIssue
				,idType,idNumber,idPlaceOfIssue,issuedDate,validDate,gender
				,STATE,district
			)
			SELECT
				 @id,@benId,''
				,@rfName,@rmName,@rlName,@rlName2
				,@receiverName
				,@pCountry,@rAdd1,@rPostCode,@rcity,@rEmail
				,@rTel,@rTel,@rMobile,@rNaCountry,@rdob,NULL
				,@rIdType,@rIdNo,NULL,NULL,@rIdValid,@rgender
				,@pLocationText, @pSubLocationText			
		

			EXEC proc_customerTxnHistory @controlNo = @controlNoEncrypted

			--**********DEPOSIT DETAIL HANDLING********** 
			DECLARE @bankSumAmt money, @reSendAmt money, @cashSumAmt money					
			
		--10. Compliance----------------------------------------------------------------------------------------------------
		IF EXISTS(SELECT 'X' FROM remitTranComplianceTemp WITH(NOLOCK) WHERE agentRefId = @agentRefId)
		BEGIN
			INSERT INTO remitTranCompliance(TranId, csDetailTranId, matchTranId)
			SELECT @id, csDetailTranId, matchTranId FROM remitTranComplianceTemp WITH(NOLOCK) WHERE agentRefId = @agentRefId
			SET @compFinalRes = 'C'
		END
		
		IF EXISTS(SELECT 'X' FROM @remitTranTemp 
		WHERE dot BETWEEN CONVERT(VARCHAR, GETDATE(), 101) AND CONVERT(VARCHAR, GETDATE(), 101) + ' 23:59:59' 
		AND cAmt = @cAmt AND (receiverName = @receiverName OR (ISNULL(receiverIdType, '0') = @rIdType 
		AND ISNULL(receiverIdNumber, '0') = @rIdNo)))
		BEGIN
			INSERT INTO remitTranCompliance(TranId, csDetailTranId, matchTranId, reason)
			SELECT @id, 0, tranid, 'Suspected duplicate transaction' FROM @remitTranTemp WHERE cAmt = @cAmt AND (receiverName = @receiverName OR (ISNULL(receiverIdType, '0') = @rIdType AND ISNULL(receiverIdNumber, '0') = @rIdNo))
			SET @compFinalRes = 'C'
		END
		ELSE
		BEGIN
			IF EXISTS(SELECT 'X' FROM @moneySendTemp WHERE paidAmt = @cAmt AND (receiverName = @receiverName OR (ISNULL(receiverIdDescription, '0') = @rIdType AND ISNULL(receiverIdDetail, '0') = @rIdNo)))
			BEGIN
				INSERT INTO remitTranCompliance(TranId, csDetailTranId, matchTranId, reason)
				SELECT @id, 0, tranNo, 'Suspected duplicate transaction from Inficare system' FROM @moneySendTemp WHERE paidAmt = @cAmt AND (receiverName = @receiverName OR (ISNULL(receiverIdDescription, '0') = @rIdType AND ISNULL(receiverIdDetail, '0') = @rIdNo))
				SET @compFinalRes = 'C'
			END
		END

		IF(ISNULL(@compFinalRes, '') <> '' OR ISNULL(@ofacRes, '') <> '')
		BEGIN
			IF(@ofacRes <> '' AND ISNULL(@compFinalRes, '') = '')
			BEGIN
				INSERT remitTranOfac(TranId, blackListId, reason, flag)
				SELECT @id, @ofacRes, @ofacReason, dbo.FNAGetOFAC_Flag(@ofacRes)
				
				UPDATE remitTranTemp SET
					 tranStatus	= 'OFAC Hold'
				WHERE controlNo = @controlNoEncrypted
			END
			
			ELSE IF(@compFinalRes <> '' AND ISNULL(@ofacRes, '') = '')
			BEGIN
				UPDATE remitTranTemp SET
					 tranStatus	= 'Compliance Hold'
				WHERE controlNo = @controlNoEncrypted
			END
			
			ELSE IF(ISNULL(@compFinalRes, '') <> '' AND ISNULL(@ofacRes, '') <> '')
			BEGIN
				INSERT remitTranOfac(TranId, blackListId, reason, flag)
				SELECT @id, @ofacRes, @ofacReason, dbo.FNAGetOFAC_Flag(@ofacRes)
				
				UPDATE remitTranTemp SET
					 tranStatus	= 'OFAC/Compliance Hold'
				WHERE controlNo = @controlNoEncrypted
			END
		END

		IF @@TRANCOUNT > 0
		COMMIT TRANSACTION
		
		IF(@complianceRes = 'C' OR @ofacRes <> '')
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction under compliance', @controlNo
			RETURN
		END
		
		EXEC [proc_errorHandler] 100, 'Transaction has been sent successfully and is waiting for approval', @controlNo	

		--****Data For TP****----
		SELECT @sederNationalityCode = countryCode FROM countryMaster (NOLOCK) WHERE countryName = @sNaCountry
		SELECT @receiverNationalityCode = countryCode FROM countryMaster (NOLOCK) WHERE countryId = @pCountryId
		select @rBankBranchCode = agentCode from agentmaster (nolock) where agentId = @pBankBranch
		select @rBankCode = agentCode, @pAgentCode = routingCode from agentmaster (nolock) where agentId = @pBank		
			
		select sederNationalityCode = @sederNationalityCode
				, sIdTypeCode = case @sIdType when 'Alien Registration Card' then '21' 
											  when 'National ID' then '9'
											  when 'Passport' then '2'
											  end
				,rIdTypeCode = case @sIdType when 'National ID' then '9' when 'Passport' then '2' else '21' end 
				,receiverNationalityCode = @receiverNationalityCode
				,rBankCode = @rBankCode
				,rBankBranchCode = @rBankBranchCode
				,sourceOfFund = '12'					--Others, so we can send our source of fund text.
				,reasonOfRemittance = '17'
				,senderOccoupation = '99'
				,remitType = 'P2P'
				,pAgentCode = @pAgentCode
		
	END

	ELSE IF @flag = 'success'
	BEGIN
	-- For mobile broadcast notification
	
		DECLARE @CustomerId  BIGINT , @availableBalance MONEY
		SELECT  @customerId = (SELECT TST.customerId FROM remitTrantemp RTT WITH(NOLOCK) INNER JOIN dbo.tranSendersTemp TST(NOLOCK) ON TST.TRANID = RTT.ID WHERE controlNo = dbo.FNAEncryptString(@controlNo))
		SELECT   @availableBalance =  (SELECT * FROM [FNAGetCustomerAvailableBalance](@customerId))
		
		IF EXISTS (SELECT TST.customerId FROM remitTrantemp RTT WITH(NOLOCK) INNER JOIN dbo.tranSendersTemp TST(NOLOCK) ON TST.TRANID = RTT.ID  WHERE controlNo = dbo.FNAEncryptString(@controlNo) AND @availableBalance <= RTT.cAmt )
		BEGIN
			EXEC ProcBroadCastMobile @Flag='TF_TXN_NO_BALANCE', @RowId=@customerId, @ControlNo=@controlNo, @CustomerId= @customerId
		END
		

		update remitTranTemp set controlno = dbo.FNAEncryptString(@tpRefNo)
								,controlNo2 = dbo.FNAEncryptString(@controlNo)
								,uploadLogId = @tpTranId
								,sharingValue = pcurrCostRate
								,pcurrCostRate = case when @tpExRate is not null then @tpExRate else pcurrCostRate end
								
		where controlno = dbo.FNAEncryptString(@controlNo)

		EXEC [proc_errorHandler] 0, 'Transaction has been sent successfully', @tpRefNo
	END
	ELSE IF @flag = 'revertTxn'
	BEGIN

		select @id = id from remitTranTemp(nolock) where controlno = dbo.FNAEncryptString(@controlNo)
		EXEC proc_ApproveHoldedTXN @flag = 'reject', @user =@user , @id =@id
	END

	ELSE IF @flag = 'pagent'
	BEGIN
		SELECT routingCode FROM agentMaster (nolock) where agentId = @pAgent
	END
	ELSE IF @flag = 'ReProcess'
	BEGIN

		SELECT @sNaCountry = S.nativeCountry,@pCountry = T.pCountry,@pBankBranch = T.pBankBranch,@pBank = T.pBank
				,@sIdType = S.idType,@rIdType = R.idType
		FROM remitTran T(NOLOCK)
		INNER JOIN tranSenders S(NOLOCK) ON S.tranId = T.id
		INNER JOIN tranReceivers R(NOLOCK) ON R.tranId = T.id
		WHERE T.controlNo = dbo.FNAEncryptString(@controlNo)

		--****Data For TP****----
		SELECT @sederNationalityCode = countryCode FROM countryMaster (NOLOCK) WHERE countryName = @sNaCountry
		SELECT @receiverNationalityCode = countryCode FROM countryMaster (NOLOCK) WHERE countryName = @pCountry
		select @rBankBranchCode = agentCode from agentmaster (nolock) where agentId = @pBankBranch
		select @rBankCode = agentCode, @pAgentCode = routingCode from agentmaster (nolock) where agentId = @pBank		
		
		SELECT	
				errorCode = 0,collTranId = @controlNo
				,payoutAgentCd = @pAgentCode,payoutAmount = pAmt,payoutCurrency = payoutCurr
				,payoutMode = case when paymentMethod ='CASH PAYMENT' then 2 else 1 end 
				,senderFirstName='Tamang',senderMiddleName='',senderLastName='santosh',senderAddress='hwaseong si'
				,senderNationalityCd = @sederNationalityCode
				,senderIdCardTypeCd = case @sIdType when 'Alien Registration Card' then '21' when 'National ID' then '9'end
				,senderIdCardTypeNo = s.idNumber,senderMonthlySalary=''
				,receiverFirstName='SUMON',receiverMiddleName='',receiverLastName='GHOSH',receiverAddress=r.address
				,rIdTypeCode = case @sIdType when 'National ID' then '9' else '21' end 
				,senderPhoneNo = '821046842625',receiverPhoneNo='0091970606253'
				,receiverNationalityCd = @receiverNationalityCode
				,receiverBankCd = @rBankCode
				,receiverBankBranchCd = @rBankBranchCode,receiverBankAcNo=t.accountNo
				,receiverIdCardTypeNo='',receiverIdCardTypeCd=''
				,sourceOfFundCd = '12',sourceOfFundText=t.sourceOfFund					--Others, so we can send our source of fund text.
				,reasonOfRemittanceCd = '17',reasonOfRemittanceText=t.purposeOfRemit
				,senderOccupationCd = '99'
				,remitType = 'P2P'
		FROM remitTran T(NOLOCK)
		INNER JOIN tranSenders S(NOLOCK) ON S.tranId = T.id
		INNER JOIN tranReceivers R(NOLOCK) ON R.tranId = T.id
		WHERE T.controlNo = dbo.FNAEncryptString(@controlNo)

	END
END

END TRY
BEGIN CATCH
	IF @@TRANCOUNT<>0
		ROLLBACK TRANSACTION
	DECLARE @errorMessage VARCHAR(MAX)
	SET @errorMessage = ERROR_MESSAGE()
	EXEC proc_errorHandler 1, @errorMessage, @user
END CATCH


GO
