USE [FastMoneyPro_Remit]
GO

/****** Object:  StoredProcedure [dbo].[proc_sendIRH]    Script Date: 3/26/2024 10:22:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER 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 NVARCHAR(150) = NULL
	,@sAdd2 NVARCHAR(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 VARCHAR(30) = 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
	,@pTownId VARCHAR(100) = NULL
	,@isManualSc CHAR(1) = NULL
	,@manualSc MONEY = NULL
	,@sCustStreet NVARCHAR(100) = NULL
	,@sCustLocation INT = NULL
	,@sCustomerType INT = NULL
	,@sCustBusinessType INT = NULL
	,@sCustIdIssuedCountry INT = NULL
	,@sCustIdIssuedDate VARCHAR(25) = NULL
	,@receiverId INT = NULL
	,@payoutPartner INT = NULL
	,@customerDepositedBank INT = NULL
	,@introducer VARCHAR(100) = NULL
	,@isOnbehalf VARCHAR(1) = NULL
	,@payerId BIGINT = NULL
	,@payerBranchId BIGINT = NULL
	,@IsFromTabPage CHAR(1) = NULL
	,@customerPassword VARCHAR(20) = NULL
	,@referralCode VARCHAR(20) = NULL
	,@isAdditionalCDDI CHAR(1) = NULL
	,@additionalCDDIXml NVARCHAR(MAX) = NULL
	,@calcBy VARCHAR(10) = NULL
	,@promotionCode INT = NULL
	,@promotionAmount VARCHAR(150) = NULL
	,@relationOther VARCHAR(150) = NULL
	,@purposeOther VARCHAR(150) = NULL
	,@txnRequestFromAgent VARCHAR(10) = NULL
	,@txnRequestRowId BIGINT = NULL
	,@goodsOrigin VARCHAR(200) = NULL
	,@goodsType VARCHAR(200) = NULL
	,@portOfShipment VARCHAR(200) = NULL
	,@visaStatus INT = NULL
	,@trackBy VARCHAR(50) = NULL
	,@partnerId INT = NULL
	,@exRateId VARCHAR(30) = NULL
	,@tpExRate FLOAT = NULL
	,@nameAsPerBank VARCHAR(150) = NULL
	,@calculatedOriginalSc MONEY = NULL
	,@paymentOption VARCHAR(100) = NULL
	,@sitereference VARCHAR(200) = NULL
	,@rewardAmt VARCHAR(200) = NULL
	,@isPromoCode CHAR(1) = NULL
	,@customerId BIGINT = NULL
	,@promoRowId INT = NULL
	,@promoCode VARCHAR(100) = NULL
	)
AS
SET NOCOUNT ON;
SET XACT_ABORT ON;

-----------------------------------------
--July 12 --> added flags (questionnaire) for Non Permit Visa
--July 14 --> JME-557 - Add compliance Log for   Non Permit Visa
--> replaced hard code with VW_VISA_STATUS_QUESTIONNAIRE
--July 29 --> set pBankName from apibanklist
--Aug 05 --JME-567 ->add col 'receiverNameAlt' changes to show BENEFICIARY NAME AS PER BANK
--SEP 09 --#127 Donga Commission Update for non 24*7
--SEP 21 -->#134 -> Allow edit option of address in Town Area
--Sep 22 -> #109 ->Change the logic to choose highest Rate in case of Nepal
--Sep 23 ->#178 -> Show only Roman in Remittance Statement
--#334 : OFAC screening changes.
--#9776  - Service Charge calcaulation for Validation , @flag = 'v'
-- # 19238 change in @flag = 'exRate' to return exrate on the basis of payment option
-- removed password validation for txn
--------------------------------------------
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)
			,@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)
			,@exRateCalByPartner BIT
			,@tranCount INT
			,@schemeCount INT
			,@isEligible CHAR(1) = 'N'
			,@schemeCodeId INT
			,@isFreeSc CHAR(1) = 'N'
			,@calcOriginalSc MONEY = 0 -- added for teller quota 


			--SET @manualSc='0'
			--SET @isManualSc='N';

		IF @pBankBranch = 'NA'
			SET @pBankBranch = NULL

		IF ISNULL(@relationship, '') <> 'other (please specify)'
			SET @relationOther = NULL

		IF ISNULL(@purpose, '') <> 'other (please specify)'
			SET @purposeOther = NULL

		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
			)

		IF ISNULL(@sBranch, 0) = 0
			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

		SELECT @sfName = LTRIM(RTRIM(@sfName))
			,@smName = LTRIM(RTRIM(@smName))
			,@slName = LTRIM(RTRIM(@slName))
			,@slName2 = LTRIM(RTRIM(@slName2))
			,@rfName = LTRIM(RTRIM(@rfName))
			,@rmName = LTRIM(RTRIM(@rmName))
			,@rlName = LTRIM(RTRIM(@rlName))
			,@rlName2 = LTRIM(RTRIM(@rlName2))

		IF @salary = 'undefined'
			SET @salary = NULL

		IF @salaryRange = 'undefined'
			SET @salaryRange = NULL

		IF @pBankBranchName IN (
				'Select'
				,'undefined'
				)
			SET @pBankBranchName = 'Any Branch'

		IF @rIdType IN (
				'Select..'
				,'Select'
				)
			SET @rIdType = NULL

		--CHECK IF SC IS ALLOWED TO EDIT BY USER OR  NOT    
		DECLARE @HAS_RIGHT_EDIT_SC CHAR(1) = 'N'

		SELECT @HAS_RIGHT_EDIT_SC = dbo.FNAHasRight(@user, '40101440')

		SET @raccountNo = UPPER(REPLACE(@raccountNo, ' ', ''))

		IF ISNULL(@isManualSc, 'N') = 'Y'
			AND @HAS_RIGHT_EDIT_SC = 'N'
		BEGIN
			SELECT '1' ErrCode
				,'Invalid attempt to calculate SC manually!' Msg
				,NULL id

			RETURN
		END

		IF @flag = 'v-referral'
		BEGIN
			DECLARE @IS_ACTIVE BIT

			SELECT @IS_ACTIVE = IS_ACTIVE
			FROM REFERRAL_AGENT_WISE(NOLOCK)
			WHERE REFERRAL_CODE = @introducer

			IF @IS_ACTIVE IS NULL
			BEGIN
				SELECT '1' ErrCode
					,'Invalid referral code!' Msg
					,NULL id

				RETURN
			END

			IF @IS_ACTIVE = 0
			BEGIN
				SELECT '1' ErrCode
					,'Disabled referral passed!' Msg
					,NULL id

				RETURN
			END

			SELECT '0' ErrCode
				,'Success!' Msg
				,NULL id

			RETURN
		END

		IF @flag IN (
				'V'
				,'I'
				)
		BEGIN
			IF ISNULL(@senderId, 0) = 0
				OR (ISNULL(@senderId, '') = '')
			BEGIN
				SELECT '1' ErrCode
					,'Invalid sender selected, please refresh page and try sending again!' Msg
					,NULL id

				RETURN
			END

			IF NOT EXISTS (
					SELECT 'X'
					FROM countryIdType CID WITH (NOLOCK)
					INNER JOIN staticDataValue SV WITH (NOLOCK) ON CID.IdTypeId = SV.valueId
					INNER JOIN (
						SELECT IDTYPE
						FROM CUSTOMERMASTER(NOLOCK)
						WHERE CUSTOMERID = @senderId
						) CM ON CM.IDTYPE = SV.VALUEID
					WHERE countryId = 233
						AND ISNULL(isDeleted, 'N') <> 'Y'
						AND ISNULL(SV.ISACTIVE, 'Y') = 'Y'
						AND (
							spFlag IS NULL
							OR ISNULL(spFlag, 0) = 5200
							)
					)
			BEGIN
				SELECT '1' ErrCode
					,'Customer ID type is not valid, please update ID details first!' Msg
					,NULL id

				RETURN
			END
			
			--CHECKING OF BRANCH/USER CASH HOLD LIMIT    
			IF EXISTS (
					SELECT *
					FROM AGENTMASTER
					WHERE AGENTID = @SAGENT
						AND ISINTL = 1
					)
				AND ISNULL(@INTRODUCER, '') <> ''
			BEGIN
				SELECT '1' ErrCode
					,'Agent''s and introducer can not be selected at same time!' Msg
					,NULL id

				RETURN
			END

			DECLARE @RULETYPE CHAR(1)
				,@LIMITERRORCODE INT
				,@BRANCH_ID_FOR_LIMIT VARCHAR(20)
				,@INTRODUCER_LIMIT VARCHAR(20)

			IF NOT EXISTS (
					SELECT *
					FROM APPLICATIONUSERS(NOLOCK)
					WHERE USERNAME = @USER
						AND AGENTID = @SAGENT
					)
				AND ISNULL(@INTRODUCER, '') = ''
				SET @INTRODUCER_LIMIT = @SAGENT
			ELSE IF ISNULL(@INTRODUCER, '') <> ''
				SET @INTRODUCER_LIMIT = @INTRODUCER

			EXEC PROC_CHECK_BRANCH_USER_CASH_HOLD_LIMIT @USER = @USER
				,@INTRODUCER = @INTRODUCER_LIMIT
				,@CAMT = @CAMT
				,@ERRORCODE = @LIMITERRORCODE OUT
				,@ERRORMSG = @msg OUT
				,@RULETYPE = @RULETYPE OUT
				
			--select @RULETYPE,@ERRORCODE    
			IF @LIMITERRORCODE <> 0
				AND @RULETYPE = 'B'
				AND @COLLMODE = 'CASH COLLECT'
			BEGIN
				SELECT '1' ErrCode
					,'Branch/User cash hold limit is exceeded, please contact head office!' Msg
					,NULL id

				RETURN
			END

			--CHECK IF PAYOUT PARTNER IS ACTIVE OR NOT AND CHECK STATUS    
			IF @payoutPartner IS NULL
			BEGIN
				SELECT '1' ErrCode
					,'Payout partner not defined yet for receiving country!' Msg
					,NULL id

				RETURN
			END

			IF NOT EXISTS (
					SELECT 1
					FROM TblPartnerwiseCountry(NOLOCK)
					WHERE AgentId = @payoutPartner
						AND IsActive = 1
					)
				AND @PCOUNTRY <> 'VIETNAM'
			BEGIN
				SELECT '1' ErrCode
					,'Payout partner is not active please retry by choosing country again!' Msg
					,NULL id

				RETURN
			END

			SELECT @exRateCalByPartner = ISNULL(exRateCalByPartner, 0)
			FROM TblPartnerwiseCountry(NOLOCK)
			WHERE CountryId = @pCountryId
				AND IsActive = 1
				AND ISNULL(PaymentMethod, @deliveryMethodId) = @deliveryMethodId

			--CHECKING CUSTOMER KYC STATUS    
			DECLARE @kycStatus INT

			SELECT @kycStatus = kycStatus
			FROM TBL_CUSTOMER_KYC(NOLOCK)
			WHERE CUSTOMERID = @senderId
				AND ISDELETED = 0
			--AND kycStatus=11044    
			ORDER BY KYC_DATE

			--IF ISNULL(@kycStatus, 0) <> 11044
			--BEGIN
			--	IF @kycStatus IS NOT NULL
			--		SELECT @MSG = 'KYC for selected customer is not completed, it is in status:' + detailTitle
			--		FROM staticDataValue(NOLOCK)
			--		WHERE valueId = @kycStatus
			--	ELSE
			--		SELECT @MSG = 'Please complete KYC status first'

			--	SELECT '1' ErrCode
			--		,@MSG Msg
			--		,NULL id

			--	RETURN
			--END

			--GET PAYOUT AGENT DETAILS    
			SELECT @PAGENT = AGENTID
			FROM AGENTMASTER(NOLOCK)
			WHERE PARENTID = @payoutPartner
				AND ISNULL(ISSETTLINGAGENT, 'N') = 'Y';

			SELECT @pSuperAgent = sSuperAgent
				,@pSuperAgentName = sSuperAgentName
				,@pAgent = sAgent
				,@pAgentName = sAgentName
				,@pBranch = sBranch
				,@pBranchName = sBranchName
			FROM dbo.FNAGetBranchFullDetails(@PAGENT)

			SELECT @sSuperAgent = sSuperAgent
				,@sSuperAgentName = sSuperAgentName
				,@sAgent = sAgent
				,@sAgentName = sAgentName
				,@sBranch = sBranch
				,@sBranchName = sBranchName
			FROM dbo.FNAGetBranchFullDetails(@sBranch)
		END

		SET @sAgentCommCurrency = 'JPY'

		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'
				AND ISNULL(CC.isDefault, 'N') = 'Y'

			-->> 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.csMasterId --csDetailId CHANGED BY ARJUN    
			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

		IF @flag = 'acBalByAgentId' --Get Available Account Balance    
		BEGIN
			SET @pCountryId = 233;

			--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'
				AND ISNULL(CC.isDefault, 'N') = 'Y'

			-->> 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.csMasterId --csDetailId CHANGED BY ARJUN    
			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 @limitAmt MONEY
				,@limitCurrency VARCHAR(3)
				,@cRateAgentAmt FLOAT
				,@userId INT
				,@user1 VARCHAR(50) = NULL
				,@holdType VARCHAR(10) = NULL

			IF EXISTS (
					SELECT 1
					FROM dbo.applicationUsers
					WHERE agentId = @sBranch
						AND userName = @user
					)
			BEGIN
				SELECT @user1 = @user
					,@sBranch = NULL
			END

			--EXEC proc_sendIRH @flag = 'acBalByAgentId', @user = 'anupam', @sBranch = '394393'    
			--EXEC proc_sendIRH @flag = 'acBalByAgentId', @user = 'anupam', @sBranch = '394392'    
			SELECT @limitAmt = availableLimit
				,@holdType = CASE 
					WHEN ruleType = 'H'
						THEN 'Hold'
					ELSE 'Block'
					END
			FROM DBO.FNAGetUserCashLimitDetails(@user1, @sBranch)

			--SELECT @limitAmt = ISNULL(dbo.proc_checkUserAvailableBalance(@settlingAgent), 0)    
			SELECT @limitCurrency = 'JPY' -- FROM creditLimitInt WITH(NOLOCK)     
				--WHERE agentId = @settlingAgent AND ISNULL(isDeleted, 'N') = 'N' AND ISNULL(isActive, 'N') = 'Y'    

			SELECT availableBal = @limitAmt
				,balCurrency = @collCurr
				,limExpiry = 'N/A'
				,sCountryLimit = ISNULL(@limitBal, 0)
				,sCurr = @collCurr
				,tellerBanalce = 0
				,txnPerDayCustomerLimit = dbo.FNAGetPerDayCustomerLimit(@settlingAgent)
				,holdType = @holdType
		END

		IF @flag = 'getReferralBal'
		BEGIN
			SELECT totalLimit
				,availableLimit
			FROM DBO.FNAGetBranchCashLimitDetails(@referralCode, 'R')
		END
		ELSE IF @flag = 'v' --Validation    
		BEGIN
			DECLARE @AVAILABLEBALANCE MONEY

			IF @nCust = 'N'
			BEGIN
				IF ISNULL(@senderId, 0) = 0
				BEGIN
					EXEC proc_errorHandler 1
						,'Please choose Sender'
						,NULL

					RETURN
				END

				SELECT @AVAILABLEBALANCE = DBO.FNAGetCustomerAvailableBalance(@senderId)

				IF (ISNULL(@AVAILABLEBALANCE, 0) < @CAMT)
					AND (@collMode = 'Bank Deposit')
				BEGIN
					EXEC proc_errorHandler 1
						,'Collect Amount can not be greater then Available Balance!'
						,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 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 = 'Bank Deposit'
			BEGIN
				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

			DECLARE @visaStatusText VARCHAR(200)

			SELECT @sendingCustType = customerType
				,@visaStatus = visaStatus
				,@visaStatusText = SV.detailTitle
			FROM dbo.customerMaster CM WITH (NOLOCK)
			LEFT JOIN STATICDATAVALUE SV(NOLOCK) ON SV.valueId = CM.visaStatus
			WHERE customerId = @senderId

			SELECT @receivingCustType = customerType
			FROM dbo.customerMaster WITH (NOLOCK)
			WHERE customerId = @benId

			--4. Exchange Rate Checking    
			--SET @pAgent=1006    
			--SET @pSuperAgent=1005    
			--SET @pBranch=1007    
			IF @pCountryId = 151
				AND @deliveryMethodId = 1
			BEGIN
				SELECT AgentId
				INTO #AgentListValidate
				FROM agentMaster(NOLOCK)
				WHERE extCode = 'NP ANYWHERE'

				SELECT @exRate = customerRate
					,@sCurrCostRate = sCurrCostRate
					,@sCurrHoMargin = sCurrHoMargin
					,@sCurrAgentMargin = sCurrAgentMargin
					,@pCurrCostRate = pCurrCostRate
					,@pCurrHoMargin = pCurrHoMargin
					,@pCurrAgentMargin = pCurrAgentMargin
				FROM (
					SELECT ROW_NUMBER() OVER (
							ORDER BY CUSTOMERRATE DESC
							) ROW_NUM
						,customerRate
						,sCurrCostRate
						,sCurrHoMargin
						,sCurrAgentMargin
						,pCurrCostRate
						,pCurrHoMargin
						,pCurrAgentMargin
						,agentCrossSettRate
						,treasuryTolerance
						,customerPremium
						,sharingValue
						,sharingType
					FROM #AgentListValidate A
					CROSS APPLY dbo.FNAGetExRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, AgentId, @pCurr, @deliveryMethodId)
					) X
				WHERE X.ROW_NUM = 1
			END
			ELSE
			BEGIN
				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)
			END

			IF @exRate IS NULL
			BEGIN
				EXEC proc_errorHandler 1
					,'Transaction cannot be proceed. Exchange Rate not defined'
					,NULL

				RETURN
			END

			-- reward amount

			--DECLARE @promoCodeValidation TABLE (
			--    IS_VALID VARCHAR(50),
			--    PROMOTIONAL_CODE VARCHAR(50),
			--    PROMOTIONAL_MSG VARCHAR(255),
			--   -- PROMOTION_TYPE INT,
			--    PROMOTION_VALUE INT
			--)

			--DECLARE @availableReward INT, @promoVal INT
			--SELECT @availableReward = CAST(dbo.[FNA_GET_AVAILABLE_BALANCE_POINTS](@senderId) AS INT)

			--IF ISNUMERIC(ISNULL(@rewardAmt,0)) = 1
			--BEGIN
			--	IF (ISNULL(@rewardAmt ,0)> 0)
			--	BEGIN		
			--		IF (@availableReward < ISNULL(@rewardAmt, 0))
			--		BEGIN
			--			SELECT '1' ErrCode
			--				,'You do not have sufficient Rewards!'
			--				,NULL id
			--			RETURN;
			--		END
			--	END
				
			--	IF(ISNULL(@rewardAmt, 0) > ISNULL(@availableReward,0))
			--	BEGIN
			--		SELECT '1' ErrCode
			--			,'Please enter the valid point. The amount cannot be more than available Reward Amount!' Msg
			--			,NULL id

			--		RETURN
			--	END
			--END
			--ELSE
			--BEGIN
			--print 'promo'
				
			--	SET @deliveryMethod = CASE WHEN @deliveryMethod = 'CASH PAYMENT' THEN '1'
			--								WHEN @deliveryMethod = 'BANK DEPOSIT' THEN '2'
			--								WHEN @deliveryMethod = 'MOBILE WALLET' THEN '3'
			--								ELSE NULL
			--						END
			--	INSERT INTO @promoCodeValidation (IS_VALID, PROMOTIONAL_CODE, PROMOTIONAL_MSG, PROMOTION_VALUE)

			--	EXEC proc_CheckPromoValidity @flag='chk-validity', @countryId=@pCountryId, @pmode= @deliveryMethod, @promoCode = @rewardAmt

			--	SELECT @promoVal = PROMOTION_VALUE FROM @promoCodeValidation WHERE IS_VALID = 'VALID'
			--	SET @rewardAmt = @promoVal
			--END


			--New code added, referral code add #arjun
			--EXEC PROC_Customer_LoyaltyV2 @flag = 'check-eligible-v2'
			--		,@isEligible = @isEligible OUT
			--		,@referralCode = @introducer
			--		,@tranCount = @trancount OUT
			--		,@schemeCount = @schemeCount OUT
			--		,@customerId = @senderId
			--		,@createdFrom = 'I'
			
			--End of Exchange Rate Checking    
			--5. Service Charge Checking    
			DECLARE @tAmtSC MONEY
			--IF EXISTS (
			--		SELECT TOP 1 1
			--		FROM REFERRAL_AGENT_WISE
			--		WHERE REFERRAL_TYPE_CODE IN (
			--				'RB'
			--				,'RC'
			--				)
			--			AND REFERRAL_CODE = @introducer
			--		)
			--BEGIN
			--	EXEC PROC_Customer_Loyalty @flag = 'check-eligible'
			--		,@isEligible = @isEligible OUT
			--END
			--EXEC proc_Customer_Loyalty @flag = 'get-tranCount'
			--	,@tranCount = @trancount OUT
			--	,@customerId = @senderId

			--SELECT TOP 1 @schemeCount = txnCount
			--FROM schemeSetup(NOLOCK)
			--ORDER BY createdDate DESC

			IF @calcBy = 'cAmt'
			BEGIN
				IF @isEligible = 'Y'
				BEGIN
						SET @iServiceCharge = 0
				END
				ELSE
				BEGIN
				IF ISNULL(@isManualSc, 'N') = 'N'
				BEGIN
					SELECT @iServiceCharge = ISNULL(amount, - 1)
					FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @cAmt, @collCurr)
				END
				ELSE
				BEGIN
					SET @iServiceCharge = ISNULL(@manualSc, 0)
					print @cAmt
					print @tAmt
					print @serviceCharge
					print @rewardAmt

					IF @cAmt <> @tAmt + @serviceCharge - ISNULL(@rewardAmt,0)
					BEGIN
						EXEC proc_errorHandler 1
							,'1Please click on Calculate or Click out side the Service Charge input Box, after editing Service Charge!'
							,NULL

						RETURN
					END
				END
			END
			END
			ELSE
			BEGIN
				--SET @tAmt = ROUND(@pAmt/(@exRate + @exRateOffer),0)    
				SET @tAmtSC = CEILING(@pAmt / (@exRate))

				IF @isEligible = 'Y'
				BEGIN
						SET @iServiceCharge = 0
				END
				ELSE
				BEGIN
				IF ISNULL(@isManualSc, 'N') = 'N'
				BEGIN
					SELECT @iServiceCharge = ISNULL(amount, - 1)
					FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @tAmtSC, @collCurr)
				END
				ELSE
				BEGIN
					SET @iServiceCharge = ISNULL(@manualSc, 0)

					IF @cAmt <> @tAmt + @iServiceCharge - ISNULL(@rewardAmt,0)
					BEGIN
						EXEC proc_errorHandler 1
							,'2Please click on Calculate or Click out side the Service Charge input Box, after editing Service Charge!'
							,NULL

						RETURN
						END
					END
				END
			END

			IF @iServiceCharge = - 1
				AND ISNULL(@isManualSc, 'N') = 'N'
			BEGIN
				EXEC proc_errorHandler 1
					,'Transaction cannot be proceed. Service Charge is not defined'
					,NULL

				RETURN
			END

			SET @iServiceCharge = ROUND(@iServiceCharge, 2)

			PRINT @isManualSc;
			IF (@iServiceCharge <> @serviceCharge)
				AND (ISNULL(@isManualSc, 'N') = 'N')
			BEGIN
				EXEC proc_errorHandler 1
					,'Transaction cannot be proceed. Amount detail not match. Please check service charge. Verify'
					,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)

			IF @pCurr = 'VND'
			BEGIN
				IF @calcBy = 'cAmt'
				BEGIN
					SET @iTAmt = @cAmt - @iServiceCharge
					SET @iPAmt = @iTAmt * @iCustomerRate
						--IF @place IS NOT NULL    
						-- SET @pAmt = ROUND(@pAmt, -@place, 1)    
				END
				ELSE
				BEGIN
					SET @iPAmt = @pAmt 
				END
			END
			ELSE
			BEGIN
			PRINT '@iServiceCharge'			
			PRINT @iServiceCharge;

				SET @iTAmt = @cAmt - @iServiceCharge + ISNULL( @rewardAmt,0)

				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)
				PRINT '@iTAmt'			
			PRINT @iTAmt;

				SET @iPAmt = @iTAmt * @iCustomerRate
					--SET @iPAmt = ROUND(@iPAmt, @currDecimal, 1)    
					--IF @place IS NOT NULL    
					-- SET @iPAmt = ROUND(@iPAmt, -@place, 1)    
			END

			IF @pAmt - @iPAmt <= 1
				SET @iPAmt = @pAmt

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

			--	RETURN
			--END

			--End of service charge Checking    
			--send agent commission if it is external agent    
			DECLARE @sSettlementRate FLOAT
				,@pSettlementRate FLOAT

			SET @sSettlementRate = @sCurrCostRate + @sCurrHoMargin
			SET @pSettlementRate = @pCurrCostRate - @pCurrHoMargin

			--START OFAC Checking     
			DECLARE @receiverName VARCHAR(200)
				,@checkNameBy VARCHAR(10)
				,@matchBy CHAR(1)

			SELECT @checkNameBy = TRACK_BY
			FROM OFACSETTING(NOLOCK)

			IF @checkNameBy IS NULL
				SET @checkNameBy = 'OFAC'

			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)
				,@matchPercentage INT

			SELECT @matchPercentage = MATCH_PERCENTAGE
			FROM OFACSETTING

			IF @checkNameBy = 'OFAC'
			BEGIN
				EXEC proc_ofacTracker @flag = 't'
					,@name = @senderName
					,@Result = @ofacRes OUTPUT

				IF @senderName = @receiverName
				BEGIN
					SET @receiverOfacRes = @ofacRes
				END
				ELSE
				BEGIN
					EXEC proc_ofacTracker @flag = 't'
						,@name = @receiverName
						,@Result = @receiverOfacRes OUTPUT
				END
			END
			ELSE
			BEGIN
				SELECT @ofacRes = Dowjones.[dbo].[DJ_GET_SUSPICIOUS_NAME_MATCH_IDS_V2](@senderName)

				IF @senderName = @receiverName
				BEGIN
					SET @receiverOfacRes = @ofacRes
				END
				ELSE
				BEGIN
					SELECT @receiverOfacRes = Dowjones.[dbo].[DJ_GET_SUSPICIOUS_NAME_MATCH_IDS_V2](@receiverName)
				END
			END

			DECLARE @result VARCHAR(MAX)

			IF ISNULL(@ofacRes, '') <> ''
			BEGIN
				SET @matchBy = 'S'
				SET @ofacReason = 'Matched by sender name'
			END

			IF ISNULL(@receiverOfacRes, '') <> ''
			BEGIN
				SET @matchBy = 'R'

				IF @senderName <> @receiverName
					SET @ofacRes = ISNULL(@ofacRes + ',' + @receiverOfacRes, '' + @receiverOfacRes)
				SET @ofacReason = 'Matched by receiver name'
			END

			IF ISNULL(@ofacRes, '') <> ''
				AND ISNULL(@receiverOfacRes, '') <> ''
			BEGIN
				SET @matchBy = 'B'
				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 Receiver if not registered#---------------    
			DECLARE @rBankId INT = ISNULL(@pBank, @pAgent)
			DECLARE @rBankBranchId INT = ISNULL(@pBankBranch, '')

			EXEC PROC_CHECK_RECEIVER_REGISTRATION @flag = 'i'
				,@user = @user
				,@rfName = @rfName
				,@rmName = @rmName
				,@rlName = @rlName
				,@receiverIdNo = @rIdNo
				,@receiverIdType = @rIdType
				,@receiverCountry = @pCountry
				,@receiverAdd = @rAdd1
				,@receiverCity = @rcity
				,@receiverMobile = @rMobile
				,@receiverPhone = @rTel
				,@receiverEmail = @rEmail
				,@receiverId = @receiverId OUT
				,@customerId = @senderId
				,@paymentMethodId = @deliveryMethodId
				,@rBankId = @rBankId
				,@rBankBranchId = @rBankBranchId
				,@rAccountNo = @raccountNo
				,@purpose = @purpose
				,@relationship = @relationship
				,@loginBranchId = @sBranch
				,@relationOther = @relationOther
				,@purposeOther = @purposeOther
				,@goodsType = @goodsType
				,@goodsOrigin = @goodsOrigin
				,@portOfShipment = @portOfShipment

			--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 @sCountry = 'Japan'

			--checking for visa status questionnaire
			DECLARE @isVisaStatusQuestionnaire CHAR(1) = 'N'

			IF EXISTS (
					SELECT *
					FROM VW_VISA_STATUS_QUESTIONNAIRE
					WHERE VISA_ID = @visaStatus
					)
			BEGIN
				SET @isVisaStatusQuestionnaire = 'Y'
			END

			IF ISNULL(@isAdditionalCDDI, 'N') = 'N'
			BEGIN
				CREATE TABLE #TBL_COMPLIANCE_RESULT (
					ERROR_CODE INT
					,MSG VARCHAR(500)
					,RULE_ID INT
					,SHORT_MSG VARCHAR(100)
					,[TYPE] VARCHAR(10)
					,IS_D0C_REQUIRED BIT
					)

				INSERT INTO #TBL_COMPLIANCE_RESULT (
					ERROR_CODE
					,MSG
					,RULE_ID
					,SHORT_MSG
					,[TYPE]
					,IS_D0C_REQUIRED
					)
				EXEC [PROC_COMPLIANCE_CHECKING_NEW] @flag = 'core'
					,@user = @user
					,@sIdType = @sIdType
					,@sIdNo = @sIdNo
					,@receiverName = @receiverName
					,@amount = @tAmt
					,@customerId = @senderId
					,@pCountryId = @pCountryId
					,@deliveryMethod = @deliveryMethodId
					,@professionId = @occupation
					,@receiverMobile = @rMobile
					,@accountNo = @raccountNo
					,@receiverId = @receiverId
					,@sNaCountryId = @sNaCountryId
					,@visaStatus = @visaStatus

				IF EXISTS (
						SELECT *
						FROM #TBL_COMPLIANCE_RESULT
						WHERE ERROR_CODE <> 0
						)
				BEGIN
					--IF(@complienceErrorCode = 1)    
					--BEGIN    
					-- SELECT 101 errorCode,@shortMsg msg, @complienceErrorCode id, @complienceMessage compApproveRemark,'compliance' vtype    
					--END     
					IF EXISTS (
							SELECT *
							FROM #TBL_COMPLIANCE_RESULT
							WHERE ERROR_CODE IN (
									2
									,3
									)
							)
					BEGIN
						DELETE
						FROM remitTranComplianceTemp
						WHERE agentRefId = @agentRefId

						INSERT remitTranComplianceTemp (
							csDetailTranId
							,matchTranId
							,agentRefId
							)
						SELECT TOP 1 RULE_ID
							,NULL
							,@agentRefId
						FROM #TBL_COMPLIANCE_RESULT
						WHERE ERROR_CODE IN (
								2
								,3
								)
						ORDER BY ISNULL(IS_D0C_REQUIRED, 0) DESC
							--SELECT 102 errorCode,@shortMsg msg, @complienceErrorCode id, @complienceMessage compApproveRemark,'compliance' vtype    
					END

					--IF(@complienceErrorCode = 3)    
					--BEGIN    
					-- SELECT 103 errorCode,@shortMsg msg, @complienceErrorCode id, @complienceMessage compApproveRemark,'compliance' vtype    
					--END    
					DELETE
					FROM ComplianceLog
					WHERE agentRefId = @agentRefId

					INSERT INTO ComplianceLog (
						senderName
						,senderCountry
						,senderIdType
						,senderIdNumber
						,senderMobile
						,receiverName
						,receiverCountry
						,payOutAmt
						,complianceId
						,complianceReason
						,complainceDetailMessage
						,createdBy
						,createdDate
						,agentRefId
						,isDocumentRequired
						)
					SELECT @senderName
						,@sCountry
						,@sIdType
						,@sIdNo
						,@sMobile
						,@receiverName
						,@pCountry
						,@cAmt
						,RULE_ID
						,SHORT_MSG
						,MSG
						,@user
						,GETDATE()
						,@agentRefId
						,IS_D0C_REQUIRED
					FROM #TBL_COMPLIANCE_RESULT

					IF @isVisaStatusQuestionnaire = 'Y'
					BEGIN
						INSERT INTO ComplianceLog (
							senderName
							,senderCountry
							,senderIdType
							,senderIdNumber
							,senderMobile
							,receiverName
							,receiverCountry
							,payOutAmt
							,complianceId
							,complianceReason
							,complainceDetailMessage
							,createdBy
							,createdDate
							,agentRefId
							,isDocumentRequired
							)
						SELECT @senderName
							,@sCountry
							,@sIdType
							,@sIdNo
							,@sMobile
							,@receiverName
							,@pCountry
							,@cAmt
							,0
							,'Compliance Hold/Questionnaire due to Visa Status: ' + @visaStatusText
							,'Compliance Hold/Questionnaire due to Visa Status: ' + @visaStatusText
							,@user
							,GETDATE()
							,@agentRefId
							,0
					END
				END
						--END OFAC/Compliance data    
			END

			IF (@ofacRes <> '')
			BEGIN
				IF @checkNameBy = 'OFAC'
				BEGIN
					SET @result = @ofacRes + '|' + ISNULL(@ofacReason, '')

					SELECT errorCode = 100
						,msg = 'WARNING!!! This customer is listed on OFAC List'
						,id = @result
						,extra = @checkNameBy

					EXEC proc_sendPageLoadData @flag = 'ofac'
						,@user = @user
						,@blackListIds = @ofacRes
				END
				ELSE
				BEGIN
					SET @result = @ofacRes + '|' + ISNULL(@ofacReason, '')

					SELECT errorCode = 100
						,msg = 'WARNING!!! This customer is listed on DJ List'
						,id = @result
						,extra = @checkNameBy

					EXEC proc_sendPageLoadData @flag = 'ofac'
						,@user = @user
						,@blackListIds = @ofacRes
						,@TRACK_BY = 'DJ'
				END
			END

			SELECT *
			INTO #TEMP_COMPLIANCE
			FROM ComplianceLog CL(NOLOCK)
			WHERE agentRefId = @agentRefId
				AND CAST(CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)

			DECLARE @IS_TXN_IN_COMPLIANCE BIT = 0
				,@isDocumentRequired CHAR(1) = 'N'
				,@complianceChecked BIT = 0

			IF EXISTS (
					SELECT *
					FROM #TEMP_COMPLIANCE
					WHERE isDocumentRequired = 1
					)
			BEGIN
				SET @isDocumentRequired = 'Y'
			END

			IF EXISTS (
					SELECT 1
					FROM #TEMP_COMPLIANCE
					)
			BEGIN
				IF EXISTS (
						SELECT 1
						FROM #TEMP_COMPLIANCE CL
						INNER JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
						WHERE agentRefId = @agentRefId
							AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
							AND nextAction = 'B'
						)
				BEGIN
					SET @IS_TXN_IN_COMPLIANCE = 1

					SELECT errorCode = 101
						,MSG = 'COMPLIANCE BLOCK'
						,id = @isVisaStatusQuestionnaire
						,compApproveRemark = 'COMPLIANCE BLOCK'
						,vtype = 'compliance'
						,isDocumentRequired = 'N'

					SELECT id
						,csDetailRecId = ''
						,[S.N.] = ROW_NUMBER() OVER (
							ORDER BY id
							)
						,[Remarks] = complianceReason
						,[Action] = CASE 
							WHEN nextAction = 'H'
								THEN 'HOLD'
							WHEN nextAction = 'B'
								THEN 'Blocked'
							ELSE 'Questionnaire'
							END
					--,[Matched Tran ID] = ''    
					FROM #TEMP_COMPLIANCE CL
					LEFT JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
					WHERE agentRefId = @agentRefId
						AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
					--AND nextAction = 'B'    
					ORDER BY CD.period
				END

				IF @IS_TXN_IN_COMPLIANCE = 0
					AND EXISTS (
						SELECT 1
						FROM #TEMP_COMPLIANCE CL
						INNER JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
						WHERE agentRefId = @agentRefId
							AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
							AND nextAction = 'Q'
						)
				BEGIN
					SET @IS_TXN_IN_COMPLIANCE = 1

					SELECT errorCode = 103
						,MSG = 'COMPLIANCE HOLD'
						,id = @isVisaStatusQuestionnaire
						,compApproveRemark = 'COMPLIANCE HOLD'
						,vtype = 'compliance'
						,isDocumentRequired = @isDocumentRequired

					SELECT id
						,csDetailRecId = ''
						,[S.N.] = ROW_NUMBER() OVER (
							ORDER BY id
							)
						,[Remarks] = complianceReason
						,[Action] = CASE 
							WHEN nextAction = 'H'
								THEN 'HOLD'
							WHEN nextAction = 'B'
								THEN 'Blocked'
							ELSE 'Questionnaire'
							END
					--,[Matched Tran ID] = ''    
					FROM #TEMP_COMPLIANCE CL
					LEFT JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
					WHERE agentRefId = @agentRefId
						AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
					--AND nextAction = 'Q'    
					ORDER BY CD.period
				END

				IF @IS_TXN_IN_COMPLIANCE = 0
					AND EXISTS (
						SELECT 1
						FROM #TEMP_COMPLIANCE CL
						INNER JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
						WHERE agentRefId = @agentRefId
							AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
							AND nextAction = 'H'
						)
				BEGIN
					SELECT errorCode = 102
						,MSG = 'COMPLIANCE QUESTIONNAIRE'
						,id = @isVisaStatusQuestionnaire
						,compApproveRemark = 'COMPLIANCE QUESTIONAIRE'
						,vtype = 'compliance'
						,isDocumentRequired = @isDocumentRequired

					SELECT id
						,csDetailRecId = ''
						,[S.N.] = ROW_NUMBER() OVER (
							ORDER BY id
							)
						,[Remarks] = complianceReason
						,[Action] = CASE 
							WHEN nextAction = 'H'
								THEN 'HOLD'
							WHEN nextAction = 'B'
								THEN 'Blocked'
							ELSE 'Questionnaire'
							END
					--,[Matched Tran ID] = ''    
					FROM #TEMP_COMPLIANCE CL
					LEFT JOIN csDetail CD(NOLOCK) ON CD.csDetailId = CL.complianceId
					WHERE agentRefId = @agentRefId
						AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
					--AND nextAction = 'H'    
					ORDER BY CD.period
				END

				IF @IS_TXN_IN_COMPLIANCE = 0
					AND EXISTS (
						SELECT 1
						FROM #TEMP_COMPLIANCE CL
						WHERE agentRefId = @agentRefId
							AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
							AND complianceId = 0
						)
				BEGIN
					SELECT errorCode = 102
						,MSG = 'COMPLIANCE HOLD'
						,id = @isVisaStatusQuestionnaire
						,compApproveRemark = 'COMPLIANCE HOLD'
						,vtype = 'compliance'
						,isDocumentRequired = 'N'

					SELECT id
						,csDetailRecId = ''
						,[S.N.] = ROW_NUMBER() OVER (
							ORDER BY id
							)
						,[Remarks] = complianceReason
						,[Action] = 'Questionnaire'
					--,[Matched Tran ID] = ''    
					FROM ComplianceLog CL
					WHERE agentRefId = @agentRefId
						AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
				END
			END
			ELSE
			BEGIN
				IF @isVisaStatusQuestionnaire = 'Y'
				BEGIN
					INSERT remitTranComplianceTemp (
						csDetailTranId
						,matchTranId
						,agentRefId
						,reason
						)
					SELECT TOP 1 0
						,NULL
						,@agentRefId
						,'Questionnaire require due to Visa Status'

					SELECT errorCode = 102
						,MSG = 'COMPLIANCE HOLD'
						,id = @isVisaStatusQuestionnaire
						,compApproveRemark = 'COMPLIANCE HOLD'
						,vtype = 'compliance'
						,isDocumentRequired = 'N'

					INSERT INTO ComplianceLog (
						senderName
						,senderCountry
						,senderIdType
						,senderIdNumber
						,senderMobile
						,receiverName
						,receiverCountry
						,payOutAmt
						,complianceId
						,complianceReason
						,complainceDetailMessage
						,createdBy
						,createdDate
						,agentRefId
						,isDocumentRequired
						)
					SELECT @senderName
						,@sCountry
						,@sIdType
						,@sIdNo
						,@sMobile
						,@receiverName
						,@pCountry
						,@cAmt
						,0
						,'Compliance Hold/Questionnaire due to Visa Status: ' + @visaStatusText
						,'Compliance Hold/Questionnaire due to Visa Status: ' + @visaStatusText
						,@user
						,GETDATE()
						,@agentRefId
						,0

					SELECT id
						,csDetailRecId = ''
						,[S.N.] = ROW_NUMBER() OVER (
							ORDER BY id
							)
						,[Remarks] = complianceReason
						,[Action] = 'Questionnaire'
					--,[Matched Tran ID] = ''    
					FROM ComplianceLog CL
					WHERE agentRefId = @agentRefId
						AND CAST(cl.CREATEDDATE AS DATE) = CAST(GETDATE() AS DATE)
				END
			END

			SELECT 0 errorCode
				,'Validation successful' msg
				,@senderId id
				,@receiverId Extra

			--*****Check For Same Name*****    
			SELECT dbo.fnadecryptstring(controlno) controlNo
				,tranId = rt.id
				,senderName
				,sIdType = sen.idType
				,sIdNo = sen.idNumber
				,cAmt
				,pCountry
			FROM vwremitTran rt WITH (NOLOCK)
			INNER JOIN vwtranSenders 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 dbo.fnadecryptstring(controlno) controlNo
				,tranId = rt.id
				,senderName
				,sIdType = sen.idType
				,sIdNo = sen.idNumber
				,cAmt
				,pCountry
			FROM vwremitTran rt WITH (NOLOCK)
			INNER JOIN vwtranSenders 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 ISNULL(@IsFromTabPage, '0') != '1'
			--BEGIN
			--	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
			--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

			IF @customerPassword IS NOT NULL
			BEGIN
				IF NOT EXISTS (
						SELECT 1
						FROM dbo.customerMaster
						WHERE customerId = @senderId
							AND dbo.decryptDb(customerPassword) = @customerPassword
						)
				BEGIN
					EXEC proc_errorHandler 1
						,'Customer Password is invalid !'
						,NULL

					RETURN
				END
			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
					)
			SET @nCust = 'Y'

			DECLARE @rewardAmount DECIMAL
			SET @rewardAmount = CAST(@rewardAmt AS DECIMAL)

			IF @nCust = 'N'
				AND @senderId IS NULL
			BEGIN
				EXEC proc_errorHandler 1
					,'Mandatory Field(s) missing'
					,NULL

				RETURN
			END

			IF @nCust = 'N'
				AND @collMode = 'Bank Deposit'
			BEGIN
				SELECT @AVAILABLEBALANCE = DBO.FNAGetCustomerAvailableBalance(@senderId)

				IF (ISNULL(@AVAILABLEBALANCE, 0) < @CAMT)
				BEGIN
					EXEC proc_errorHandler 1
						,'Collect Amount can not be greater then Available Balance!'
						,NULL

					RETURN
				END
			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 = '779' + LEFT(CAST(ABS(CHECKSUM(NEWID())) AS VARCHAR(10)) + '0000000000', 9)

			IF EXISTS (
					SELECT 'X'
					FROM controlNoList WITH (NOLOCK)
					WHERE controlNo = @controlNo
					)
			BEGIN
				SET @controlNo = '779' + 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
			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    
			SELECT @settlingAgent = agentId
			FROM dbo.agentMaster(NOLOCK)
			WHERE agentId = @sBranch
				AND ISNULL(isSettlingAgent, 'N') = 'Y'

			IF @settlingAgent IS NULL
				SELECT @settlingAgent = agentId
				FROM dbo.agentMaster(NOLOCK)
				WHERE agentId = @sAgent
					AND ISNULL(isSettlingAgent, 'N') = 'Y'

			--Credit Limit Section    
			IF @collMode = 'Cash Collect'
			BEGIN
				DECLARE @sBranch1 INT

				IF EXISTS (
						SELECT 1
						FROM dbo.applicationUsers
						WHERE agentId = @sBranch
							AND userName = @user
						)
				BEGIN
					SELECT @user1 = @user
						,@sBranch1 = NULL
				END
				ELSE
				BEGIN
					SET @sBranch1 = @sBranch
				END

				SELECT @limitBal = availableLimit
					,@holdType = CASE 
						WHEN ruleType = 'H'
							THEN 'Hold'
						ELSE 'Block'
						END
				FROM DBO.FNAGetUserCashLimitDetails(@user1, @sBranch1)

				IF @tAmt > @limitBal
					AND @holdType = 'B'
				BEGIN
					EXEC [proc_errorHandler] 1
						,'Transfer amount exceeds Limit. Please, Check your available limit.'
						,@controlNo

					RETURN
				END
			END

			--End of Credit Limit Section-------------------------------------------------------------------------------------------------------------    
			--Get Service Charge----------------------------------------------------------------------------------------------------------------------    
			DECLARE @originalSC MONEY = 0

			SET @sCountryId = 233

			--New code added, referral code add #arjun
			--EXEC PROC_Customer_LoyaltyV2 @flag = 'check-eligible-v2'
			--		,@isEligible = @isEligible OUT
			--		,@referralCode = @introducer
			--		,@tranCount = @trancount OUT
			--		,@schemeCount = @schemeCount OUT
			--		,@customerId = @senderId
			--		,@createdFrom = 'I'

			-- loyalty free sc 
			--IF EXISTS (
			--		SELECT TOP 1 1
			--		FROM REFERRAL_AGENT_WISE
			--		WHERE REFERRAL_TYPE_CODE IN (
			--				'RB'
			--				,'RC'
			--				)
			--			AND REFERRAL_CODE = @introducer
			--		)
			--BEGIN
			--	EXEC PROC_Customer_Loyalty @flag = 'check-eligible'
			--		,@isEligible = @isEligible OUT
			--END

			--EXEC proc_Customer_Loyalty @flag = 'get-tranCount'
			--	,@tranCount = @trancount OUT
			--	,@customerId = @senderId

			--SELECT TOP 1 @schemeCount = txnCount
			--FROM schemeSetup(NOLOCK)
			--ORDER BY createdDate DESC

			PRINT @isManualSc
			PRINT 'isManualSc'
			IF @calcBy = 'cAmt'
			BEGIN
				IF @isEligible = 'Y'
				BEGIN
						SET @iServiceCharge = 0
				END
				ELSE
				BEGIN
					IF ISNULL(@isManualSc, 'N') = 'N'
					BEGIN
						SELECT @iServiceCharge = ISNULL(amount, - 1)
						FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @cAmt, @collCurr)

						SET @originalSC = @iServiceCharge
					END
					ELSE
					BEGIN
						SET @iServiceCharge = ISNULL(@manualSc, 0)

						SELECT @originalSC = ISNULL(amount, - 1)
						FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @cAmt, @collCurr)

						IF @cAmt <> @tAmt + @iServiceCharge - ISNULL(@rewardAmount,0)
						BEGIN
							EXEC proc_errorHandler 1
								,'3Please click on Calculate or Click out side the Service Charge input Box, after editing Service Charge!'
								,NULL

							RETURN
						END
					END
				END
			END
			ELSE
			BEGIN
				--SET @tAmt = ROUND(@pAmt/(@exRate + @exRateOffer),0)    
				--SET @tAmt = CEILING(@pAmt / (@exRate + ISNULL(@exRateOffer, 0))) + ISNULL(@rewardAmt,0)

				SET @tAmt = (@pAmt / (@exRate + ISNULL(@exRateOffer, 0))) + ISNULL(@rewardAmount,0)
				SET @tAmt =Cast(Round(@tAmt,2,1) as decimal(18,2));
				IF @isEligible = 'Y'
				BEGIN
						SET @iServiceCharge = 0
				END
				ELSE
				BEGIN
					IF ISNULL(@isManualSc, 'N') = 'N'
					BEGIN
						SELECT @iServiceCharge = ISNULL(amount, - 1)
						FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @tAmt, @collCurr)

						SET @originalSC = @iServiceCharge
					END
					ELSE
					BEGIN
						SET @iServiceCharge = ISNULL(@manualSc, 0)

						SELECT @originalSC = ISNULL(amount, - 1)
						FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethodId, @tAmtSC, @collCurr)

						PRINT '@cAmt'
						PRINT @cAmt
						PRINT '@tAmt'
						PRINT @tAmt
						PRINT '@iServiceCharge'

								PRINT @iServiceCharge
						IF @cAmt <> @tAmt + @iServiceCharge -ISNULL( @rewardAmount,0)
						BEGIN
							EXEC proc_errorHandler 1
								,'Please click on Calculate or Click out side the Service Charge input Box, after editing Service Charge!'
								,NULL

							RETURN
						END
					END
				END
			END

			--		PRINT @iServiceCharge
			IF @iServiceCharge = - 1
				AND ISNULL(@isManualSc, 'N') = 'N'
			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
				AND ISNULL(@isManualSc, 'N') = 'N'
			BEGIN
				EXEC proc_errorHandler 1
					,'Transaction cannot be proceed. Amount detail not match. Service Charge is different.'
					,NULL

				RETURN
			END

			PRINT 'osc'
			PRINT @originalSc
			PRINT @iServiceCharge

			IF (@iServiceCharge <> @calculatedOriginalSc)
				AND ISNULL(@isManualSc, 'Y') = 'Y'
			BEGIN
				PRINT 'condition matched'

				UPDATE APPLICATIONUSERS
				SET freeScCounter = isnull(freeScCounter, 0) + 1
				WHERE username = @user
			END

			--End-------------------------------------------------------------------------------------------------------------------------------------    
			--4. Get Exchange Rate Details------------------------------------------------------------------------------------------------------------------    
			IF @pCountryId = 151
				AND @deliveryMethodId = 1
			BEGIN
				SELECT AgentId
				INTO #AgentListSend
				FROM agentMaster(NOLOCK)
				WHERE extCode = 'NP ANYWHERE'

				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 (
					SELECT ROW_NUMBER() OVER (
							ORDER BY CUSTOMERRATE DESC
							) ROW_NUM
						,customerRate
						,sCurrCostRate
						,sCurrHoMargin
						,sCurrAgentMargin
						,pCurrCostRate
						,pCurrHoMargin
						,pCurrAgentMargin
						,agentCrossSettRate
						,treasuryTolerance
						,customerPremium
						,sharingValue
						,sharingType
					FROM #AgentListSend A
					CROSS APPLY dbo.FNAGetExRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, AgentId, @pCurr, @deliveryMethodId)
					) X
				WHERE X.ROW_NUM = 1
			END
			ELSE
			BEGIN
				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)
			END

			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)

			PRINT '@serviceCharge'
			PRINT @serviceCharge
			SET @iServiceCharge = @iServiceCharge - ISNULL(@iScDiscount, 0)

			PRINT '@@iServiceCharge'
			PRINT @iServiceCharge

				PRINT 'rewardAmt'
			PRINT @rewardAmount
			SET @tAmt = @cAmt - @serviceCharge + ISNULL(@rewardAmount,0)

			SET @iCustomerRate = @customerRate + ISNULL(@schemePremium, 0)

			IF @pCurr = 'VND'
			BEGIN
				IF @calcBy = 'cAmt'
				BEGIN
					SET @iTAmt = @cAmt - @iServiceCharge + ISNULL(@rewardAmount,0)
					SET @iPAmt = @iTAmt * @iCustomerRate
						--IF @place IS NOT NULL    
						-- SET @pAmt = ROUND(@pAmt, -@place, 1)    
				END
				ELSE
				BEGIN
					SET @iPAmt = @pAmt
				END
			END
			ELSE
			BEGIN
				SET @iTAmt = @cAmt - @iServiceCharge + ISNULL(@rewardAmount,0)

				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)    
			END

			SET @iPAmt = @iTAmt * @iCustomerRate
			SET @iPAmt = ROUND(@iPAmt, @currDecimal, 1)

			--IF @place IS NOT NULL    
			-- SET @iPAmt = ROUND(@iPAmt, -@place, 1)    
			IF @pAmt - @iPAmt <= 1
				SET @iPAmt = @pAmt

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

			--	RETURN
			--END

			SELECT @customerPremium= ISNULL(detaildesc,0) FROM 
			staticDataValue where typeID='8109' and detailTitle= @paymentOption;
			print 'wqq'

			--6. Commission Calculation Start    
			--**********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)

			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
					)
			BEGIN
				IF NOT EXISTS (
						SELECT 'Z'
						FROM tranSendersTEMP WITH (NOLOCK)
						WHERE customerId = @senderId
						)
					SET @isFirstTran = 'Y'
				ELSE
					SET @isFirstTran = 'N'
			END

			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'

			--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 API_BANK_LIST(NOLOCK)
						WHERE BANK_ID = @pBank
							AND IS_ACTIVE = 1
						)
				BEGIN
					EXEC proc_errorHandler 1
						,'Invalid bank selected'
						,NULL

					RETURN
				END
			END

			--##Get Voucher Details into temp table END##--     
			SELECT @pAgentCommCurrency = DBO.FNAGetPayCommCurrency(@sSuperAgent, @sAgent, @sBranch, @SCOUNTRYID, @pSuperAgent, @pBranch, @pCountryId)

			IF (
					LEN(ISNULL(@nameAsPerBank, '')) < 1
					AND @pCountryId = '203'
					AND @pAgent = '394133'
					AND @deliveryMethodId = '2'
					) -- DONGA Bank Deposit
			BEGIN
				SET @pAgentComm = (@pAmt * 0.17) / 100;
			END
			ELSE
			BEGIN
				SELECT @pAgentComm = amount
				FROM dbo.FNAGetPayComm(@sAgent, @sCountryId, NULL, NULL, @pCountryId, NULL, @pAgent, @pAgentCommCurrency, @deliveryMethodId, @cAmt, @pAmt, @serviceCharge, @tAmt, NULL)
			END

			SET @sSettlementRate = @sCurrCostRate + @sCurrHoMargin
			SET @pSettlementRate = @pCurrCostRate - @pCurrHoMargin

			--IF EXISTS (SELECT 'X' FROM agentMaster(nolock) WHERE agentId = @sAgent AND ISNULL(isSettlingAgent, 'N') = 'Y' AND ISNULL(isIntl, 0) = 1 AND isApiPartner = 0 AND ISNULL(ACTASBRANCH, 'N') = 'N')    
			--BEGIN    
			-- SELECT @sAgentComm = amount, @sAgentCommCurrency = commissionCurrency FROM dbo.FNAGetSendComm(    
			--          @sCountryId, @sSuperAgent, @sAgent, @sBranch,    
			--          @pCountryId, @pSuperAgent, @pAgent, @pBankBranch,    
			--          @collCurr, @deliveryMethodId, @cAmt, @pAmt, @serviceCharge, NULL, NULL,    
			--          @sSettlementRate, @pSettlementRate)    
			-- SELECT @sSuperAgentComm = 0, @sSuperAgentCommCurrency = @sAgentCommCurrency    
			-- IF (@sAgentComm IS NULL)    
			-- BEGIN    
			--  EXEC proc_errorHandler 1, 'Transaction cannot be proceed. Commission is not defined', NULL    
			--  RETURN    
			-- END    
			--END    
			--ELSE    
			--BEGIN    
			SELECT @sAgentComm = 0
				,@sSuperAgentComm = 0
				,@sSuperAgentCommCurrency = @sAgentCommCurrency

			--END    
			IF EXISTS (
					SELECT *
					FROM REFERRAL_AGENT_WISE(NOLOCK)
					WHERE REFERRAL_CODE = @introducer
						AND AGENT_ID <> 0
					)
			BEGIN
				SELECT @sAgent = AM.AGENTID
					,@sAgentName = AM.AGENTNAME
					,@sBranch = AM.AGENTID
					,@sBranchName = AM.AGENTNAME
				FROM REFERRAL_AGENT_WISE R(NOLOCK)
				INNER JOIN AGENTMASTER AM(NOLOCK) ON AM.AGENTID = R.AGENT_ID
				WHERE REFERRAL_CODE = @introducer
			END

			DECLARE @ADDRESS_TBL_ROW_ID BIGINT

			SELECT @sAdd2 = ISNULL(additionalAddress, '')
				,@visaStatus = visastatus
				,@ADDRESS_TBL_ROW_ID = district
				,@sCustStreet = ISNULL(street, rtrim(ltrim(replace(replace(cast(streetunicode AS VARCHAR), '?', ''), '-', ''))))
				,@sAdd1 = ISNULL(CITY, '') + ', ' + ISNULL(street, rtrim(ltrim(replace(replace(cast(streetunicode AS VARCHAR), '?', ''), '-', ''))))
			FROM customermaster(NOLOCK)
			WHERE customerid = @senderId

			--IF EXISTS(SELECT * FROM REFERRAL_AGENT_WISE (NOLOCK) WHERE REFERRAL_CODE = @introducer AND AGENT_ID <> 0)
			--BEGIN
			--	SELECT @SAGENT = AM.AGENTID, @SAGENTNAME = AM.AGENTNAME
			--	FROM AGENTMASTER AM(NOLOCK)
			--	INNER JOIN REFERRAL_AGENT_WISE R(NOLOCK) ON R.AGENT_ID = AM.AGENTID
			--	WHERE REFERRAL_CODE = @introducer
			--END
			BEGIN TRANSACTION

			--ANYWHERE
			--IF (
			--		@pCountry = 'Nepal'
			--		AND @deliveryMethodId = 1
			--		)
			--BEGIN
			--	SELECT @pSuperAgent = NULL
			--		,@pSuperAgentName = NULL
			--		,@PAGENT = NULL
			--		,@pAgentName = NULL
			--		,@pBranch = NULL
			--		,@pBranchName = NULL
			--END

			SELECT @pBankName = BANK_NAME
			FROM API_BANK_LIST (NOLOCK)
			WHERE BANK_ID = @pbank;

			SELECT @promoCode = PROMOTIONAL_CODE FROM TBL_PROMOTIONAL_CAMAPAIGN WHERE ROW_ID = @promoRowId

			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
				,pLocation
				--NEW    
				,isScMaunal
				,originalSC
				,externalBankCode
				,isOnBehalf
				,PayerId
				,PayerBranchId
				,sRouteId
				,company
				,receiverNameAlt
				,depositType
				,rewardPoints
				,rewardType
				,isBonusUpdated
				,schemeId
				)
			SELECT @controlNoEncrypted
				,@sCurrCostRate
				,@sCurrHoMargin
				,@sCurrSuperAgentMargin
				,@sCurrAgentMargin
				,@pCurrCostRate
				,@pCurrHoMargin
				,@pCurrSuperAgentMargin
				,@pCurrAgentMargin
				,@agentCrossSettRate
				,@exRate
				,@sAgentSettRate
				,@pDateCostRate
				,@treasuryTolerance
				,@customerPremium
				,ISNULL(@schemePremium, 0)
				,@sharingValue
				--,@sharingType    
				,@serviceCharge
				,ISNULL(@scDiscount, 0)
				,0
				,@sAgentComm
				,@sAgentCommCurrency
				,@sSuperAgentComm
				,@sSuperAgentCommCurrency
				,@pAgentComm
				,@pAgentCommCurrency
				,@pSuperAgentComm
				,@pSuperAgentCommCurrency
				,@introducer
				,@promotionType --@promotionCode REPLACED BY ARJUN    
				,@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 + ISNULL(' :' + @relationOther, '')
				,@purpose + ISNULL(' :' + @purposeOther, '')
				,@sourceOfFund
				,'Hold'
				,'UNPAID'
				,DBO.FNADateFormatTZ(GETDATE(), @user)
				,GETDATE()
				,@user
				,'I'
				,''
				,@senderName
				,@receiverName
				,@pLocation
				,@pSubLocation
				,@pTownId
				,CASE 
					WHEN ISNULL(@isManualSc, 'N') = 'Y'
						THEN 1
					ELSE 0
					END
				,@originalSC
				,@customerDepositedBank
				,CASE @isOnbehalf
					WHEN 'Y'
						THEN 1
					ELSE 0
					END
				,@payerId
				,@payerBranchId
				,CASE @IsFromTabPage
					WHEN '1'
						THEN '1'
					ELSE '0'
					END
				,@exRateId
				,@nameAsPerBank
				,@paymentOption
				,ISNULL(@rewardAmount, 0)
				,CASE 
					WHEN (ISNULL(@rewardAmount, 0) > 0 AND @isPromoCode = 'Y')
						THEN ISNULL(@promoCode,'PROMOCODE')
					WHEN (ISNULL(@rewardAmount, 0) > 0 AND @isPromoCode = 'N')
						THEN 'REDEEM'
					ELSE NULL
					END
				,'N'
				,@promoRowId

			SET @id = SCOPE_IDENTITY()

			INSERT INTO controlNoList (
				controlNo
				,createdby
				)
			SELECT @controlNo
				,'C'

			--UPDATE PROMOTIONAL CAMPAIGN    
			--IF ISNULL(@promotionCode, 0) <> 0
			--BEGIN
			--	EXEC PROC_PROMOTIONAL_CAMPAIGN_COUNTRY_WISE @ID = @id
			--		,@promotionCode = @promotionCode
			--		,@promotionAmount = @promotionAmount
			--END

			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
				--NEW    
				,STATE
				,district --USE FOR STREET    
				,customerType
				--,ttName--USE FOR BUSINESS TYPE    
				,idPlaceOfIssue
				,visaStatus
				,issuedDate
				)
			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
				,@ADDRESS_TBL_ROW_ID
				,@sDcInfo
				,@sIpAddress
				,@RBAScoreTxn
				,@sCustLocation
				,@sCustStreet
				,@sCustomerType
				--,@sCustBusinessType    
				,@sCustIdIssuedCountry
				,@visaStatus
				,@sCustIdIssuedDate

			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
				,accountNo
				,goodsType
				,goodsOrigin
				,portOfShipment
				)
			SELECT @id
				,@receiverId
				,''
				,@rfName
				,@rmName
				,@rlName
				,@rlName2
				,@receiverName
				,@pCountry
				,@rAdd1
				,@rPostCode
				,@rcity
				,@rEmail
				,@rTel
				,@rTel
				,@rMobile
				,@rNaCountry
				,@rdob
				,NULL
				,@rIdType
				,@rIdNo
				,NULL
				,NULL
				,@rIdValid
				,@rgender
				,@pLocationText
				,@pSubLocationText
				,@raccountNo
				,@goodsType
				,@goodsOrigin
				,@portOfShipment


			--New code added, referral code add #arjun
			EXEC PROC_Customer_LoyaltyV2 @flag = 'update-v2'
					,@customerId = @senderId
					,@createdFrom = 'I'
					,@tranId = @id
					,@createdBy = @user
					,@controlNo = @controlNo
					,@isManualSc = @isManualSc
					,@referralCode = @introducer
					,@serviceCharge = @iServiceCharge

			DECLARE @NewId uniqueidentifier
			 SET @NewId = NEWID()		

				INSERT INTO TRU_TranDetail
			(
			    refId,
			    email,
				createddate,
				orderreference,
				sitereference,
				Tranid,
				customerid,
				token,
				recordStatus
			)
			VALUES
			(
			    @NewId
				,@user
				,GETDATE()
				,@controlNo
			    ,@sitereference
				,@id
				,@senderId
				,''
				,'DRAFT'
			)
			
			-- UPDATE FOR CUSTOMER LOYALTY
			--IF EXISTS (
			--		SELECT TOP 1 1
			--		FROM REFERRAL_AGENT_WISE
			--		WHERE REFERRAL_TYPE_CODE IN (
			--				'RB'
			--				,'RC'
			--				)
			--			AND REFERRAL_CODE = @introducer
			--		)
			--BEGIN
			--	IF @isEligible = 'Y'
			--	BEGIN
			--		EXEC PROC_Customer_Loyalty @flag = 'update'
			--			,@customerId = @SenderId
			--			,@tranId = @id
			--			,@createdFrom = 'I'
			--			,@reqTranCount = @tranCount
			--			,@schemeCount = @schemeCount
			--			,@isManualSc = @isManualSc
			--			,@serviceCharge = @iServiceCharge
			--			,@createdBy = @user
			--			,@controlNo = @controlNo
			--	END
			--END

			IF (@iServiceCharge <> @calculatedOriginalSc)
				AND ISNULL(@isManualSc, 'Y') = 'Y'
			BEGIN
				UPDATE remitTranTemp
				SET isScMaunal = 1
					,originalSC = @calculatedOriginalSc
					,company = 'M'
				WHERE id = @id
			END

			--SELECT @sourceOfFund = valueId FROM dbo.staticDataValue WHERE detailTitle = @sourceOfFund and typeID = '3900'    
			DECLARE @SOURCE INT
				,@PURPOSEID INT
				,@RELATION INT
				,@OCCUPATIONID INT

			SELECT @SOURCE = valueId
			FROM STATICDATAVALUE(NOLOCK)
			WHERE detailTitle = @sourceOfFund
				AND typeID = '3900'

			SELECT @PURPOSEID = valueId
			FROM STATICDATAVALUE(NOLOCK)
			WHERE detailTitle = @purpose
				AND typeID = '3800'

			SELECT @RELATION = valueId
			FROM STATICDATAVALUE(NOLOCK)
			WHERE detailTitle = @relationship
				AND typeID = '2100'

			SELECT @OCCUPATIONID = valueId
			FROM STATICDATAVALUE(NOLOCK)
			WHERE valueId = @occupation
				AND typeID = '2000'

			EXEC PROC_CUSTOMERMODIFYLOG @flag = 'i-fromSendPage'
				,@user = @user
				,@customerId = @senderId
				,@mobileNumber = @sMobile
				,@monthlyIncome = @salaryRange
				,@email = @sEmail
				,@placeofissue = @sCustIdIssuedCountry
				,@occupation = @OCCUPATIONID
				,@sourceOfFund = @SOURCE

			UPDATE CUSTOMERMASTER
			SET mobile = ISNULL(@sMobile, mobile)
				,monthlyincome = ISNULL(@salaryRange, monthlyincome)
				,email = ISNULL(@sEmail, email)
				,placeofissue = ISNULL(@sCustIdIssuedCountry, placeofissue)
				,occupation = ISNULL(@OCCUPATIONID, occupation)
				,sourceOfFund = ISNULL(@SOURCE, sourceOfFund)
			WHERE CUSTOMERID = @senderId

			EXEC PROC_RECEIVERMODIFYLOGS @flag = 'i-fromSendPage'
				,@address = @rAdd1
				,@email = @rEmail
				,@mobile = @rMobile
				,@receiverId = @receiverId
				,@customerId = @senderId

			UPDATE RECEIVERINFORMATION
			SET address = ISNULL(@rAdd1, address)
				,mobile = ISNULL(@rMobile, mobile)
				,email = ISNULL(@rEmail, email)
				,purposeOfRemit = ISNULL(@PURPOSEID, purposeOfRemit)
				,relationship = ISNULL(@RELATION, relationship)
				,bankBranchName = ISNULL(@pBankBranchName, bankBranchName)
			WHERE receiverId = @receiverId

			IF @collMode = 'Cash Collect'
			BEGIN
				SELECT @userId = userId
				FROM APPLICATIONUSERS
				WHERE USERNAME = @USER

				EXEC PROC_UPDATE_AVAILABALE_BALANCE @FLAG = 'SEND'
					,@S_AGENT = @sAgent
					,@S_USER = @userId
					,@C_AMT = @cAmt
					,@REFERRAL_CODE = @introducer
					,@ONBEHALF = @isOnbehalf
			END
			ELSE
			BEGIN
				EXEC PROC_INSERT_JP_DEPOSIT_TXN_LOG @FLAG = 'I'
					,@TRANID = @id
					,@CUSTOMERID = @senderId
					,@CAMT = @cAmt
			END

			DECLARE @PARTICULARS VARCHAR(200) = 'Send TXN: ' + @controlNo

			EXEC proc_customerTxnHistory @controlNo = @controlNoEncrypted

			DECLARE @XMLDATA XML;

			IF ISNULL(@isAdditionalCDDI, 'N') = 'Y'
			BEGIN
				SET @XMLDATA = CONVERT(XML, REPLACE(@additionalCDDIXml, '&', '&amp;'), 2)

				SELECT ID = p.value('@id', 'varchar(150)')
					,ANSWER = p.value('@answer', 'varchar(500)')
				INTO #TRANSACTION_COMPLIANCE_CDDI
				FROM @XMLDATA.nodes('/root/row') AS tmp(p);

				INSERT INTO TBL_TXN_COMPLIANCE_CDDI
				SELECT @id
					,ID
					,ANSWER
				FROM #TRANSACTION_COMPLIANCE_CDDI
			END

			----UPDATE BRANCH/AGENT CREDIT LIMIT    
			--EXEC Proc_AgentBalanceUpdate_INT @flag = 's',@tAmt = @cAmt ,@settlingAgent = @settlingAgent        
			--10. Compliance----------------------------------------------------------------------------------------------------    
			IF EXISTS (
					SELECT 'X'
					FROM remitTranComplianceTemp WITH (NOLOCK)
					WHERE agentRefId = @agentRefId
					)
			BEGIN
				INSERT INTO remitTranCompliance (
					TranId
					,csDetailTranId
					,matchTranId
					,reason
					)
				SELECT @id
					,csDetailTranId
					,matchTranId
					,reason
				FROM remitTranComplianceTemp WITH (NOLOCK)
				WHERE agentRefId = @agentRefId

				SET @compFinalRes = 'C'

				UPDATE ComplianceLog
				SET tranId = @id
				WHERE agentRefId = @agentRefId
			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
				CREATE TABLE #temp (
					sno INT
					,rmrks NVARCHAR(MAX)
					)

				SELECT @checkNameBy = TRACK_BY
				FROM OFACSETTING(NOLOCK)

				IF ISNULL(@checkNameBy, 'OFAC') = 'OFAC'
				BEGIN
					INSERT INTO #temp (
						sno
						,rmrks
						)
					EXEC proc_sendPageLoadData @flag = 'ofac'
						,@user = @user
						,@blackListIds = @ofacRes
				END
				ELSE
				BEGIN
					INSERT INTO #temp (
						sno
						,rmrks
						)
					EXEC proc_sendPageLoadData @flag = 'ofac'
						,@user = @user
						,@blackListIds = @ofacRes
						,@TRACK_BY = 'DJ'
				END

				DECLARE @ofacResult NVARCHAR(MAX)

				SET @ofacResult = (
						SELECT *
						FROM #temp
						FOR JSON AUTO
						)

				IF (
						@ofacRes <> ''
						AND ISNULL(@compFinalRes, '') = ''
						)
				BEGIN
					INSERT remitTranOfac (
						TranId
						,blackListId
						,reason
						,flag
						,TRACK_BY
						,ofacDetail
						)
					SELECT @id
						,@ofacRes
						,@ofacReason
						,CASE 
							WHEN @trackBy = 'OFAC'
								THEN dbo.FNAGetOFAC_Flag(@ofacRes)
							ELSE 'D'
							END
						,@checkNameBy
						,@ofacResult

					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
						,TRACK_BY
						,ofacDetail
						)
					SELECT @id
						,@ofacRes
						,@ofacReason
						,CASE 
							WHEN @trackBy = 'OFAC'
								THEN dbo.FNAGetOFAC_Flag(@ofacRes)
							ELSE 'D'
							END
						,@checkNameBy
						,@ofacResult

					UPDATE remitTranTemp
					SET tranStatus = 'OFAC/Compliance Hold'
					WHERE controlNo = @controlNoEncrypted
				END
			END

			IF @LIMITERRORCODE <> 0
				AND @RULETYPE = 'H'
				AND @COLLMODE = 'CASH COLLECT'
			BEGIN
				UPDATE remitTranTemp
				SET tranStatus = CASE 
						WHEN tranStatus = 'Compliance Hold'
							THEN 'Cash Limit/Compliance Hold'
						WHEN tranStatus = 'OFAC Hold'
							THEN 'Cash Limit/OFAC Hold'
						WHEN tranStatus = 'OFAC/Compliance Hold'
							THEN 'Cash Limit/OFAC/Compliance Hold'
						ELSE 'Cash Limit Hold'
						END
				WHERE controlNo = @controlNoEncrypted

				INSERT INTO dbo.remitTranCashLimitHold (
					tranId
					,approvedRemarks
					,approvedBy
					,approvedDate
					,reason
					)
				VALUES (
					@id
					,-- tranId - bigint    
					NULL
					,-- approvedRemarks - varchar(150)    
					NULL
					,-- approvedBy - varchar(80)    
					NULL
					,-- approvedDate - datetime    
					NULL -- reason - varchar(500)    
					)
			END

			 --New logic for referral
			 IF (ISNULL(@rewardAmount, 0) > 0 AND @isPromoCode = 'N')
				EXEC proc_InsertRewardPoints @Flag = 'DEBIT', @CustomerId = @senderId, @rewardPoints = @rewardAmount, @TranId = @id

			IF @@TRANCOUNT > 0
				COMMIT TRANSACTION

			IF (
					@complianceRes = 'C'
					OR @ofacRes <> ''
					)
			BEGIN
				SELECT 101 errorCode
					,'Transaction under compliance' msg
					,@controlNo id
					,@id extra
					,@paymentOption extra2
					,@NewId extra3

				RETURN
			END

			SELECT 100 errorCode
				,'Transaction has been sent successfully and is waiting for approval' msg
				,@controlNo id
				,@id extra
				,@paymentOption extra2
				,@NewId extra3
		END
		ELSE IF @flag = 'exRate' --Get Exchange Rate, Service Charge, Scheme/Offer and amount details    
		BEGIN
			IF @partnerId IS NOT NULL --AND @pCountryId = '203'
				SELECT @payoutPartner = AGENTID
					,@exRateCalByPartner = ISNULL(exRateCalByPartner, 0)
				FROM TblPartnerwiseCountry(NOLOCK)
				WHERE CountryId = @pCountryId
					AND IsActive = 1
					AND ISNULL(PaymentMethod, @deliveryMethod) = @deliveryMethod
					AND AGENTID = @partnerId
			ELSE
				SELECT @payoutPartner = AGENTID
					,@exRateCalByPartner = ISNULL(exRateCalByPartner, 0)
				FROM TblPartnerwiseCountry(NOLOCK)
				WHERE CountryId = @pCountryId
					AND IsActive = 1
					AND ISNULL(PaymentMethod, @deliveryMethod) = @deliveryMethod

			IF @payoutPartner IS NOT NULL
			BEGIN
				--GET PAYOUT AGENT DETAILS    
				SELECT @PAGENT = AGENTID
				FROM AGENTMASTER(NOLOCK)
				WHERE PARENTID = @payoutPartner
					AND ISNULL(ISSETTLINGAGENT, 'N') = 'Y';

				SELECT @pSuperAgent = sSuperAgent
					,@pSuperAgentName = sSuperAgentName
					,@pAgent = sAgent
					,@pAgentName = sAgentName
					,@pBranch = sBranch
					,@pBranchName = sBranchName
				FROM dbo.FNAGetBranchFullDetails(@PAGENT)
			END
			ELSE
			BEGIN
				SELECT '1' ErrCode
					,'Partner not yet mapped for the selected country!' Msg
					,NULL id

				RETURN
			END

			

			DECLARE @rowId INT

			SELECT @scValue = 0
				,@scOffer = 0
				,@exRateOffer = 0
				,@scDiscount = 0

			--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
					,NULL id

				RETURN
			END

			IF @pCountryId = 151
				AND @deliveryMethod = 1
			BEGIN
				SELECT AgentId
				INTO #AgentList
				FROM agentMaster(NOLOCK)
				WHERE extCode = 'NP ANYWHERE'

				print 'del1'
				SELECT @exRate = MAX(customerRate)
				FROM #AgentList A
				CROSS APPLY dbo.FNAGetExRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, AgentId, @pCurr, @deliveryMethod) FN
				print @exRate
				print 'del1'
			END
			ELSE
			BEGIN
			print 'del2'
				SELECT @exRate = dbo.FNAGetCustomerRate(@sCountryId, @sAgent, @sBranch, @collCurr, @pCountryId, @pAgent, @pCurr, @deliveryMethod)
				print @exRate
				print 'del2'
			END

			IF ISNULL(@exRate, 0) = 0
			BEGIN
				SELECT '1' ErrCode
					,'Exchange rate not defined yet for receiving currency (' + @pCurr + ')' Msg
					,NULL id

				RETURN
			END

			DECLARE @rate FLOAT, @promRate FLOAT
			SELECT @rate = ISNULL(margin,0), @promRate = ISNULL(purchaseRate,0) FROM countryWiseExchangeRate WHERE countryId = @pCountryId

			IF EXISTS(SELECT 'X' FROM vwtransenders WHERE customerId = @senderId)
			BEGIN
				IF @tpExRate > 0
				BEGIN
					SET @exRate = @exRate - (ISNULL(@tpExRate, @rate) + @promRate)
				END
				ELSE 
				BEGIN
					SET @exRate = @exRate - (ISNULL(@tpExRate , @rate))
				END
			END
			ELSE 
			BEGIN
				SET @exRate = @exRate - (ISNULL(@tpExRate , @rate))
			END
		
			--New code added, referral code add #arjun
			--EXEC PROC_Customer_LoyaltyV2 @flag = 'check-eligible-v2'
			--		,@isEligible = @isEligible OUT
			--		,@referralCode = @introducer
			--		,@tranCount = @trancount OUT
			--		,@schemeCount = @schemeCount OUT
			--		,@customerId = @senderId
			--		,@createdFrom = 'I'


			--IF EXISTS (
			--		SELECT TOP 1 1
			--		FROM REFERRAL_AGENT_WISE
			--		WHERE REFERRAL_TYPE_CODE IN (
			--				'RB'
			--				,'RC'
			--				)
			--			AND REFERRAL_CODE = @introducer
			--		)
			--BEGIN
			--	EXEC PROC_Customer_Loyalty @flag = 'check-eligible'
			--		,@isEligible = @isEligible OUT
			--END
			--EXEC proc_Customer_Loyalty @flag = 'get-tranCount'
			--	,@tranCount = @trancount OUT
			--	,@customerId = @senderId

			--SELECT TOP 1 @schemeCount = txnCount
			--FROM schemeSetup(NOLOCK)
			--ORDER BY createdDate DESC

			pRINT @schemeCount;
			pRINT @isEligible;
			pRINT @trancount;

			

			DECLARE @ValidationResult TABLE (
			    IS_VALID VARCHAR(50),
				ROW_ID INT,
			    PROMOTIONAL_CODE VARCHAR(50),
			    PROMOTIONAL_MSG VARCHAR(255),
			   -- PROMOTION_TYPE INT,
			    PROMOTION_VALUE MONEY,
				MIN_SENDING_AMT MONEY,
				START_DT DATETIME,
				END_DT DATETIME
			)

			DECLARE @availableRewardAmt INT, @row_id INT, @promoValue MONEY, @minSendAmt MONEY, @startDate DATETIME, @endDate DATETIME, @errMsg VARCHAR(100)
			SELECT @availableRewardAmt = CAST(dbo.[FNA_GET_AVAILABLE_BALANCE_POINTS](@senderId) AS INT)

			DECLARE @minCollAmt MONEY, @maxRewardAmt MONEY
			SELECT @maxRewardAmt = CAST(detailDesc AS MONEY) FROM staticDataValue WHERE valueId = '11492' AND detailTitle = 'MAX_REWRAD_AMT'
			SELECT @minCollAmt = CAST(detailDesc AS MONEY) FROM staticDataValue WHERE valueId = '11491' AND detailTitle = 'MIN_COLL_AMT_FOR_REWARD'

			IF ISNUMERIC(ISNULL(@rewardAmt,0)) = 1
			BEGIN
				SET @isPromoCode = 'N'
				IF (ISNULL(@rewardAmt ,0)> 0)
				BEGIN		
					IF (@availableRewardAmt < ISNULL(@rewardAmt, 0))
					BEGIN
						SELECT '1' ErrCode
							,'You do not have sufficient Rewards!'
							,NULL id
						RETURN;
					END
				END
				
				IF(ISNULL(@rewardAmt, 0) > ISNULL(@availableRewardAmt,0))
				BEGIN
					SELECT '1' ErrCode
						,'Please enter the valid point. The amount cannot be more than available Reward Amount!' Msg
						,NULL id

					RETURN
				END

				DECLARE @rewardAmtMoney MONEY = CAST(@rewardAmt AS MONEY)

				IF (@rewardAmtMoney > 0.00 AND @cAmt < @minCollAmt AND @rewardAmtMoney > @maxRewardAmt)                              
				BEGIN
				    SELECT '1' ErrCode
				        ,'The maximum reward amount per transaction is ' + CAST(@maxRewardAmt AS VARCHAR(20)) + ' Pounds and the minimum amount that can be sent for each transaction is ' + CAST(@minCollAmt AS VARCHAR(20)) + ' Pounds' Msg
				        ,NULL id
				    
				    RETURN;
				END

				IF (@rewardAmtMoney > 0.00 AND @rewardAmtMoney > @maxRewardAmt)               			
				BEGIN
				    SELECT '1' ErrCode
				        ,'The maximum reward amount per transaction is ' + CAST(@maxRewardAmt AS VARCHAR(20)) + ' Pounds' Msg
				        ,NULL id
				
				    RETURN;
				END

				IF (@rewardAmtMoney > 0.00 AND @cAmt < @minCollAmt)               			
				BEGIN
				    SELECT '1' ErrCode
				        ,'The minimum amount that can be sent for each transaction is ' + CAST(@minCollAmt AS VARCHAR(20)) + ' Pounds' Msg
				        ,NULL id
				
				    RETURN;
				END
			END
			ELSE
			BEGIN
			print 'promo'
				SET @isPromoCode = 'Y'
				INSERT INTO @ValidationResult (IS_VALID, ROW_ID, PROMOTIONAL_CODE, PROMOTIONAL_MSG, PROMOTION_VALUE, MIN_SENDING_AMT, START_DT, END_DT)

				EXEC proc_CheckPromoValidity @flag='chk-validity', @countryId=@pCountryId, @pmode= @deliveryMethod, @promoCode = @rewardAmt

				IF EXISTS (SELECT 'X' FROM @ValidationResult WHERE IS_VALID = 'VALID')
				BEGIN
					SELECT @row_id = ROW_ID, @promoValue = PROMOTION_VALUE, @minSendAmt = MIN_SENDING_AMT, @startDate = START_DT, @endDate = END_DT FROM @ValidationResult WHERE IS_VALID = 'VALID'
					SET @rewardAmt = @promoValue

					IF (@cAmt < @minSendAmt)
					BEGIN
						 SELECT '1' ErrCode
				        ,'The minimum amount per transaction should be ' + CAST(@minSendAmt AS VARCHAR(20)) + ' Pounds to use Promo Code' Msg
				        ,NULL id
				
				    RETURN;
					END
				END
				ELSE
				BEGIN
					SELECT @errMsg = PROMOTIONAL_MSG FROM @ValidationResult WHERE IS_VALID = 'INVALID'

					SELECT '1' ErrCode
					,@errMsg Msg
					RETURN
				END				
			END

			--IF EXISTS (SELECT 'X' FROM tranSendersTemp tst 
			--	LEFT JOIN remitTranTemp rtt on rtt.id = tst.tranId where rtt.rewardType = 'PROMOCODE' AND tst.customerId = @customerId AND rtt.createdDate BETWEEN @startDate AND @endDate)
			--BEGIN
			--	SELECT '1' ErrCode
			--		,'Promo Code already used!'
			--		,NULL id
			--	RETURN;
			--END

			--IF EXISTS(SELECT 'X' FROM tranSenders ts
			--		LEFT JOIN remitTran rt on rt.id = ts.tranId where rt.rewardType = 'PROMOCODE' AND ts.customerId = @customerId AND rt.createdDate BETWEEN @startDate AND @endDate)
			--BEGIN
			--	SELECT '1' ErrCode
			--		,'Promo Code already used!'
			--		,NULL id
			--	RETURN;
			--END

			IF ISNULL(@cAmt, 0.00) <> 0.00
			BEGIN
				IF @isEligible = 'Y'
				BEGIN
					SET @serviceCharge = 0
					SET @isFreeSc = 'Y'
				END
				
				ELSE
				BEGIN
					SELECT @calcOriginalSc = amount
					FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethod, @cAmt, @collCurr)

					IF ISNULL(@isManualSc, 'N') = 'N'
					BEGIN
					 print 'manual'
						SELECT @serviceCharge =   amount
							 FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethod, @cAmt, @collCurr)
					END
					ELSE
					BEGIN
						SET @serviceCharge = ISNULL(@manualSc, 0)
					END

					IF @serviceCharge IS NULL
						AND ISNULL(@isManualSc, 'N') = 'N'
					BEGIN
						SELECT '1' ErrCode
							,'Service charge not defined yet for receiving country' Msg
							,NULL id

						RETURN;
					END
				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 + ISNULL(@rewardAmt,0)
				SET @pAmt = @tAmt * (@exRate + @exRateOffer)
				--SET @pAmt = FLOOR(@pAmt)
				print 'payam'
				print @pAmt
				print 'another'
				SET @pAmt =Cast(Round(@pAmt,2,1) as decimal(18,2));
				print @pAmt

			END
			ELSE
			BEGIN
				SET @tAmt = @pAmt/(@exRate + @exRateOffer);
				SET @tAmt=Cast(Round(@tAmt,2,1) as decimal(18,2))
				--SET @tAmt = CEILING(@pAmt / (@exRate + @exRateOffer))

				IF @isEligible = 'Y'
				BEGIN
						SET @serviceCharge = 0
						SET @isFreeSc = 'Y'
				END
				ELSE
				BEGIN
				  PRINT @tAmt;
				  PRINT @pAgent
				    PRINT @pBranch
					 PRINT @deliveryMethod
					  PRINT @collCurr
					SELECT @calcOriginalSc = amount
					FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethod, @tAmt, @collCurr)

					IF ISNULL(@isManualSc, 'N') = 'N'
					BEGIN
						SELECT @serviceCharge = @calcOriginalSc --amount
							--FROM [dbo].FNAGetServiceCharge(@sCountryId, @sSuperAgent, @sAgent, @sBranch, @pCountryId, @pSuperAgent, @pAgent, @pBranch, @deliveryMethod, @tAmt, @collCurr)
					END
					ELSE
					BEGIN
						SET @serviceCharge = ISNULL(@manualSc, 0)
					END

					IF @serviceCharge IS NULL
					BEGIN
						SELECT '1' ErrCode
							,'Service charge not defined yet for receiving country' Msg
							,NULL id

						RETURN;
					END
				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, 2)
				--SET @cAmt = CEILING(@cAmt)
				SET @cAmt =Cast(Round(@cAmt,2,1) as decimal(18,2))
				
			END

			--New validation negative coll amt due to manual service charge added
			IF @pAmt <= 0
				OR @tAmt <= 0
				OR @cAmt <= 0
			BEGIN
				SELECT '1' ErrCode
					,'Invalid payout/transfer amount/collect amount found!' Msg
					,NULL id

				RETURN;
			END

			----validate cash hold limit of branch/user    
			--EXEC PROC_CHECK_BRANCH_USER_CASH_HOLD_LIMIT @USER = @USER, @CAMT = @CAMT, @ERRORCODE = @LIMITERRORCODE OUT    
			--            , @ERRORMSG = @msg OUT, @RULETYPE = @RULETYPE OUT    
			--IF @LIMITERRORCODE <> 0 AND @RULETYPE = 'B' AND @collMode = 'CASH COLLECT'    
			--BEGIN    
			-- SELECT '1' ErrCode, 'Branch/User cash hold limit is exceeded, please contact head office!' Msg,NULL id    
			-- RETURN    
			--END     
			--4. Validate Country Sending Limit 
			print 'here'
			print @cAmt
			print @pAmt
			print @sCountryId
			print @collMode
			print @deliveryMethod 
			print @sendingCustType
			print @pCountryId
			print @pCurr
			print @collCurr
			print @pAgent 
			print @sAgent 
			print @sBranch
			print 'end'

			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

			PRINT @cAmt
			print 'pan'
			PRINT @pAmt
			print 'can'
			PRINT @sCountryId
			PRINT @collMode
			PRINT @deliveryMethod

			--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
				,place = @place
				,disc = 0.00
				,collAmt = @cAmt
				,exRateOffer = @exRateOffer
				,scOffer = @scDiscount
				,scAction = @scAction
				,scValue = @scValue
				,scDiscount = @scDiscount
				,tpExRate = 0
				,exRateConfirmId = 0
				,IsFreeSc = @isFreeSc
				,calcOriginalSc = @calcOriginalSc
				,rewardAmt = @rewardAmt
				,isPromoCode = @isPromoCode
				,rowId = @row_id
				,promoCode = @promoCode
		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
					,NULL id

				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
					,NULL id

				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

