USE [FastMoneyPro_Remit]
GO
/****** Object:  StoredProcedure [dbo].[INBOUND_PROC_SCHEDULER_RECEIVER_SCANNER]    Script Date: 3/16/2020 10:36:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER    PROC [dbo].[INBOUND_PROC_SCHEDULER_RECEIVER_SCANNER]
(
	 @Flag			VARCHAR(30)		= NULL
	,@user			VARCHAR(100)	= NULL
	,@bank			VARCHAR(100)	= NULL
    ,@accountNo		VARCHAR(100)	= NULL 
    ,@mobile		VARCHAR(100)	= NULL 
    ,@id			BIGINT			= NULL 
	,@processId		VARCHAR(100)	= NULL
	,@customerId	BIGINT			= NULL
	,@controlNo		VARCHAR(100)	= NULL


)
AS
SET NOCOUNT ON
DECLARE  @tranId					BIGINT
		,@EncryptedprocessId		VARCHAR(100)
DECLARE @controlNoEncrypted VARCHAR(20)
SELECT @controlNoEncrypted = dbo.FNAEncryptString(@controlNo)

BEGIN TRY
	IF @Flag='getUnpaidTxn'
	BEGIN 
		SELECT TOP 100  rt.id, rt.pBank,rt.accountNo,rt.receiverName,rt.senderName,rt.sCountry ,tr.mobile
			 FROM dbo.INBOUND_REMIT_TRAN (NOLOCK) rt
		INNER JOIN dbo.INBOUND_TRAN_RECEIVERS (NOLOCK) tr ON tr.tranId=rt.id
		WHERE tranStatus='Payment' AND payStatus='Hold' 
		AND rt.id NOT IN (SELECT tranId FROM dbo.INBOUND_PROCESSID(NOLOCK))
		RETURN 	
	END

	IF @Flag='checkBankDetails'
	BEGIN 
		DECLARE @IsCustomerExist	BIT = 0, @IsCustomerApproved	BIT =0
				,@IsPennyTest		BIT = 0, @CustomerApproved  VARCHAR(100)
				,@customerType		VARCHAR(100)

		SELECT TOP 1 @customerId=customerId,@CustomerApproved=approvedDate,
					@customerType=CASE WHEN customerType='11018' THEN 1 ELSE 0 END
		 FROM dbo.customerMaster (NOLOCK)
		WHERE bankName=@bank AND bankAccountNo=@accountNo 
		 AND approvedDate IS NOT NULL

		IF @CustomerId IS NOT NULL
			SET @IsCustomerExist = 1 

		IF @CustomerApproved IS NOT NULL
			SET @IsCustomerApproved = 1

		IF @IsCustomerExist = 0
		BEGIN
			IF EXISTS(SELECT 'X' FROM dbo.INBOUND_CUSTOMERBANKLIST(NOLOCK) t  
			INNER JOIN dbo.KoreanBankList(NOLOCK) k ON k.bankCode = t.bankCode
			WHERE t.accountNo = @accountNo AND k.rowId = @bank AND t.isPennyTest = 1)
			BEGIN
				 SELECT 
					 @customerId = t.customerId
					,@IsPennyTest = CASE WHEN t.isPennyTest = 1 THEN 1 ELSE 0 END
				FROM dbo.INBOUND_CUSTOMERBANKLIST(NOLOCK) t  
				INNER JOIN dbo.KoreanBankList(NOLOCK) k ON k.bankCode = t.bankCode
				WHERE t.accountNo = @accountNo AND k.rowId = @bank AND t.isPennyTest = 1

				SELECT 
					@IsCustomerExist = CASE WHEN @customerId IS NOT NULL THEN 1 ELSE 0 END
				   ,@IsCustomerApproved = CASE WHEN approvedDate IS NOT NULL THEN 1 ELSE 0 END
				FROM dbo.customerMaster(NOLOCK) WHERE customerId = @customerId
			END
		END


		 --SELECT @IsCustomerExist,@IsCustomerApproved,@IsPennyTest
		 --RETURN


		IF EXISTS(SELECT 'X' FROM dbo.INBOUND_CUSTOMERBANKLIST (NOLOCK) WHERE customerId=@CustomerId AND action='SUCCESS')
		BEGIN		
			SET @IsPennyTest = 1		
		END
		
		IF EXISTS(SELECT 'X' FROM dbo.TblCustomerBankVerification (NOLOCK) WHERE customerId=@CustomerId AND action='SUCCESS')
		BEGIN		
			SET @IsPennyTest = 1
			IF NOT EXISTS(SELECT * FROM dbo.INBOUND_CUSTOMERBANKLIST(NOLOCK) t 
							INNER JOIN dbo.KoreanBankList(NOLOCK) k ON k.bankCode = t.bankCode 
							WHERE t.accountNo = @accountNo AND k.rowId = @bank )
			BEGIN
				INSERT INTO dbo.INBOUND_CUSTOMERBANKLIST
				(
					customerId,customerName,certNumber,certLimitCount,bankCode,
					accountNo,isPennyTest,action,
					createdDate, createdBy, reqDate, certDate
				)
				SELECT @CustomerId,cm.firstName,cv.certNumber,cv.certLimitCount,cm.bankName
					,cv.bankAccountNo,1,cv.action,GETDATE(),'system',cv.reqDate,cv.certDate 
				FROM dbo.TblCustomerBankVerification (nolock) cv
				INNER JOIN dbo.customerMaster (NOLOCK) cm ON cm.customerId = cv.customerId WHERE cm.customerId=@CustomerId AND action='SUCCESS'
			END
		END
		
		
		/*Already existing customer */
		IF(@IsCustomerExist= 1 AND @IsCustomerApproved= 1 AND @IsPennyTest= 1)
		BEGIN	
		BEGIN TRANSACTION	
			UPDATE dbo.INBOUND_REMIT_TRAN SET
					 payStatus='Unpaid' 
					 ,postedDate=GETDATE()
					 ,postedBy='system' 
			 WHERE id =@id

			 UPDATE INBOUND_TRAN_RECEIVERS SET
					customerId=@customerId
			WHERE tranId=@id
		
		IF @@TRANCOUNT > 0
				COMMIT TRANSACTION
			
			SELECT	0 ErrorCode, 'Transaction post successfully!' Msg,NULL Id
			RETURN 
		END
		
		SELECT @processId=LEFT(CONVERT(VARCHAR(36), NEWID()), 8) 	
			SET @EncryptedprocessId=dbo.FNAEncryptString(@processId)

		/*New customer*/
		IF(@IsCustomerExist= 0 AND @IsCustomerApproved= 0 AND @IsPennyTest= 0 )
		BEGIN
			 IF NOT EXISTS(SELECT 'x' FROM dbo.INBOUND_PROCESSID(NOLOCK) WHERE processID=@processId OR (tranId=@id AND remarks='Register'))
			 BEGIN
				BEGIN TRANSACTION
					INSERT INTO  dbo.INBOUND_PROCESSID(processID,tranId,remarks,createdDate)SELECT @processId,@id,'Register',GETDATE()			
		   
					INSERT INTO KT_SMS.dbo.SDK_SMS_SEND ( USER_ID, SCHEDULE_TYPE, SUBJECT, SMS_MSG, NOW_DATE, SEND_DATE, CALLBACK, DEST_INFO)
					SELECT 'globalmoney',0,'Inbound','Test Registration Link.(http://gmeuat.gmeremit.com:5023/Register?ib='+CAST(@EncryptedprocessId AS VARCHAR(100))+')',FORMAT(GETDATE(),'yyyyMMddHHmmss')
					,FORMAT(GETDATE(),'yyyyMMddHHmmss'),'1588-6864',@mobile
			
				IF @@TRANCOUNT > 0
				COMMIT TRANSACTION

				SELECT	0 ErrorCode, 'New Customer' Msg,NULL Id
				RETURN 
			 END
			 SELECT	1 ErrorCode, 'New Customer!. Sms already sent.' Msg,NULL Id	
			 RETURN
             
		END

		/*penny test */
		IF(@IsCustomerExist= 1 AND @IsPennyTest= 0 )--AND @customerType=1)
		BEGIN
			 IF NOT EXISTS(SELECT 'x' FROM dbo.INBOUND_PROCESSID(NOLOCK) WHERE processID=@processId OR (tranId=@id AND remarks='Penny'))
			 BEGIN
				BEGIN TRANSACTION
					INSERT INTO  dbo.INBOUND_PROCESSID(processID,tranId,customerId,remarks,createdDate)
										SELECT @processId,@id,@customerId,'Penny',GETDATE()				
		   
					INSERT INTO KT_SMS.dbo.SDK_SMS_SEND ( USER_ID, SCHEDULE_TYPE, SUBJECT, SMS_MSG, NOW_DATE, SEND_DATE, CALLBACK, DEST_INFO)
					SELECT 'globalmoney',0,'Inbound','Test Penny Link.(http://gmeuat.gmeremit.com:5023/PennyCertificate?ib='+CAST(@CustomerId AS VARCHAR(50))+'&pi='+CAST(@EncryptedprocessId AS VARCHAR(100))+')',FORMAT(GETDATE(),'yyyyMMddHHmmss')
					,FORMAT(GETDATE(),'yyyyMMddHHmmss'),'1588-6864',@mobile
			
				 
				IF @@TRANCOUNT > 0
				COMMIT TRANSACTION
			
				SELECT	0 ErrorCode, 'Penny Test' Msg,NULL Id
				RETURN
			 END
			 SELECT	1 ErrorCode, 'Penny Test!.Sms already sent.' Msg,NULL Id	
			 RETURN
		END
		--/*approve customer */
		--IF(@IsCustomerExist= 1 AND @IsCustomerApproved = 0 )
		--BEGIN
		--	IF NOT EXISTS(SELECT 'x' FROM dbo.INBOUND_PROCESSID(NOLOCK) WHERE processID=@processId OR (tranId=@id AND remarks='Approve'))
		--	BEGIN
		--		BEGIN TRANSACTION
		--			INSERT INTO  dbo.INBOUND_PROCESSID(processID,tranId,customerId,remarks,createdDate)
		--								SELECT @processId,@id,@customerId,'Approve',GETDATE()	
		   
		--		   INSERT INTO KT_SMS.dbo.SDK_SMS_SEND ( USER_ID, SCHEDULE_TYPE, SUBJECT, SMS_MSG, NOW_DATE, SEND_DATE, CALLBACK, DEST_INFO)
		--			 SELECT 'inbound',0,'Notice','Test document approval.',FORMAT(GETDATE(),'yyyyMMddHHmmss')
		--			,FORMAT(GETDATE(),'yyyyMMddHHmmss'),'1588-6864',@mobile
			
		--		IF @@TRANCOUNT > 0
		--		COMMIT TRANSACTION
			
		--		SELECT	0 ErrorCode, 'Customer approval pending' Msg,NULL Id
		--		RETURN 
		--	END
		--	SELECT	1 ErrorCode, 'Customer approval pending.Sms already sent' Msg,NULL Id
		--		RETURN

		--END
		SELECT	1 ErrorCode, 'No record found' Msg,NULL Id
		RETURN
	END
		
	IF @Flag='getCustBankDetails' --autoload bank name and accounno ddl in online system
	BEGIN
		SELECT @tranId=tranId FROM dbo.INBOUND_PROCESSID (NOLOCK) WHERE processID =dbo.FNADecryptString(@processId)

		SELECT TOP 1 pBank ,accountNo FROM INBOUND_REMIT_TRAN(NOLOCK) 
		 WHERE id=@tranId
		RETURN 
	END
	IF @Flag='checkInboundRequest' --check processid of inbound request
	BEGIN
		IF EXISTS(SELECT 'X' FROM dbo.INBOUND_PROCESSID (NOLOCK) WHERE processID =dbo.FNADecryptString(@processId) AND customerId=@customerId)
		BEGIN
			SELECT	0 ErrorCode, 'Valid request' Msg,@customerId Id
			RETURN 
		END
		SELECT	1 ErrorCode, 'InValid request for penny test.Please contact GME.' Msg,NULL Id
		RETURN 
		
	END
	IF @Flag='checkCustomerType' --check inbound customer 
	BEGIN
	IF EXISTS(SELECT 'X' FROM dbo.customerMaster(NOLOCK) WHERE customerId=@customerId )
	BEGIN
	  SELECT customerType =CASE WHEN customerType='11018' THEN 'INBOUND' ELSE  'OUTBOUND' END
		 FROM dbo.customerMaster(NOLOCK) WHERE customerId=@customerId
		RETURN 	
	END 
	END
	
	IF @Flag='getTxnForPaid'
	BEGIN 
	
		SELECT  rt.id AS tranId, rt.controlNo
			 FROM dbo.INBOUND_REMIT_TRAN (NOLOCK) rt
		WHERE tranStatus='Payment' AND payStatus='Unpaid' 
		RETURN 	
	END	
	IF @flag='Post'
	BEGIN
	 IF EXISTS ( SELECT 1 FROM dbo.INBOUND_REMIT_TRAN (NOLOCK) WHERE controlNo=@controlNo AND tranStatus='Payment' AND payStatus='Unpaid')
	 BEGIN	   
			UPDATE INBOUND_REMIT_TRAN 
				SET payStatus='Post',postedDate=GETDATE(),postedDateLocal=GETDATE(),postedBy='system' 
			WHERE controlNo =@controlNo 
			AND tranStatus='Payment' AND payStatus='Unpaid' AND id=@id

		SELECT TOP 1 
			 kb.bankCode AS receiveInstitution 
			,accountNo AS receiveAccountNo
			,senderName
			,pAmt AS  amount 					
		FROM INBOUND_REMIT_TRAN (NOLOCK) rt  
		INNER JOIN dbo.KoreanBankList(NOLOCK) kb ON kb.rowId = rt.pBank
		WHERE controlNo =@controlNo 
		AND tranStatus='Payment' AND payStatus='Post'	AND id=@id

	 END	
	END
	IF @flag='Paid'
	BEGIN
		
	   DECLARE @tId BIGINT, @ctrlNo VARCHAR(100)
	   SELECT @tId = id, @ctrlNo = dbo.FNADecryptString(controlNo) FROM  INBOUND_REMIT_TRAN(NOLOCK) WHERE controlNo =@controlNo 
		AND tranStatus='Payment' AND payStatus='Post'

		BEGIN TRAN

	     UPDATE INBOUND_REMIT_TRAN SET 
				tranStatus = 'Paid'
				,payStatus = 'Paid'
				,paidDate  =  GETDATE()
				,paidBy   =   'system'
	    WHERE controlNo = @controlNo 
		AND tranStatus='Payment' AND payStatus='Post'

		INSERT INTO dbo.inboundVoucherMaster
		(
		    tranId,
		    controlNo,
		    category,
		    seq,
		    VoucherGeneratedDate,
		    isGenerated
		)
		VALUES
		(   @tId,         -- tranId - bigint
		    @ctrlNo,        -- controlNo - varchar(50)
		    'paid',        -- category - varchar(50)
		    2,         -- seq - int
		    NULL, -- VoucherGeneratedDate - datetime
		    0       -- isGenerated - bit
		    )
		COMMIT TRAN		

		EXEC proc_errorHandler 0, 'Transaction has been successfully Paid', @id
	END			
	
END TRY
BEGIN CATCH
	IF @@TRANCOUNT > 0
		ROLLBACK TRAN
		
	EXEC proc_errorHandler 1 ,'Exception occured' ,NULL

END CATCH






