﻿--EXEC proc_jme_agent_system_customer @Flag ='register-customer-and-receiver' ,@customerId =null,@user = 'shikshya',@customerType = null,@firstName='cfirst',@middleName='cmiddle',@lastName1='clast',@custEmail='cemail@gmail.com',@custDOB='1995-05-02',@custAdd1=null,@occupation='11267',@custCity='SHINJUKU KU - 新宿区',@cityUnicode=null,@streetUnicode=null,@custPostal=null,@street='794908',@state='10346',@visaStatus='11021',@employeeBusinessType='11008',@nameofEmployeer='cnameofemp',@SSNNO='cssnno',@zipCode='1690074',@sourceOfFound='8075',@remittanceAllowed=True,@onlineUser=True,@remarks='cremarks',@country='113',@custNativecountry='104',@customerIdType='10997',@customerIdNo='hhhhhhh2222',@custIdissueDate='2020-01-02',@custIdValidDate='2021-05-02',@custMobile='+811111111111',@custTelNo='1111111111',@ipAddress=null,@createdBy='shikshya',@custGender='98',@bankId=null,@accountNumber=null,@nameOfAuthorizedPerson=null,@registerationNo=null,@organizationType=null,@dateOfIncorporation=null,@natureOfCompany=null,@position=null,@membershipId=null,@companyName=null,@monthlyIncome='JPY170,000 - JPY340,000',@isCounterVisited='Y',@newPassword=[REDACTED] ='104',@recNativeCountry ='174',@recReceiverType ='4700',@recEmail ='remail@gmail.com',@recFirstName ='RFIRST',@recMiddleName ='RMIDDLE',@recLastName1 ='RLAST',@recLastName2 =null,@recAddress ='raddress',@recCity ='rcity',@recHomePhone ='222222222',@recMobile ='+912222222222',@recRelationship ='11304',@recPlaceOfIssue ='ckathmandu',@recIdType ='10997',@recIdNumber ='2222222222',@recPurposeOfRemit ='8060',@recPaymentMode ='2',@recPayOutPartner ='1499',@recBankLocation ='441335',@recBankName =null,@recReceiverAccountNo ='2222222222222',@recRemarks ='rremarks',@recOtherRelationDesc ='11304'

alter PROC [dbo].[proc_jme_agent_system_customer]
    @flag						VARCHAR(50)			=	NULL,
    @user						VARCHAR(30)			=	NULL,
    @customerId					VARCHAR(30)			=	NULL,
    @fullName					NVARCHAR(200)		=	NULL,
    @passportNo					VARCHAR(30)			=	NULL,
    @mobile						VARCHAR(15)			=	NULL,
    @firstName					VARCHAR(100)		=	NULL,
    @middleName					VARCHAR(100)		=	NULL,
    @lastName1					VARCHAR(100)		=	NULL,
    @lastName2					VARCHAR(100)		=	NULL,
    @customerIdType				VARCHAR(30)			=	NULL,
    @customerIdNo				VARCHAR(50)			=	NULL,
    @custIdissueDate			VARCHAR(30)			=	NULL,
    @custIdValidDate			VARCHAR(30)			=	NULL,
    @custDOB					VARCHAR(30)			=	NULL,
    @custTelNo					VARCHAR(30)			=	NULL,
    @custMobile					VARCHAR(30)			=	NULL,
    @custCity					VARCHAR(100)		=	NULL,
    @custPostal					VARCHAR(30)			=	NULL,
    @companyName				VARCHAR(100)		=	NULL,
    @custAdd1					VARCHAR(100)		=	NULL,
    @custAdd2					VARCHAR(100)		=	NULL,
    @country					VARCHAR(30)			=	NULL,
    @custNativecountry			VARCHAR(30)			=	NULL,
    @custEmail					VARCHAR(50)			=	NULL,
    @custGender					VARCHAR(30)			=	NULL,
    @custSalary					VARCHAR(30)			=	NULL,
    @memberId					VARCHAR(30)			=	NULL,
    @occupation					VARCHAR(30)			=	NULL,
    @state						VARCHAR(30)			=	NULL,
    @zipCode					VARCHAR(30)			=	NULL,
    @district					VARCHAR(30)			=	NULL,
    @homePhone					VARCHAR(30)			=	NULL,
    @workPhone					VARCHAR(30)			=	NULL,
    @placeOfIssue				VARCHAR(30)			=	NULL,
    @customerType				VARCHAR(30)			=	NULL,
    @isBlackListed				VARCHAR(30)			=	NULL,
    @relativeName				VARCHAR(30)			=	NULL,
    @relationId					VARCHAR(30)			=	NULL,
    @lastTranId					VARCHAR(30)			=	NULL,
    @receiverName				VARCHAR(100)		=	NULL,
    @tranId						VARCHAR(20)			=	NULL,
    @ICN						VARCHAR(50)			=	NULL,
    @bank						VARCHAR(100)		=	NULL,
    @bankId						VARCHAR(100)		=	NULL,
    @accountNumber				VARCHAR(100)		=	NULL,
    @mapCodeInt					VARCHAR(10)			=	NULL,
    @sortBy						VARCHAR(50)			=	NULL,
    @sortOrder					VARCHAR(5)			=	NULL,
    @pageSize					INT					=	NULL,
    @pageNumber					INT					=	NULL,
    @HasDeclare					INT					=	NULL,
    @agent						VARCHAR(50)			=	NULL,
    @branch						VARCHAR(50)			=	NULL,
    @branchId					VARCHAR(50)			=	NULL,
    @onlineUser					VARCHAR(50)			=	NULL,
    @ipAddress					VARCHAR(30)			=	NULL,
    @howDidYouHear				VARCHAR(200)		=	NULL,
    @ansText					VARCHAR(200)		=	NULL,
    @isActive					CHAR(1)				=	NULL,
    @email						VARCHAR(150)		=	NULL,
    @searchCriteria				VARCHAR(30)			=	NULL,
    @searchValue				VARCHAR(50)			=	NULL,
    @newPassword				VARCHAR(20)			=	NULL,
    @createdDate				DATETIME			=	NULL,
    @createdBy					VARCHAR(50)			=	NULL,
    @verifyDoc1					VARCHAR(255)		=	NULL,
    @verifyDoc2					VARCHAR(255)		=	NULL,
    @verifyDoc3					VARCHAR(255)		=	NULL,
    @verifyDoc4					VARCHAR(255)		=	NULL,
    @membershipId				VARCHAR(50)			=	NULL,
    @sourceOfFound				VARCHAR(100)		=	NULL,
    @street						VARCHAR(80)			=	NULL,
    @streetUnicode				NVARCHAR(100)		=	NULL,
    @cityUnicode				NVARCHAR(100)		=	NULL,
    @visaStatus					INT					=	NULL,
    @employeeBusinessType		INT					=	NULL,
    @nameOfEmployeer			VARCHAR(80)			=	NULL,
    @SSNNO						VARCHAR(20)			=	NULL,
    @remittanceAllowed			BIT					=	NULL,
    @remarks					VARCHAR(1000)		=	NULL,
    @registerationNo			VARCHAR(30)			=	NULL,
    @organizationType			INT					=	NULL,
    @dateofIncorporation		DATETIME			=	NULL,
    @natureOfCompany			INT					=	NULL,
    @position					INT					=	NULL,
    @nameOfAuthorizedPerson		VARCHAR(80)			=	NULL,
    @fromDate					NVARCHAR(20)		=	NULL,
    @toDate						NVARCHAR(20)		=	NULL,
	@monthlyIncome				VARCHAR(50)			=	NULL,
	@isCounterVisited			CHAR(1)				=	NULL,
	@additionalAddress			VARCHAR(50)			=	NULL,
	@loginBranchId				BIGINT				=	NULL,
	@rowid						BIGINT				=	NULL,
	@docType					INT					=	NULL,
	@otherOccupationText		VARCHAR(50)			=	NULL,

	--for receiverData
      @recFirstName				VARCHAR(100)	= NULL,
      @recMiddleName			VARCHAR(100)	= NULL,
      @recLastName1				VARCHAR(100)	= NULL,
      @recLastName2				VARCHAR(100)	= NULL,
      @recCountry				VARCHAR(200)	= NULL,
      @recNativeCountry			VARCHAR(200)	= NULL,
      @recAddress				VARCHAR(500)	= NULL,
      @recState					VARCHAR(200)	= NULL,
      @recZipCode				VARCHAR(50)		= NULL,
      @recCity					VARCHAR(100)	= NULL,
      @recEmail					VARCHAR(150)	= NULL,
      @recHomePhone				VARCHAR(100)	= NULL,
      @recWorkPhone				VARCHAR(100)	= NULL,
      @recMobile				VARCHAR(100)	= NULL,
      @recRelationship			VARCHAR(100)	= NULL,
      @recSortBy				VARCHAR(50)		= NULL,
      @recSortOrder				VARCHAR(5)		= NULL,
      @recReceiverType			INT				= NULL,
      @recIdType				INT				= NULL,
      @recIdNumber				VARCHAR(25)		= NULL,
      @recPlaceOfIssue			VARCHAR(80)		= NULL,
      @recPaymentMode			INT				= NULL,
      @recBankLocation			VARCHAR(100)	= NULL,
      @recPayOutPartner			INT				= NULL,
      @recBankName				VARCHAR(150)	= NULL,
      @recReceiverAccountNo		VARCHAR(40)		= NULL,
      @recRemarks				NVARCHAR(800)	= NULL,
      @recPurposeOfRemit		VARCHAR(100)	= NULL,
	  @purposeOfRemitanceOther	VARCHAR(100)	= NULL,
      @recFromDate				NVARCHAR(20)	= NULL,
      @recToDate				NVARCHAR(20)	= NULL,
	  @recOtherRelationDesc		VARCHAR(20)		= NULL,
	  @receiverId				VARCHAR(50)		= NULL,
	  @branchManual 			VARCHAR(100)	= NULL

AS
SET NOCOUNT ON;  
SET XACT_ABORT ON;  


BEGIN TRY 
--BEGIN NECESSARY STEPS FOR CUSTOMER REGISTER
	IF @sortBy = 'SN'
	   SET @sortBy = NULL;
	SELECT  @homePhone = @customerIdNo ,
	        @accountNumber = REPLACE(@accountNumber, '-', '');
	
	IF ISNUMERIC(@country) <> '1'
    SET @country = ( SELECT TOP 1
                            countryId
                     FROM   countryMaster WITH ( NOLOCK )
                     WHERE  countryName = @country
                   );  
	CREATE TABLE #msg
	    (
	      errorCode INT ,
	      msg VARCHAR(100) ,
	      id INT
	    );	
	DECLARE @sql VARCHAR(MAX) ,
	    @oldValue VARCHAR(MAX) ,
	    @newValue VARCHAR(MAX) ,
	    @module VARCHAR(10) ,
	    @tableAlias VARCHAR(100) ,
	    @logIdentifier VARCHAR(50) ,
	    @logParamMod VARCHAR(100) ,
	    @logParamMain VARCHAR(100) ,
	    @table VARCHAR(MAX) ,
	    @select_field_list VARCHAR(MAX) ,
	    @extra_field_list VARCHAR(MAX) ,
        @sql_filter VARCHAR(MAX) ,
        @modType VARCHAR(6) ,
        @errorMsg VARCHAR(MAX) ,
        @bankName VARCHAR(100);  

    
	SELECT  @logIdentifier = 'customerId' ,
	       @logParamMain = 'customerMaster' ,
	       @module = '20' ,
	       @tableAlias = 'CustomerMaster';  
       
 
	SET @fullName = UPPER(@fullName)				
	SET @passportNo = UPPER(@passportNo)					
	SET @firstName = UPPER(@firstName)					
	SET @middleName = UPPER(@middleName)					
	SET @lastName1 = UPPER(@lastName1)					
	SET @lastName2 = UPPER(@lastName2)		
	--BEGIN NECESSARY STEPS FOR CUSTOMER REGIST

	--BEGIN NECESSARY STEPS FOR RECEIVER DATA
          
		--,@customerId1			VARCHAR(50)
		DECLARE @PURPOSEID INT = NULL, @RELATION INT = NULL

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

		IF @PURPOSEID IS NULL
			SET @PURPOSEID = @recPurposeOfRemit

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

		IF @RELATION IS NULL
			SET @RELATION = @recRelationship
	--BEGIN NECESSARY STEPS FOR RECEIVER DATA

IF @flag = 'register-customer-and-receiver'
BEGIN 
	SET @onlineUser = CASE WHEN @onlineUser='true'THEN 'Y' ELSE 'N' END
	DECLARE @OBP_ID INT = null

	
	--BEGIN CUSTOMER VALIDATION

    IF EXISTS (SELECT  'X' FROM customerMaster WITH (NOLOCK)WHERE   email = @custEmail)
    BEGIN  
        SELECT  @errorMsg = 'Customer with email '+ @custEmail + ' already exist.';  
        EXEC proc_errorHandler 1, @errorMsg, @customerId; 
        RETURN;  
    END;  
				
	IF EXISTS ( SELECT  'X' FROM   customerMaster WITH (NOLOCK)
						WHERE   email = @custEmail
	                    AND ISNULL(onlineUser, 'N') = 'Y'
	                    AND ISNULL(isDeleted, 'N') = 'N' )
	BEGIN  
	    SELECT  @errorMsg = 'Customer with email '+ @custEmail + ' already exist.';  
	    EXEC proc_errorHandler 1, @errorMsg, @customerId;  
	    RETURN;  
	END; 

	IF EXISTS ( SELECT  'x' FROM customerMaster (NOLOCK)
	 					WHERE   REPLACE(idNumber, '-', '') = REPLACE(@customerIdNo,'-', '') )
	BEGIN  
	    SELECT  @errorMsg = 'Customer with idnumber '+ @customerIdNo + ' already exist.';  
	    EXEC proc_errorHandler 1, @errorMsg, @customerId;  
	    RETURN;  
	END; 
	--END OF CUSTOMER VALIDATION
	--BEGIN OF CUSTOMER DATA PREPARATION
	DECLARE @newMobileNumber VARCHAR(20) = REPLACE(@custMobile, '+', '')
	SET @newMobileNumber = CASE WHEN @newMobileNumber LIKE '81%' THEN STUFF(@newMobileNumber, 1, 2, '') ELSE @newMobileNumber END
		
	SELECT @firstName = LTRIM(RTRIM(@firstName))
		    ,@middleName = LTRIM(RTRIM(@middleName))
			,@lastName1 = LTRIM(RTRIM(@lastName1))
			,@fullName = ISNULL(@firstName, '')
                         + ISNULL(' ' + @middleName, '')
                         + ISNULL(' ' + @lastName1, '')
					     + ISNULL(' ' + @lastName2, '')
		
	IF @newPassword IS NULL
	BEGIN
		SET @newPassword = [REDACTED]
	                         + CAST(CHECKSUM(NEWID()) AS VARCHAR),
	                      7);
	END

	IF @streetUnicode = 'Nnull'
	BEGIN
	    SET @streetUnicode = NULL;
	END;
	
	IF @cityUnicode = 'Nnull'
	BEGIN
	    SET @cityUnicode = NULL;
	END;
	IF @customerType = '4701'
	BEGIN
		SET @employeeBusinessType = NULL;
	END
	IF @customerType IS NULL
	BEGIN
		SET @customerType = '4700'
	END
		
	IF ISNULL(@street, '') IS NOT NULL
	BEGIN
		SET @district = @street
		SELECT @custCity = CITY_NAME, @street = STREET_NAME 
		FROM TBL_JAPAN_ADDRESS_DETAIL(NOLOCK)
		WHERE ROW_ID = @district
	END
	--END OF CUSTOMER DATA PREPARATION 
	BEGIN TRANSACTION;  
               INSERT  INTO customerMaster(
						firstName,middleName,lastName1,lastName2,country,[address],zipCode,district,city,email,homePhone,workPhone,mobile,
						nativeCountry,dob,placeOfIssue,occupation,isBlackListed,lastTranId,relationId,relativeName,gender,salaryRange,address2,
						fullName,
						createdBy,createdDate,postalCode,idIssueDate,idExpiryDate,idType,idNumber,telNo,agentId,branchId,onlineUser,
						ipAddress,customerPassword,customerType,isActive,verifiedBy,verifiedDate,isForcedPwdChange,bankName,bankAccountNo,HasDeclare,
						membershipId,[state],sourceOfFund,street,streetUnicode,cityUnicode,visaStatus,employeeBusinessType,nameOfEmployeer,SSNNO,
						remittanceAllowed,remarks,registerationNo,organizationType,dateofIncorporation,natureOfCompany,position
						,nameOfAuthorizedPerson,monthlyIncome,OBPID,ADDITIONALADDRESS,documentType,occupationOther
					)
                       VALUES (
						@firstName,@middleName,@lastName1,@lastName2,@country,@custAdd1,ISNULL(@zipCode, @custPostal),@district,@custCity,@custEmail,null,@workPhone,@custMobile,
						@custNativecountry,@custDOB,@placeOfIssue,@occupation,@isBlackListed,@lastTranId,@relationId,@relativeName,@custGender,@custSalary,@custAdd2,
						@fullName,
                           @user,DATEADD(HH, 0, GETUTCDATE()),@custPostal,@custIdissueDate,@custIdValidDate,@customerIdType,@customerIdNo,@custTelNo,@loginBranchId,@branch,@onlineUser,
						@ipAddress,dbo.FNAEncryptString(@newPassword),@customerType,'Y',@user,NULL,'1',@bankId,@accountNumber,@HasDeclare,---- New Added Values
						@membershipId,@state,@sourceOfFound,@street,@streetUnicode,@cityUnicode,@visaStatus,@employeeBusinessType,@nameOfEmployeer,@SSNNO,
						@remittanceAllowed,@remarks,@registerationNo,@organizationType,@dateofIncorporation,@natureOfCompany,@position
						,@nameOfAuthorizedPerson,@monthlyIncome,null,@additionalAddress,@docType,@otherOccupationText
					)
               SET @customerId = SCOPE_IDENTITY();
		
               EXEC PROC_GENERATE_MEMBERSHIP_ID @USER = @user,
                   @CUSTOMERID = @customerId,@loginBranchId = @loginBranchId, @MEMBESHIP_ID = @membershipId OUT;
            
               UPDATE  dbo.customerMaster
               SET     membershipId = @membershipId
               WHERE   customerId = @customerId;

			IF @isCounterVisited ='Y'
			BEGIN
			    INSERT INTO dbo.TBL_CUSTOMER_KYC
								(	customerId,kycMethod,kycStatus,createdBy,createdDate,isDeleted
								)
						VALUES  ( 
									@customerId,11048,11044,@user,GETDATE(),0
								)
			END

			 INSERT  INTO receiverInformation
                        (fullname
						 ,membershipId ,customerId ,firstName ,middleName ,lastName1 ,lastName2 ,country ,NativeCountry,[address] ,[state] ,zipCode ,city ,email ,
                          homePhone ,workPhone ,mobile ,relationship ,receiverType ,idType ,idNumber ,placeOfIssue ,paymentMode ,bankLocation ,payOutPartner ,
                          bankName ,receiverAccountNo ,remarks ,purposeOfRemit ,createdBy ,createdDate,otherRelationDesc,agentId,purposeOther,
						  bankBranchName
		                )
                        SELECT    ISNULL(@recFirstName,'') + ISNULL(' ' + @recMiddleName,'') +ISNULL(' ' + @recLastName1,''),
								@membershipId ,@customerId ,@recFirstName ,@recMiddleName ,@recLastName1 ,@recLastName2 ,@recCountry ,@recNativeCountry,@recAddress ,@recState ,@recZipCode ,@recCity ,@recEmail ,
                                @recHomePhone ,@recWorkPhone ,@recmobile ,@RELATION ,@recReceiverType ,@recIdType ,@recIdNumber ,@recPlaceOfIssue ,@recPaymentMode ,@recBankLocation ,@recPayOutPartner ,
                                @recBankName ,@recReceiverAccountNo ,@recRemarks ,@PURPOSEID ,@user ,GETDATE(),@recOtherRelationDesc,@loginBranchId	,@purposeOfRemitanceOther,
								@branchManual
				
				SET @receiverId=SCOPE_IDENTITY();						


               IF @@TRANCOUNT > 0
                   COMMIT TRANSACTION;  

               SELECT  '0' ErrorCode ,
                       'Customer and receiver has been registered successfully with customer membershipId: '+CAST(@membershipId AS VARCHAR) + ' and with receiverId: ' + CAST(@receiverId AS VARCHAR) Msg ,
                 cast(@customerId as varchar) +'|' + cast(@membershipId as varchar) + '|' + cast(cast(GETDATE() as date) as varchar) + '|'  + cast(@receiverId as varchar) id;
END


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