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

CREATE PROC [dbo].[proc_sendIRH] (
	 @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
)

AS

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)

	DECLARE
		 @xAmt			MONEY
		,@baseCurrency	VARCHAR(3)

		,@limitBal				MONEY
		,@sendingCustType		INT
		,@receivingCustType		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 @errorCode CHAR(1) = 0

	DECLARE 
		 @tellerBalance MONEY
		,@tellerLimit MONEY
		,@sendPerTransaction MONEY
		,@vaultBalance MONEY
		,@vaultLimit 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 = @senderId
	
	SET @sAgentCommCurrency = 'KRW'	
	IF @flag = 'acBal'					--Get Available Account Balance
	BEGIN
		SELECT 
			 @pCountryId = am.agentCountryId
		FROM applicationUsers au WITH(NOLOCK)
		INNER JOIN agentMaster am WITH(NOLOCK) ON au.agentId = am.agentId
		WHERE userName = @user

		SELECT TOP 1 @collCurr = CM.currencyCode
		FROM currencyMaster CM WITH(NOLOCK)
		INNER JOIN countryCurrency CC WITH(NOLOCK) ON CM.currencyId = CC.currencyId
		WHERE CC.countryId = @pCountryId AND ISNULL(cc.isDeleted,'N') = 'N'

		-->> checking per day country send limit 
		SELECT 
			@limitBal = D.amount 
		FROM csMaster M WITH (NOLOCK)
		INNER JOIN csDetail D WITH(NOLOCK) ON M.csMasterId = D.csDetailId
		WHERE sCountry = @pCountryId
		AND ISNULL(M.isActive,'Y') = 'Y' AND ISNULL(D.isActive,'Y')='Y' 				

		IF @agentId IS NULL
			SELECT @sBranch = agentId FROM applicationUsers WITH(NOLOCK) WHERE userName = @user
		ELSE
			SELECT @sBranch = @agentId
		
		SELECT @sAgent = parentId, @agentType = agentType FROM agentMaster WITH(NOLOCK) 
		   WHERE agentId = @sBranch

		IF @agentType = 2903
			SET @sAgent = @sBranch
		
		SELECT @sSuperAgent = parentId FROM agentMaster WITH(NOLOCK) 
			  WHERE agentId = @sAgent
		
		SELECT @settlingAgent = agentId FROM agentMaster 
			  WHERE agentId = @sBranch AND isSettlingAgent = 'Y'
		
		 IF @settlingAgent IS NULL
			SELECT @settlingAgent = agentId FROM agentMaster WITH(NOLOCK) WHERE agentId = @sAgent AND isSettlingAgent = 'Y'
		IF @settlingAgent IS NULL
			SELECT @settlingAgent = agentId FROM agentMaster WITH(NOLOCK) WHERE agentId = @sSuperAgent AND isSettlingAgent = 'Y'
		
		DECLARE @limit MONEY, @limitCurr VARCHAR(3), @cRateAgent FLOAT

		SELECT @limit = ISNULL(dbo.FNAGetLimitBalIRH(@settlingAgent), 0)
		SELECT @limitCurr = currency FROM creditLimitInt WITH(NOLOCK) 
		WHERE agentId = @settlingAgent AND ISNULL(isDeleted, 'N') = 'N' AND ISNULL(isActive, 'N') = 'Y'
		
		SELECT 
			 availableBal				= @limit
			,balCurrency				= @collCurr
			,limExpiry					= ISNULL(CONVERT(VARCHAR, expiryDate, 101), 'N/A')
			,sCountryLimit				= ISNULL(@limitBal,0)
			,sCurr						= @collCurr			
			,tellerBanalce				= 0
			,txnPerDayCustomerLimit		= dbo.FNAGetPerDayCustomerLimit(@settlingAgent)
		FROM creditLimitInt cl
		WHERE agentId = @settlingAgent		

	END

	ELSE IF @flag = 'v'						--Validation
	BEGIN
		IF @nCust='N'
		BEGIN
			IF ISNULL(@senderId, 0) = 0
			BEGIN
				EXEC proc_errorHandler 1, 'Please choose Sender', NULL
				RETURN
			END
		END
		IF @sfName IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Sender First Name 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, 'New Receiver First Name 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 

		--IF @occupation IS NULL
		--BEGIN
		--	EXEC proc_errorHandler 1, 'Occupation is missing', 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
			SELECT @pAgent = @pBank, @pAgentName = @pBankName, @pBranch = @pBankBranch, @pBranchName = @pBankBranchName
				
			IF @pBank IS NULL
			BEGIN
				EXEC proc_errorHandler 1, 'Please select bank', 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
		SELECT @receivingCustType = customerType FROM dbo.customerMaster WITH(NOLOCK) WHERE customerId = @benId
		
		--Credit Limit Section--------------------------------------------------------------------------------------------------

		--SELECT @limitBal = [dbo].FNAGetLimitBalIRH(@settlingAgent)
		--SELECT @baseCurrency = currency FROM creditLimitInt WITH(NOLOCK) WHERE agentId = @settlingAgent AND ISNULL(isActive, 'N') = 'Y' AND ISNULL(isDeleted, 'N') = 'N'
		--SELECT @limitBal = dbo.FNAGetExchangeAmount(@collCurr, @sCountryId, @settlingAgent, @limit)

		--IF @tAmt > @limitBal
		--BEGIN
		--	EXEC [proc_errorHandler] 1, 'Transfer amount exceeds Limit. Please, Check your available limit.', @controlNo
		--	RETURN		
		--END

		--IF EXISTS(SELECT 'X' FROM creditLimitInt WITH(NOLOCK)
		--		WHERE agentId = @settlingAgent
		--			 AND expiryDate < GETDATE() 
		--			 AND ISNULL(isActive, 'N') = 'Y' 
		--			 AND ISNULL(isDeleted, 'N') = 'N')
		--BEGIN
		--	EXEC [proc_errorHandler] 1, 'Your credit limit has been expired. Please contact HO', @controlNo
		--	RETURN
		--END
		--IF((SELECT ISNULL(expiryDate, '1900-01-01') FROM creditLimitInt WITH(NOLOCK) 
		--			WHERE agentId = @settlingAgent 
		--			AND ISNULL(isActive, 'N') = 'Y'
		--			 AND ISNULL(isDeleted, 'N') = 'N') 
		--			 <(SELECT TOP 1 ISNULL(topUpExpiryDate, '1900-01-01') FROM balanceTopUp WITH(NOLOCK)
		--			 WHERE agentId = @settlingAgent ORDER BY btId DESC)) 
		--BEGIN
		--	IF NOT EXISTS(SELECT TOP 1 'X' FROM balanceTopUp WITH(NOLOCK) WHERE agentId = @settlingAgent 
		--			AND topUpExpiryDate >= ISNULL(GETDATE(), '1900-01-01') 
		--			ORDER BY btId DESC)
		--	BEGIN
		--		EXEC [proc_errorHandler] 1, 'Your Top-up has been expired. Please contact HO', @controlNo
		--		RETURN
		--	END
		--END
	
		--END of Credit Limit Section
		
		--4. Exchange Rate Checking
		--SET @pAgent=1006
		--SET @pSuperAgent=1005
		--SET @pBranch=1007
		SELECT @exRate=customerRate
				,@sCurrCostRate = sCurrCostRate
				,@sCurrHoMargin = sCurrHoMargin
				,@sCurrAgentMargin = sCurrAgentMargin
				,@pCurrCostRate = pCurrCostRate
				,@pCurrHoMargin = pCurrHoMargin
				,@pCurrAgentMargin = pCurrAgentMargin
		 FROM dbo.FNAGetExRate(@sCountryId,@sAgent,@sBranch,@collCurr,@pCountryId,@pAgent,@pCurr,@deliveryMethodId)
		 

		IF @exRate IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Exchange Rate not defined', NULL
			RETURN
		END
		--End of Exchange Rate Checking
		
		--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
		IF @schemeCode IS NOT NULL
		BEGIN
			DECLARE @scValue MONEY, @scAction CHAR(2), @scOffer MONEY, @exRateOffer FLOAT, @scDiscount MONEY
			
		END
		SET @iCustomerRate = @exRate + ISNULL(@schemePremium, 0)
		SET @iTAmt = @cAmt - @iServiceCharge

		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)
		SET @place = ISNULL(@place, 0)
		
		SET @iPAmt = @iTAmt * @iCustomerRate

		SET @iPAmt = ROUND(@iPAmt, @currDecimal, 1)
		--IF @place IS NOT NULL
		--	SET @iPAmt = ROUND(@iPAmt, -@place, 1)
	
		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

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

		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
				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
			SELECT @pAgent = @pBank, @pAgentName = @pBankName, @pBranch = @pBankBranch, @pBranchName = @pBankBranchName
		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

		--End of Credit Limit Section-------------------------------------------------------------------------------------------------------------

		--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
		
		--Earthquake relief fund
		DECLARE @scDisc MONEY
		
		IF @iServiceCharge <> @serviceCharge
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Amount detail not match', NULL
			RETURN
		END
		--End-------------------------------------------------------------------------------------------------------------------------------------
		
		--4. Get Exchange Rate Details------------------------------------------------------------------------------------------------------------------
		SELECT 
			 @customerRate			= customerRate
			,@sCurrCostRate			= sCurrCostRate
			,@sCurrHoMargin			= sCurrHoMargin
			,@sCurrAgentMargin		= sCurrAgentMargin
			,@pCurrCostRate			= pCurrCostRate
			,@pCurrHoMargin			= pCurrHoMargin
			,@pCurrAgentMargin		= pCurrAgentMargin
			,@agentCrossSettRate	= agentCrossSettRate
			,@treasuryTolerance		= treasuryTolerance
			,@customerPremium		= customerPremium
			,@sharingValue			= sharingValue
			,@sharingType			= sharingType
		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
		
		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)
		
		SET @iPAmt = @iTAmt * @iCustomerRate

		SET @iPAmt = ROUND(@iPAmt, @currDecimal, 1)
		--IF @place IS NOT NULL
		--	SET @iPAmt = ROUND(@iPAmt, -@place, 1)
		
		
		IF @iPAmt <> @pAmt
		BEGIN
			EXEC proc_errorHandler 1, 'Amount detail not match. Please re-calculate the amount again.', NULL
			RETURN
		END
		
		--6. Commission Calculation Start
		
		DECLARE @agentFxGain MONEY
		SET @agentFxGain = ((@tAmt) *(@agentCrossSettRate - (@customerRate + ISNULL(@schemePremium, 0))))/@agentCrossSettRate
		
		--Commission Calculation End
		
		--**********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
		
		IF @deliveryMethod = 'BANK DEPOSIT'  
		BEGIN 
			IF NOT EXISTS(SELECT 'A' FROM agentMaster(nolock) where agentId = @pBank and agenttype =2903 and IsIntl = 1)
			begin
				EXEC proc_errorHandler 1, 'Invalid bank selected', NULL
				return
			end
			select @pAgent = bankpartnerId from AgentBankMapping(nolock) where bankId = @pBank
			SELECT @pSuperAgent = sSuperAgent,@pSuperAgentName = sSuperAgentName,
				   @pAgent = sAgent,@pAgentName = sAgentName ,@pBranch = sBranch,@pBranchName = sBranchName
			FROM dbo.FNAGetBranchFullDetails(@pAgent)
		END 
		--##Get Voucher Details into temp table END##--
		IF @pCountry ='VIETNAM' 
		BEGIN
			SELECT @pSuperAgent = sSuperAgent,@pSuperAgentName = sSuperAgentName,
				   @pAgent = sAgent,@pAgentName = sAgentName ,@pBranch = sBranch,@pBranchName = sBranchName
			FROM dbo.FNAGetBranchFullDetails(2090)

			SELECT
					@pAgentComm	= (SELECT amount FROM dbo.FNAGetPayComm
					(@sAgent,(SELECT countryId FROM countryMaster WITH(NOLOCK) WHERE countryName = @sCountry), 
					NULL, null, @pCountryId, null, @pAgent, 'USD'
					,@deliveryMethodId, @cAmt, @pAmt, @serviceCharge, NULL, NULL))
					,@pAgentCommCurrency	= 'KRW'

		END

		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
			)				
						
			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
				
			SET @id = SCOPE_IDENTITY()	
			
			INSERT INTO bankCollectionVoucherDetail( tempTranId ,voucherNo ,voucherDate ,voucherAmt ,bankId)
			SELECT @id, voucherNo, voucherDate, voucherAmount, bankId FROM #tempVoucherData
			
			-- UPDATE BONUS
			--UPDATE customerMaster SET lastTranId = @id, bonusPointPending = ISNULL(bonusPointPending,0) + ISNULL(@cAmt,0) WHERE customerId = @senderId
			
			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 101, 'Transaction under compliance', @controlNo
			RETURN
		END
		EXEC [proc_errorHandler] 100, 'Transaction has been sent successfully and is waiting for approval', @controlNo	
		
	END

	ELSE IF @flag = 'exRate'			--Get Exchange Rate, Service Charge, Scheme/Offer and amount details
	BEGIN
			DECLARE @rowId INT
			SELECT @scValue = 0, @scOffer = 0, @exRateOffer = 0, @scDiscount = 0
			
			IF @senderId IS NOT NULL
				SELECT @senderId = customerId, @sIdNo = idNumber FROM customerMaster WITH(NOLOCK) WHERE idNumber = @senderId
		
			--2. Find Decimal Mask for payout amount rounding
			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
            
			SELECT @place = place, @currDecimal = currDecimal
			FROM currencyPayoutRound WITH(NOLOCK) WHERE ISNULL(isDeleted, 'N') = 'N' 
			AND currency = @pCurr AND ISNULL(tranType,@deliveryMethod) = @deliveryMethod
			
			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 @exRate = dbo.FNAGetCustomerRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, @pAgent, @pCurr, @deliveryMethod)
			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, @currDecimal, 1)
				
				--IF @place IS NOT NULL
				--	SET @pAmt = ROUND(@pAmt, -@place, 1)
			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		
				
		--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 = @exRateOffer, scOffer = @scDiscount, scAction = @scAction, scValue = @scValue, scDiscount = @scDiscount
	END
	
	ELSE IF @flag = 'customerRate'		--Get Customer Rate
	BEGIN
		SELECT TOP 1 @pCurr = CM.currencyCode 
		FROM currencyMaster CM WITH (NOLOCK)
		INNER JOIN countryCurrency CC WITH (NOLOCK) ON CM.currencyId = CC.currencyId
		WHERE CC.countryId = @pCountryId 
		AND ISNULL(CC.isDeleted, 'N') = 'N'
	    
		IF @pCurr IS NULL
		BEGIN
			 SELECT '1' ErrCode, 'Not defined' Msg
			 RETURN
		END
		
		SELECT @exRate = dbo.FNAGetCustomerRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, @pAgent, @pCurr, @deliveryMethod)
		IF @exRate IS NULL
		BEGIN
			SELECT '1' ErrCode, 'Not defined' Msg
			RETURN
		END

		declare @maxLimit as money,@lCurr as varchar(10)

		SELECT @maxLimit = maxLimitAmt,@lCurr = currency FROM sendTranLimit with(nolock)
		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'

		SELECT @maxLimit = maxLimitAmt,@lCurr = currency FROM sendTranLimit with(nolock)
		WHERE agentId is null
		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'



		SELECT '0' ErrCode, @exRate exRate, @pCurr pCurr,@maxLimit limit,@lCurr limitCurr
	END
	
	ELSE IF @flag = 'CustdayLimit'		-- CUSTOMER PER DAY LIMIT
	BEGIN
		DECLARE @txnSum MONEY,@txnCount INT, @tranId INT, @date VARCHAR(20) = CONVERT(varchar(20), GETDATE(),111)
	
		SELECT 
			@limitBal= D.amount FROM csMaster M WITH (NOLOCK)
		INNER JOIN csDetail D WITH(NOLOCK) ON M.csMasterId=D.csDetailId
		WHERE sCountry=@sCountryId
		AND ISNULL(M.isActive,'Y')='Y' AND ISNULL(D.isActive,'Y')='Y' 
		
		
		SELECT 
			 @txnSum= ISNULL(SUM(R.cAmt),0),@txnCount=COUNT('x')  
		FROM remitTran R WITH (NOLOCK), tranSenders  S WITH (NOLOCK)
		WHERE R.id = S.tranId and S.customerId = @senderId
		  AND R.approvedDate between @date and @date +' 23:59:59'
			
			
		SELECT ISNULL(@limitBal,0) countryBalLimit,ISNULL(@txnSum,0) custDayLimit,
			 ISNULL(@txnCount,0) custDayTxn,CAST(GETDATE() as DATE) [txnDate]
			
	END
	
	ELSE IF @flag = 'cti'				--All transaction information (sender, receiver, payout)
	BEGIN
		SELECT DISTINCT
			 c.customerId
			,c.membershipId
			,Name = c.firstName + ISNULL(' ' + c.middleName, '') + ISNULL(' ' + c.lastName1, '') + ISNULL(' ' + c.lastName2, '')
			,c.Country 
			,Address
			,[State]
			,Phone = COALESCE(mobile, homePhone, workPhone)
			,city
		FROM tranSenders c WITH(NOLOCK)	
		WHERE c.id = @senderId
		
		SELECT DISTINCT
			 c.customerId
			,c.membershipId
			,Name = c.firstName + ISNULL( ' ' + c.middleName, '') + ISNULL( ' ' + c.lastName1, '') + ISNULL( ' ' + c.lastName2, '')
			,Country 
			,Address
			,[State]
			,Phone = COALESCE(mobile, homePhone, workPhone)
			,city
		FROM tranreceivers c WITH(NOLOCK)	
		WHERE c.id = @benId
		
		IF @agentId > 0
		BEGIN
			SELECT
				DISTINCT
				 am.agentId
				,am.agentCode
				,name = am.agentName
				,address = am.agentAddress
				,city = agentCity
				,[State] = agentState
				,Phone = COALESCE(agentMobile1, agentMobile2, agentPhone1, agentPhone2)
				,Country = @pCountry
			FROM agentMaster am WITH(NOLOCK)
			LEFT JOIN agentCurrency ac WITH(NOLOCK) ON am.agentId = ac.agentId
			WHERE am.agentId = @agentId
		END
		ELSE
		BEGIN
			SELECT
				 agentId = NULL
				,agentCode = NULL
				,name = 'Any'
				,address = NULL
				,city = NULL
				,state = NULL
				,Phone = NULL
				,country = @pCountry
		END
	END
	
	ELSE IF @flag = 'controlNo'
	BEGIN
		SELECT @controlNoEncrypted = dbo.FNAEncryptString(@controlNo)
		SELECT
			  senderId = sen.customerId
			 ,benId = ben.customerId
			 ,pCountry = cm.countryId
			 ,deliveryMethod = stm.serviceTypeId
			 ,tAmt = trn.tAmt
			 ,cAmt = trn.cAmt
			 ,pAmt = trn.pAmt
			 ,customerRate = trn.customerRate
			 ,serviceCharge = trn.serviceCharge
			 ,trn.collCurr
			 ,trn.payoutCurr
			 ,agentId = pBranch
		FROM remitTran trn WITH(NOLOCK)
		INNER JOIN tranSenders sen WITH(NOLOCK) ON trn.id = sen.tranId
		INNER JOIN tranReceivers ben WITH(NOLOCK) ON trn.id = ben.tranId
		INNER JOIN countryMaster cm WITH(NOLOCK) ON trn.pCountry = cm.countryName
		INNER JOIN serviceTypeMaster stm WITH(NOLOCK) ON trn.paymentMethod = stm.typeTitle
		WHERE controlNo = @controlNoEncrypted
	END
	
	ELSE IF @flag = 'senderId'
	BEGIN
		SELECT TOP 1
			 senderId = sen.customerId
			,benId = ben.customerId
			,pCountry = cm.countryId
			,deliveryMethod = stm.serviceTypeId
			,tAmt = trn.tAmt
			,cAmt = trn.cAmt
			,pAmt = trn.pAmt
			,customerRate = trn.customerRate
			,serviceCharge = trn.serviceCharge
			,trn.collCurr
			,trn.payoutCurr
			,agentId = pBranch
		FROM remitTran trn WITH(NOLOCK)
		INNER JOIN tranSenders sen WITH(NOLOCK) ON trn.id = sen.tranId
		INNER JOIN tranReceivers ben WITH(NOLOCK) ON trn.id = ben.tranId
		INNER JOIN countryMaster cm WITH(NOLOCK) ON trn.pCountry = cm.countryName
		INNER JOIN serviceTypeMaster stm WITH(NOLOCK) ON trn.paymentMethod = stm.typeTitle
		WHERE sen.customerId = @senderId ORDER BY trn.id DESC
	END	
	ELSE IF @flag = 'chkSenderIdNo'
	BEGIN
		--IF EXISTS(SELECT 'X' FROM dbo.customerMaster WITH(NOLOCK) WHERE idNumber = @sIdNo AND ISNULL(isDeleted, 'N') = 'N')
		--BEGIN
		--	EXEC proc_errorHandler 1, 'Customer is already registered with this Id Number', NULL
		--	RETURN
		--END
		EXEC proc_errorHandler 0, 'Success', NULL
	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
