		INSERT INTO bankcreditcard(bankId, creditCardName, benifitDescription, keyFeatures,joiningFee,renualFee,creditCardUrl, createdBy, modifiedBy) 
        VALUES(_bankId, _creditCardName, _benifitDescription, _keyFeatures,_joiningFee,_renualFee,_creditCardUrl, _userId, _userId);
    END IF;
END$$
DELIMITER ;



DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCustomerAddress`(IN _customerAddressId INT, IN _customerId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100), IN _district VARCHAR(100), IN _state VARCHAR(50),IN _customerLoanId INT, IN _userId INT)
BEGIN
	IF _customerAddressId > 0 THEN
		UPDATE customeraddresses SET customerId = _customerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2
        , pincode = _pincode, cityId = _cityId, city = _city, district = _district, state = _state, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerAddressId;
        SELECT _customerAddressId as customerAddressId,_addressTypeId as addressTypeId;
    ELSE 
		INSERT INTO customeraddresses(customerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) VALUES(_customerId
        , _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
        SET _customerAddressId = LAST_INSERT_ID();
        SELECT _customerAddressId as customerAddressId,_addressTypeId as addressTypeId;
    END IF;
END$$
DELIMITER ;





DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCustomerCreditCard`(IN _customerId INT, IN _userId INT, IN _creditCardId INT, IN _fullName VARCHAR(200),IN _birthdate DATETIME,IN _gender VARCHAR(15), IN _panCardNo VARCHAR(20), IN _maritalStatusId INT,IN _otherCreditCardBankId INT,IN _maxCreditLimit varchar(45),IN _availableCreditLimit varchar(45),IN _isAlreadyCreditCard tinyint,IN _email varchar(200),IN _currentUserId INT,IN _partnerId INT,IN _creditCardEmploymentDetailId INT, IN _employmentTypeId INT,IN _companyName varchar(100),IN _professionName varchar(100),IN _bankId INT,IN _bankAccountNo varchar(45),IN _lastItr TEXT,IN _educationTypeId INT,IN _officeContactNo varchar(45))
BEGIN    
        UPDATE customers SET gender=_gender, fullName=_fullName, birthdate = _birthdate ,panCardNo = _panCardNo, maritalStatusId = _maritalStatusId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerId;   
    
    IF _creditCardId>0 THEN
        IF _isAlreadyCreditCard = TRUE THEN
                UPDATE customercreditcards SET customerId = _customerId,isAlreadyCreditCard = _isAlreadyCreditCard ,otherCreditCardBankId = _otherCreditCardBankId,maxCreditLimit = _maxCreditLimit ,availableCreditLimit = _availableCreditLimit,
        modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardId;
        ELSE 
        UPDATE customercreditcards SET customerId = _customerId,isAlreadyCreditCard = _isAlreadyCreditCard ,otherCreditCardBankId = null,maxCreditLimit = null ,availableCreditLimit = null,
        modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardId;
        END IF;
		ELSE
		INSERT INTO customercreditcards(customerId,isAlreadyCreditCard,otherCreditCardBankId, maxCreditLimit,availableCreditLimit,createdBy, modifiedBy) VALUES(_customerId,_isAlreadyCreditCard,_otherCreditCardBankId,_maxCreditLimit,_availableCreditLimit, _userId, _userId);
        SET @creditCardId = LAST_INSERT_ID();
        SET _creditCardId = @creditCardId;
        IF _partnerId>0 THEN
                        INSERT INTO partnercustomercreditcards(customerCreditCardId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(@creditCardId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
            
        END IF;
    
    IF _currentUserId>0 THEN
                UPDATE users SET email = _email,fullName=_fullName ,gender=_gender, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_currentUserId WHERE id = _currentUserId;
    END IF;
    IF _creditCardId >0 THEN
    SELECT _creditCardId as creditCardId;
    END IF;
     IF _creditCardEmploymentDetailId >0 THEN
       UPDATE customercreditcardemploymentdetail SET employmentTypeId=_employmentTypeId,creditCardId = _creditCardId, companyName =_companyName,professionName = _professionName,officeContactNo = _officeContactNo, bankId = _bankId,bankAccountNo = _bankAccountNo, lastItr = _lastItr,educationTypeId = _educationTypeId ,modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardEmploymentDetailId;
	ELSE 
		INSERT INTO customercreditcardemploymentdetail(employmentTypeId, creditCardId, companyName, professionName,bankId,bankAccountNo,lastItr,educationTypeId,officeContactNo,createdBy, modifiedBy) VALUES(_employmentTypeId, _creditCardId, _companyName,_professionName,_bankId, _bankAccountNo,_lastItr,_educationTypeId,_officeContactNo,_userId, _userId);
	END IF;
    INSERT INTO creditcardcompletescreenhistory (customerCreditCardId,isCompleted,completeScreen) VALUES (@creditCardId,true,5);
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCustomerLoanPropertyDetail`(IN _customerLoanId INT, IN _customerLoanPropertyDetailId INT
, IN _propertyTypeId INT, IN _propertyPurchaseValue DECIMAL(15,2), IN _propertyCityId INT, IN _propertyCity VARCHAR(100), IN _propertyDistrict VARCHAR(100), IN _propertyState VARCHAR(100),IN _pincode VARCHAR(10),IN _addressLine1 TEXT, IN _addressLine2 TEXT
, IN _userId INT,IN _loanAmountTakenExisting DECIMAL(15,2),IN _approxDate VARCHAR(200),IN _topupAmount DECIMAL(15,2),IN _approxCurrentEMI DECIMAL(15,2),IN _bankId INT,IN _customerLoanTransferPropertyDetailId INT,IN _loanType varchar(45))
BEGIN
		IF _customerLoanPropertyDetailId > 0 THEN      
        UPDATE customerloanpropertydetails SET propertyTypeId = _propertyTypeId, propertyPurchaseValue = _propertyPurchaseValue, propertyCityId = _propertyCityId, propertyCity = _propertyCity, pincode = _pincode, addressLine1 =_addressLine1,addressLine2 =_addressLine2
        , propertyDistrict = _propertyDistrict, propertyState = _propertyState, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(),loanType = _loanType WHERE id = _customerLoanPropertyDetailId;
        SELECT _customerLoanPropertyDetailId as customerLoanPropertyDetailId;
		ELSE
        INSERT INTO customerloanpropertydetails(customerLoanId, propertyTypeId, propertyPurchaseValue, propertyCityId, propertyCity, propertyDistrict, propertyState, pincode,addressLine1,addressLine2,loanType,createdBy, modifiedBy) 
        VALUES(_customerLoanId, _propertyTypeId, _propertyPurchaseValue, _propertyCityId, _propertyCity, _propertyDistrict, _propertyState,_pincode,_addressLine1,_addressLine2,_loanType, _userId, _userId);
        SET _customerLoanPropertyDetailId = LAST_INSERT_ID();
        INSERT INTO loancompletescreenhistory(customerLoanId,isCompleted,completeScreen) VALUES(_customerLoanId, false, 3);
        END IF;
	IF(_loanType = 'Bank Transfer') THEN
    IF _customerLoanTransferPropertyDetailId > 0 THEN
       UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting , approxDate = _approxDate , topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI, bankId =_bankId ,modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerLoanTransferPropertyDetailId ;
    ELSE 
       INSERT INTO customerloantransferpropertydetails(customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy, modifiedBy) 
	   VALUES(_customerLoanId, _loanAmountTakenExisting, _approxDate, _topupAmount, _approxCurrentEMI, _bankId,_userId, _userId);
	   SET _customerLoanTransferPropertyDetailId = LAST_INSERT_ID();
	END IF;
    END IF;
		
        SELECT  _customerLoanPropertyDetailId as customerLoanPropertyDetailId,_customerLoanTransferPropertyDetailId as customerLoanTransferPropertyDetailId;

END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCustomerLoanRejectionReson`(IN _id INT,IN _customerLoanId INT,IN _reason TEXT,IN _userId INT)
BEGIN
	IF(_id = 0) THEN
		INSERT INTO customerloanrejectionreason (customerLoanId,reason,createdBy,modifiedBy) VALUES (_customerLoanId,_reason,_userId,_userId);
		INSERT INTO customerloanstatushistory (customerloanId,loanStatusId,transactionDate,createdBy,modifiedBy) VALUES (_customerLoanId,14,CURRENT_TIMESTAMP(),_userId,_userId);
        UPDATE customerloans SET statusId = 14 WHERE id = _customerLoanId;
	ELSE
		UPDATE customerloanrejectionreason SET reason = _reason,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
    END IF;
END$$
DELIMITER ;



DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateFaq`(IN _id INT,IN _faqTypeId INT,IN _faqCategoryId INT,IN _question TEXT,IN _answer TEXT,IN _userId INT)
BEGIN
	IF(_id = 0) THEN
		INSERT INTO faqs (faqCategoryId,faqType,question,answer,createdBy,modifiedBy) VALUES (_faqCategoryId,_faqTypeId,_question,_answer,_userId,_userId);
	ELSE
		UPDATE faqs SET faqCategoryId = _faqCategoryId,faqType = _faqTypeId,question = _question,answer = _answer,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
    END IF;
END$$
DELIMITER ;






DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateFaqCategories`(IN _categoryId INT,IN _categoryName VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
    IF (_categoryId = 0) THEN
	IF 	EXISTS(SELECT 1 FROM faqcategories) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(categoryName) FROM faqcategories WHERE isDelete =0;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getFaqCategories: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getFaqCategories;
					END IF;
					IF _existName = lower(_categoryName) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			INSERT INTO faqcategories (categoryName,createdBy,modifiedBy) VALUES (_categoryName,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO faqcategories (categoryName,createdBy,modifiedBy) VALUES (_categoryName,_userId,_userId);
	END IF;
    ELSE 
    IF 	EXISTS(SELECT 1 FROM faqcategories) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(categoryName) FROM faqcategories WHERE isDelete =0 AND id != _categoryId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getFaqCategories: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getFaqCategories;
					END IF;
					IF _existName = lower(_categoryName) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE faqcategories SET categoryName = _categoryName,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _categoryId;
		END IF;
	ELSE
		UPDATE faqcategories SET categoryName = _categoryName,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _categoryId;
	END IF;
    END IF;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateHomeLoanBasicDetail`(IN _customerLoanId INT,IN _motherName VARCHAR(200),IN _fatherContactNo VARCHAR(200) ,IN _userId INt, IN _customerId INT, IN _fullName VARCHAR(200), IN _birthdate DATETIME
, IN  _maritalStatusId INT, IN _panCardNo VARCHAR(20),IN _loanAmount INT,IN _serviceId INT,IN _partnerId INT,IN _residentTypeId INT,IN _rentAmount INT,IN _valueOfProperty INT,IN _customerloancurrentresidentdetailId INT,IN _currentUserId INT,IN _loanType VARCHAR(200))
BEGIN
	IF _customerId>0 THEN
		SET @UpdateQuery = "";
        SET @SetStatement = "";
        
        SET @UserUpdateQuery = "";
        SET @UserSetStatement = "";
        
        SET @UpdateQuery =  "UPDATE customers SET modifiedDate = '";
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
        
        SET @UserUpdateQuery =  "UPDATE users SET modifiedDate = '";
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, CURRENT_TIMESTAMP(),"'");
		
        IF _fullName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", fullName = '",_fullName,"'");
            SET @UserSetStatement = CONCAT_WS('', @UserSetStatement, ", fullName = '",_fullName,"'");
        END IF;
        
        IF _birthdate IS NOT NULL THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", birthdate = '",_birthdate,"'");
        END IF;
        
        IF _panCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", panCardNo = '",_panCardNo,"'");
        END IF;
        
        IF _maritalStatusId != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", maritalStatusId = ",_maritalStatusId);
        END IF;
        
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerId);
        PREPARE stmt FROM @UpdateQuery;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
    
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, @UserSetStatement," WHERE id = ",_currentUserId);
        
        PREPARE stmt_user FROM @UserUpdateQuery;
		EXECUTE stmt_user;
		DEALLOCATE PREPARE stmt_user;
        IF _customerLoanId != '' THEN
			UPDATE customerloans SET motherName = _motherName,customerId= _customerId,serviceId = _serviceId, fatherContactNo = _fatherContactNo,loanAmount = _loanAmount, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(),loanType = _loanType WHERE id = _customerLoanId;
        ELSE 
			INSERT INTO customerloans (motherName,fatherContactNo,customerId,serviceId,loanAmount,createdBy,modifiedBy,loanType) VALUES (_motherName,_fatherContactNo,_customerId,_serviceId,_loanAmount,_userId,_userId,_loanType);
			IF _partnerId>0 THEN
			INSERT INTO partnerscustomerloans(customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(_customerLoanId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
            SET _customerLoanId = LAST_INSERT_ID();
        END IF;
		IF _customerloancurrentresidentdetailId >0 THEN
		UPDATE customerloancurrentresidentdetails SET customerLoanId = _customerLoanId, residentTypeId = _residentTypeId, rentAmount = _rentAmount, valueOfProperty = _valueOfProperty
        , modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _customerloancurrentresidentdetailId;
    ELSE
		INSERT INTO customerloancurrentresidentdetails(customerLoanId, residentTypeId, rentAmount, valueOfProperty, createdBy, modifiedBy) 
        VALUES(_customerLoanId, _residentTypeId, _rentAmount, _valueOfProperty, _userId, _userId);
		SET _customerloancurrentresidentdetailId = LAST_INSERT_ID();
    END IF;
        SELECT _customerLoanId as customerLoanId,_customerloancurrentresidentdetailId as customerloancurrentresidentdetailId ;
END IF;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateHomeLoanEmploymentDetail`(IN _customerloanemploymentdetailId INT, IN _customerLoanId INT, IN _monthlyIncome DECIMAL(15,2)
, IN _otherIncome DECIMAL(15,2), IN _companyTypeId INT, IN _companyName VARCHAR(100), IN _companyAddressId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _officePincode VARCHAR(8), IN _designationId INT, IN _designation VARCHAR(100), IN _employmentNatureId INT
, IN _employmentServiceTypeId INT, IN _currentCompanyExperience DECIMAL(5,2), IN _experienceInProfession DECIMAL(5,2), IN _employmentTypeId INT, IN _industryTypeId INT, IN _userId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    
    UPDATE customerloans SET employmentTypeId = _employmentTypeId WHERE id = _customerLoanId;
    
	IF _customerloanemploymentdetailId>0 THEN
    -- Update
		IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId, modifiedDate=CURRENT_TIMESTAMP()
            , modifiedBy=_userId WHERE id = _companyAddressId;
		ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
			SET _companyAddressId = LAST_INSERT_ID();
        END IF;
		IF _companyAddressId>0 THEN
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _customerloanId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerloanId = ",_customerloanId);
			END IF;                
			IF _monthlyIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
			END IF;                
			IF _otherIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", otherIncome = ",_otherIncome);
			END IF;
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;
			IF _companyName!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
			END IF;
			IF _companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",_companyAddressId);
			END IF;
			IF _officePincode!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", officePincode = '",_officePincode,"'");
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designationId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = ",_designation);
			END IF;
			IF _employmentNatureId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentNatureId = ",_employmentNatureId);
			END IF;
            IF _industryTypeId  >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", industryTypeId = ",_industryTypeId );
			END IF;
			IF _employmentServiceTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentServiceTypeId = ",_employmentServiceTypeId);
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			IF _experienceInProfession >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", experienceInProfession = ",_experienceInProfession);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerloanemploymentdetailId);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		END IF; 
    ELSE
    -- Insert
    INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
    VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
    SET _companyAddressId = LAST_INSERT_ID();
    
    INSERT customerloanemploymentdetails(customerLoanId, monthlyIncome, otherIncome, companyTypeId, companyName, companyAddressId, officePincode, cityId, designationId, designation
    , employmentNatureId,industryTypeId , employmentServiceTypeId, currentCompanyExperience, experienceInProfession, createdBy, modifiedBy) VALUES(_customerLoanId, _monthlyIncome, _otherIncome, _companyTypeId
    , _companyName, _companyAddressId, _pincode, _cityId, _designationId, _designation, _employmentNatureId,_industryTypeId ,_employmentServiceTypeId, _currentCompanyExperience, _experienceInProfession, _userId, _userId);
	SET _customerloanemploymentdetailId = LAST_INSERT_ID();

    END IF;
    UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId = _customerLoanId;
     SELECT _customerloanemploymentdetailId as customerloanemploymentdetailId, _companyAddressId as companyAddressId;
END$$
DELIMITER ;



DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateLoanBasicDetail`(IN _fullName VARCHAR(200),IN _birthDate DATE,IN _panCardNo VARCHAR(20),IN _customerId INT, IN _alternativeContactNo VARCHAR(15), IN _gender VARCHAR(15), IN _maritalStatusId INT,
IN _motherName VARCHAR(100), IN _fatherName VARCHAR(15), IN _userId INT, IN _customerLoanSpouseId INT, IN _spouseName VARCHAR(100), IN _spouseContactNo VARCHAR(45),IN _customerLoanId INT,IN _serviceId INT,IN _loanAmount DECIMAL(15,2),IN _tenureId INT,IN _currentAddressId INT,IN _addressTypeId INT,IN _label VARCHAR(200),
IN _addressLine1 TEXT,IN _addressLine2 TEXT,IN _pincode VARCHAR(10),IN _cityId INT,IN _city VARCHAR(200),IN _district VARCHAR(200),IN _state VARCHAR(200),
IN _loanAmountTakenExisting DECIMAL(15,2),IN  _approxDate VARCHAR(200),IN _topupAmount DECIMAL(15,2),IN _approxCurrentEMI DECIMAL(15,2),IN _bankId INT,IN _loanType VARCHAR(40))
BEGIN
	DECLARE customerLoanspouseId INT DEFAULT 0;
    DECLARE currentAddressId INT DEFAULT 0;
	DECLARE finished INT DEFAULT 0;
    DECLARE _existId INT DEFAULT 0;
	UPDATE customers SET fullName=_fullName,birthDate =_birthDate,panCardNo = _panCardNo,alternativeContactNo=_alternativeContactNo, gender=_gender, maritalStatusId=_maritalStatusId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId 
    WHERE id = _customerId;
    IF _customerLoanId > 0 THEN
	UPDATE customerloans SET motherName=_motherName, fatherName=_fatherName,loanAmount = _loanAmount,tenureId = _tenureId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId,loanType = _loanType WHERE id = _customerLoanId;
   
    ELSE 
    INSERT INTO customerloans (serviceId,customerId,motherName,fatherName,loanAmount,tenureId,createdBy,modifiedBy,loanType) VALUES (_serviceId,_customerId,_motherName,_fatherName,_loanAmount,_tenureId,_userId,_userId,_loanType);
   
    SET _customerLoanId = LAST_INSERT_ID();
    INSERT INTO loancompletescreenhistory (customerLoanId,isCompleted,completeScreen) VALUES (_customerLoanId,false,1);

	END IF;
  
             IF _loanType != 'New' THEN
			IF 	EXISTS(SELECT 1 FROM customerloantransferpropertydetails) THEN
             
		BEGIN
       
			DECLARE cur_checkexist cursor for select id FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				gettransfercustomerloan: LOOP
					FETCH cur_checkexist INTO _existId;
					IF finished = 1 THEN 
                   
						LEAVE gettransfercustomerloan;
					END IF;
                   
					IF _existId THEN
                    
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting,approxDate = _approxDate,topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI,bankId = _bankId,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE customerLoanId  = _customerLoanId;	
		ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
        ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdby,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
	END IF;
    SET @customerLoanspouseId = 0;
    IF _customerLoanSpouseId>0 THEN
		UPDATE customerloanspouses SET name=_spouseName, contactNo=_spouseContactNo, modifiedDate=CURRENT_TIMESTAMP() , modifiedBy=_userId WHERE id =_customerLoanSpouseId;
        SET @customerLoanspouseId = _customerLoanSpouseId;
    ELSE
		IF(_spouseName != "") THEN
		INSERT INTO customerloanspouses(customerLoanId,name,contactNo,createdBy,modifiedBy) VALUES(_customerLoanId, _spouseName, _spouseContactNo, _userId, _userId);
        SET @customerLoanspouseId = LAST_INSERT_ID();
        END IF;
	END IF;
    IF _currentAddressId > 0 THEN 
		UPDATE customeraddresses SET addressTypeId = _addressTypeId,label = _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,pincode = _pincode,cityId = _cityId,city = _city,district = _district,state = _state,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _currentAddressId;
		 SET @currentAddressId = _currentAddressId;
    ELSE 
		INSERT INTO customeraddresses (customerId,addressTypeId,label,addressLine1,addressLine2,pincode,cityId,city,district,state,createdBy,modifiedBy) VALUES (_customerId,_addressTypeId,_label,_addressLine1,_addressLine2,_pincode,_cityId,_city,_district,_state,_userId,_userId);
		SET @currentAddressId = LAST_INSERT_ID();
    END IF;
    
    SELECT _customerLoanId as customerLoanId,@customerLoanspouseId as customerLoanspouseId,@currentAddressId as currentAddressId;
END$$
DELIMITER ;



DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateLoanEmploymentDetail`(IN _customerloanId INT, IN _customerLoanEmploymentId INT, IN _employmentTypeId INT, IN _monthlyIncode DECIMAL(15,2)
, IN _companyName VARCHAR(100),IN _companyTypeId INT, IN _officeCode VARCHAR(8), IN _serviceId INT, IN _customerId INT, IN _userId INT,IN _companyAddressId INT, IN _addressTypeId INT
, IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _city VARCHAR(200), IN _district VARCHAR(200)
, IN _state VARCHAR(200), IN _designation VARCHAR(100), IN _currentCompanyExperience DECIMAL(5,2),IN _officeEmailId VARCHAR(200))
BEGIN
	UPDATE customerloans SET employmentTypeId=_employmentTypeId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerloanId;
    UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId = _customerloanId;
    IF(_customerLoanEmploymentId > 0) THEN
		UPDATE customerloanemploymentdetails SET monthlyIncome=_monthlyIncode, companyName=_companyName,companyTypeId = _companyTypeId, officePincode=_officeCode,cityId = _cityId,designation  = _designation,currentCompanyExperience = _currentCompanyExperience, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId
        WHERE id = _customerLoanEmploymentId;
        SET @customerLoanEmploymentId = _customerLoanEmploymentId;
    ELSE
		INSERT INTO customerloanemploymentdetails(customerloanId, monthlyIncome, companyName,companyTypeId, officePincode,cityId,designation,currentCompanyExperience, createdBy, modifiedBy) VALUES(_customerLoanId, _monthlyIncode, _companyName,_companyTypeId
        , _officeCode,_cityId,_designation,_currentCompanyExperience, _userId, _userId);
        SET @customerLoanEmploymentId = LAST_INSERT_ID();
	END IF;
	IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId
            , city=_city, district=_district, state=_state, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _companyAddressId;
             SET @companyAddressId = _companyAddressId;
	ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
            SET @companyAddressId = LAST_INSERT_ID();
            UPDATE customerloanemploymentdetails SET companyAddressId =@companyAddressId WHERE id = @customerLoanEmploymentId;
	END IF;
    UPDATE users SET email = _officeEmailId WHERE id = (SELECT userId FROM customers WHERE id = _customerId);
    SELECT @companyAddressId as companyAddressId,@customerLoanEmploymentId as customerLoanEmploymentId;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateOtherLoanDetail`(IN _id INT,IN _customerUserId INT, IN _serviceId INT, IN _serviceTypeId INT, IN _fullName TEXT,IN _birthdate DATETIME, IN _panCardNo VARCHAR(20),IN _aadhaarCardNo VARCHAR(20), IN _ContactNo VARCHAR(15),  IN _email VARCHAR(256), IN _employmentTypeId INT, IN _monthlyIncome decimal(15,2), IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _city VARCHAR(200), IN _district VARCHAR(200)
, IN _state VARCHAR(200),IN _userId INT)
BEGIN
	IF _id > 0 THEN
		UPDATE customerotherloans SET userId = _customerUserId,serviceId = _serviceId,fullName = _fullName,birthDate = _birthDate,panCardNo = _panCardNo,aadhaarCardNo = _aadhaarCardNo,contactNo = _contactNo,email = _email,employmentTypeId = _employmentTypeId,monthlyincome = _monthlyIncome,label = _label,addressline1 = _addressline1,addressline2 = _addressline2,pincode = _pincode,cityId = _cityId,city = _city,distict = _district,state = _state,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
    ELSE
		INSERT INTO customerotherloans(userId, serviceId, serviceTypeId, fullName, birthdate, panCardNo, aadhaarCardNo, contactNo, email, employmentTypeId, monthlyincome, label, addressline1, addressline2, pincode, cityId, city, distict, state,  createdBy, modifiedBy) 
		VALUES(_customerUserId, _serviceId, _serviceTypeId, _fullName, _birthdate, _panCardNo, _aadhaarCardNo, _ContactNo, _email, _employmentTypeId,  _monthlyIncome, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state , _userId, _userId );
		SET @insertId = LAST_INSERT_ID();    
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdatePartnerCommission`(IN _partnerIds VARCHAR(200), IN _commissionTypeId INT, IN _bankId INT, IN _serviceId INT
, IN _commission DECIMAL(5,2), IN _commissionTemplateId INT, IN _userId INT)
BEGIN
	DECLARE cBankLoanCommissionId INT DEFAULT 0;
	DECLARE cBankLoanPartnerCommissionId INT DEFAULT 0;
    DECLARE finished INT DEFAULT 0;
    DECLARE front TEXT;
    DECLARE frontlen INT;
   DECLARE TempValue TEXT;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_bank_loan_commission CURSOR FOR SELECT bankloancommissions.id FROM bankloancommissions WHERE bankloancommissions.bankId = _bankId AND bankloancommissions.serviceId = _serviceId;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
            OPEN  cur_bank_loan_commission;
				cur_bank_loan_commission_loop: LOOP
					FETCH cur_bank_loan_commission INTO cBankLoanCommissionId;
					IF finished = 1 THEN
						LEAVE cur_bank_loan_commission_loop;
					END IF;
                    
                END LOOP cur_bank_loan_commission_loop;
			CLOSE cur_bank_loan_commission;
            -- SELECT cBankLoanCommissionId, _bankLoanPartnerCommissionId;
            IF cBankLoanCommissionId >0 THEN
				
				iterator:
					LOOP  
						IF LENGTH(TRIM(_partnerIds)) = 0 OR _partnerIds IS NULL THEN
							LEAVE iterator;
						END IF;
                      	SET front = SUBSTRING_INDEX(_partnerIds,',',1);
						SET frontlen = LENGTH(front);
						SET TempValue = TRIM(front);
                        SET cBankLoanPartnerCommissionId = 0;
                        BEGIN
							DECLARE partnerCommission CURSOR FOR SELECT id FROM bankloanpartnercommissions WHERE bankId = _bankId AND serviceId = _serviceId  AND partnerId = TempValue; -- AND commissionTypeId = _commissionTypeId
							DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
							OPEN  partnerCommission;
                            partnerCommission: LOOP
							FETCH partnerCommission INTO cBankLoanPartnerCommissionId;
							IF finished = 1 THEN
								LEAVE partnerCommission;
							END IF;
							END LOOP partnerCommission;
						CLOSE partnerCommission;
                        END;
                         IF cBankLoanPartnerCommissionId > 0 THEN
                        	UPDATE bankloanpartnercommissions SET partnerId=TempValue, bankLoanCommissionId=cBankLoanCommissionId, commissionTypeId=_commissionTypeId, bankId=_bankId, serviceId=_serviceId
							, commissionTemplateId = _commissionTemplateId, commission=_commission, modifiedBy=_userId, modifiedDate=CURRENT_TIMESTAMP() WHERE id = cBankLoanPartnerCommissionId;
                            SET _partnerIds = INSERT(_partnerIds,1,frontlen + 1,'');
                        ELSE
                       		INSERT INTO bankloanpartnercommissions(partnerId, bankLoanCommissionId, commissionTypeId, bankId, serviceId, commissionTemplateId, commission, createdBy, modifiedBy) 
							VALUES(TempValue, cBankLoanCommissionId, _commissionTypeId, _bankId, _serviceId, _commissionTemplateId, _commission, _userId, _userId);
							SET _partnerIds = INSERT(_partnerIds,1,frontlen + 1,'');
                        END IF;
					END LOOP;
				ELSE
					SELECT 'Bank Loan Commision is Not Set' AS message;
                END IF;
			END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateProducts`(IN _id INT, IN _name VARCHAR(200), IN _description TEXT, IN _imageUrl TEXT, IN _coin DECIMAL(15,3), IN _duration VARCHAR(50), IN _userId INT)
BEGIN
	IF _id >0 THEN
		UPDATE products SET name = _name, description = _description, imageUrl = _imageUrl, coin = _coin, duration = _duration, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _id;
    ELSE 
		INSERT INTO products(name, description, imageUrl, coin, duration, createdBy, modifiedBy) VALUES(_name, _description, _imageUrl, _coin, _duration, _userId, _userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateRewardCoin`(IN _id INT, IN _rewardTypeId INT, IN _rewardCoin DECIMAL(15,3), IN _minLoanFile INT, IN _maxLoanFile INT, IN _userId INT,IN _roleIds VARCHAR(100),IN _isScratchCard BOOLEAN)
BEGIN
        IF _id >0 THEN
                UPDATE rewardcoin SET rewardTypeId = _rewardTypeId, rewardCoin = _rewardCoin, minLoanFile = _minLoanFile, maxLoanFile = _maxLoanFile,roleIds = _roleIds,isScratchCard = _isScratchCard, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _id;
    ELSE
                INSERT INTO rewardcoin(rewardTypeId, rewardCoin, minLoanFile, maxLoanFile,roleIds,isScratchCard, createdBy, modifiedBy) VALUES(_rewardTypeId, _rewardCoin, _minLoanFile, _maxLoanFile,_roleIds,_isScratchCard, _userId, _userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertUsers`(IN _fullName TEXT, IN _gender VARCHAR(20), IN _email VARCHAR(256),IN _contactNo VARCHAR(20), IN _password TEXT, IN _profilePicUrl TEXT, IN _userId INT, IN _isDisabled boolean,IN _permissionGroupId INT, IN _roleId INT,IN _designation VARCHAR(200))
BEGIN
	INSERT INTO users(fullName, gender, email,contactNo, password, profilePicUrl, isDisabled,permissionGroupId, createdBy, modifiedBy,designation) VALUES(_fullName, _gender, _email,_contactNo, _password, _profilePicUrl, _isDisabled,_permissionGroupId, _userId, _userId,_designation);
    SET @userId = LAST_INSERT_ID();
    INSERT INTO userroles(userId, roleId, createdBy, modifiedBy) VALUES(@userId, _roleId, _userId, _userId);
    SELECT @userId as userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertVisitingCard`(IN _roleIds VARCHAR(100),IN _template TEXT,IN _dynamicFields VARCHAR(255), IN _location TEXT,IN _userId INT)
BEGIN
	DECLARE visitingCardId INT DEFAULT 0;
	DECLARE front TEXT;
    DECLARE frontlen INT;
    DECLARE TempValue TEXT;
	INSERT INTO visitingcards (template,dynamicFields,location,createdBy,modifiedBy) VALUES (_template,_dynamicFields,_location,_userId,_userId);
    SET visitingCardId = LAST_INSERT_ID();
   	iterator:
	LOOP  
    IF LENGTH(TRIM(_roleIds)) = 0 OR _roleIds IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_roleIds,',',1);
    SET frontlen = LENGTH(front);
    SET TempValue = TRIM(front);
	INSERT INTO rolesvisitingcards (visitingCardId,roleId,createdBy,modifiedBy) VALUES (visitingCardId,TempValue,_userId,_userId);
    SET _roleIds = INSERT(_roleIds,1,frontlen + 1,'');
    END LOOP;
    
    SELECT * FROM visitingcards WHERE id = visitingCardId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminLeadAssignToPartner`(IN _leadId INT,IN _partnerId INT,IN _userId INT,IN _assignById INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
    
	BEGIN
			DECLARE cur_checkexist cursor for select id FROM leadstatushistory WHERE leadId = _leadId AND leadStatusId = 3;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getHistory: LOOP
					FETCH cur_checkexist INTO fetchedId;
					IF finished = 1 THEN 
						LEAVE getHistory;
					END IF;
					IF (fetchedId) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist != 1 THEN		
			INSERT INTO leadstatushistory (leadId,leadStatusId,transactionDate,createdBy,modifiedBy) VALUES (_leadId,3,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE leads SET assignedById = _assignById,assignToPartnerId = _partnerId,assignOn = CURRENT_TIMESTAMP(),leadStatusId = 3, modifiedBY = _userId WHERE id = _leadId;
		ELSE 
		   UPDATE leads SET assignedById = _assignById,assignToPartnerId = _partnerId,assignOn = CURRENT_TIMESTAMP(),leadStatusId = 3,modifiedBY = _userId WHERE id = _leadId;
		END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminLoanAgainstCollteral`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	IF _id > 0 THEN 
		UPDATE loanagainstcollteral SET name = _name,modifiedBy = _userId WHERE id = _id;
	ELSE 
		INSERT INTO loanagainstcollteral (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminLogin`(IN _email VARCHAR(256), IN _password TEXT, IN _sessionToken TEXT, IN _appId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cIsDisabled INT DEFAULT 1;
    DECLARE cRoleId INT DEFAULT 0;
    DECLARE cRoleName VARCHAR(45) DEFAULT NULL;
   
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
	BEGIN
    
		DECLARE cur_user CURSOR FOR SELECT users.id, users.isDisabled, roles.id as roleId, roles.name as roleName FROM users 
									INNER JOIN userroles ON userroles.userId = users.id 
									INNER JOIN roles ON roles.id = userroles.roleId
									WHERE users.email = _email AND password = _password AND userroles.roleId IN(1,7,10);
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_user;
			cur_user_loop: LOOP
				FETCH cur_user INTO cUserId, cIsDisabled, cRoleId, cRoleName;
                IF finished = 1 THEN
					LEAVE cur_user_loop;
				END IF;
                IF cUserId>0 AND cRoleId >0 AND cIsDisabled=0 THEN
					INSERT INTO usersessions(sessionToken, appId, expireAt, userId) VALUES(_sessionToken, _appId, TIMESTAMPADD(DAY,60,CURRENT_TIMESTAMP()), cUserId);
                ELSE 
                    LEAVE cur_user_loop;
                END IF;
            END LOOP cur_user_loop;
		CLOSE cur_user;
		IF cIsDisabled = 0 THEN
			SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = cUserId;
            SELECT users.* FROM users INNER JOIN userroles ON userroles.userId = users.id WHERE users.email = _email AND password = _password AND userroles.roleId IN(1,7,10) AND users.isDelete = 0 AND users.isActive = 1;
		ELSE
			SELECT 'User Not Verified' as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminPayoutRelease`(IN _userId INT,IN _partnerCommissionId INT)
BEGIN
	/*UPDATE partnercommission SET commission = (_partnerCommission - _commission),modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _partnerCommissionId;
    INSERT INTO partnercommissionhistory (partnerCommissionId,partnerId,commission,type,createdBy,modifiedBy) VALUES (_partnerCommissionId,_partnerId,_commission,'OUT',_userId,_userId);*/
    
    UPDATE partnercommissionhistory  SET isReleased = true,releaseDate  = CURRENT_TIMESTAMP(),modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _partnerCommissionId;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminProductActiveInactive`(IN _id INT, IN _userId INT)
BEGIN
	UPDATE products SET isActive = !isActive, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminRemoveTraining`(IN _id INT)
BEGIN
	DELETE FROM trainings WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminRemoveTrainingCategroy`(In _id INT)
BEGIN
	DELETE FROM triningcategories WHERE id = _id OR parentId = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminRemoveUser`(IN _id INT,IN _userId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE _customerloans VARCHAR(200) DEFAULT '';
    BEGIN
		DECLARE cur_checkexist cursor for select id FROM customerloans WHERE assignRMId = _id;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
				getcustomerloans: LOOP
					FETCH cur_checkexist INTO _customerloans;
					IF finished = 1 THEN 
						LEAVE getcustomerloans;
					END IF;
						UPDATE customerloanstatushistory SET loanStatusId=1,modifiedDate =current_timestamp(),modifiedBy = _userId WHERE  customerloanId = _customerloans;
					END LOOP getcustomerloans;
			CLOSE cur_checkexist;
END;
	UPDATE customerloans SET assignRMId = null,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE assignRMId = _id;
	DELETE FROM userroles WHERE userId = _id;
	DELETE FROM users WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateAddressType`(IN _id INT,IN _name VARCHAR(200),IN _description TEXT,IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM addresstypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM addresstypes WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getAddressTypes: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getAddressTypes;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE addresstypes SET name = _name,description = _description,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE addresstypes SET name = _name,description = _description,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBadges`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM badges) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM badges WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBadges: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBadges;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE badges SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE badges SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBank`(IN _id INT,IN _name VARCHAR(255),IN _description VARCHAR(700),IN _headquarters VARCHAR(200),IN _bankCode VARCHAR(100),IN _userId INT,IN _minAge INT,IN _maxAge INT,IN _bankLogo TEXT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM banks) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM banks WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBanks: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBanks;
					END IF;
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE banks SET name = _name,description = _description,headquarters = _headquarters,bankCode = _bankCode,bankLogo = _bankLogo,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId,minAge = _minAge,maxAge = _maxAge WHERE id = _id;
		END IF;
	ELSE
		UPDATE banks SET name = _name,description = _description,headquarters = _headquarters,bankCode = _bankCode,bankLogo = _bankLogo,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId,minAge = _minAge,maxAge = _maxAge WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBankLoan`(IN _id INT,IN _bankId INT,IN _serviceId INT,IN _loanName VARCHAR(100),IN _userId INT)
BEGIN
	UPDATE bankloans SET bankId = _bankId,serviceId = _serviceId, loanName = _loanName,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id =_id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBusinessAnnualProfits`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM businessannualprofits) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM businessannualprofits WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessAnnualProfits: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessAnnualProfits;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE businessannualprofits SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE businessannualprofits SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBusinessAnnualSale`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM businessannualsales) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM businessannualsales WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessAnnualSales: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessAnnualSales;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE businessannualsales SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE businessannualsales SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBusinessExperience`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM businessannualprofits) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM businessexperience WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessExperience: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessExperience;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE businessexperience SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE businessexperience SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateBusinessNature`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM businessnatures) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM businessnatures WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessNatures: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessNatures;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE businessnatures SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE businessnatures SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateCoApplicantRelation`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM coapplicantrelations) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM coapplicantrelations WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getCoApplicantRelations: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getCoApplicantRelations;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE coapplicantrelations SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE coapplicantrelations SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateContactRequestStatus`(IN _id INT,IN _status VARCHAR(200),IN _userId INT)
BEGIN
	UPDATE contacts SET status = _status,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateDocumentMaster`(IN _id INT, IN _name VARCHAR(200),IN _maxSize VARCHAR(40), IN _userId INT)
BEGIN
	UPDATE documentmasters SET name = _name,maxSize = _maxSize, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP()  WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateEmploymentNature`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM employmentnatures) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM employmentnatures WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getEmploymentNatures: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getEmploymentNatures;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE employmentnatures SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE employmentnatures SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateEmploymentServiceType`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM employmentservicetypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM employmentservicetypes WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getEmploymentServiceTypes: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getEmploymentServiceTypes;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE employmentservicetypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE employmentservicetypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateEmploymentType`(IN _id INT,IN _name VARCHAR(100),IN _parentId INT,IN _userId INT)
BEGIN
	IF _parentId > 0 THEN
		UPDATE employmenttypes SET name = _name,parentId=_parentId,modifiedDate = current_timestamp(),modifiedBy = _userId WHERE id = _id;
	ELSE
		UPDATE employmenttypes SET name = _name,modifiedDate = current_timestamp(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateIndustryType`(IN _id INT,IN _name VARCHAR(200),IN _parentId INT,IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM industrytypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM industrytypes WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getIndustryTypes: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getIndustryTypes;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			IF _parentId > 0 THEN
				UPDATE industrytypes  SET name = _name,parentId = _parentId,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
            ELSE
				UPDATE industrytypes  SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
			END IF;
		END IF;
	ELSE
		IF _parentId > 0 THEN
			UPDATE industrytypes  SET name = _name,parentId = _parentId,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		ELSE
			UPDATE industrytypes  SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateLoanAgainstColleteral`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM loanagainstcollteral) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM loanagainstcollteral WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getLoanAgainstColletral: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getLoanAgainstColletral;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE loanagainstcollteral SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE loanagainstcollteral SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateLoanAmount`(IN _customerLoanId INT,IN _loanAmount INT,IN _userId INT)
BEGIN
	UPDATE customerloans SET loanAmount=_loanAmount, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerloanId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateLoanStatus`(IN _id INT,IN _status VARCHAR(200),IN _isDataEditable TEXT,IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM loanstatuses) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(status) FROM loanstatuses WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getLoanStatus: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getLoanStatus;
					END IF;                    
					IF _existName = lower(_status) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE loanstatuses SET status = _status,isDataEditable = _isDataEditable,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE loanstatuses SET status = _status,isDataEditable = _isDataEditable,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateMaritalStatus`(IN _id INT,IN _status VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM maritalstatuses) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(status) FROM maritalstatuses WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getMaritalStatus: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getMaritalStatus;
					END IF;                    
					IF _existName = lower(_status) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE maritalstatuses SET status = _status,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE maritalstatuses SET status = _status,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdatePropertyType`(IN _id INT,IN _name VARCHAR(200),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM propertytypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM propertytypes WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getPropertyTypes: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getPropertyTypes;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE propertytypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE propertytypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateResidentType`(IN _id INT,IN _name VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM residenttypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM residenttypes WHERE isDelete =0 AND id != _id;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getResidentTypes: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getResidentTypes;
					END IF;                    
					IF _existName = lower(_name) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as nameExist;				
		ELSE
			UPDATE residenttypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
		END IF;
	ELSE
		UPDATE residenttypes SET name = _name,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateService`(IN _id INT, IN _serviceTypeId INT, IN _displayName VARCHAR(500), IN _description TEXT, IN _iconUrl TEXT, IN _colorCode VARCHAR(45), IN _userId INT)
BEGIN
		UPDATE services SET serviceTypeId = _serviceTypeId, displayName =_displayName, description = _description, colorCode = _colorCode, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
        IF _iconUrl != '' THEN
			UPDATE services SET iconUrl =_iconUrl, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
        END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateServiceEmploymentType`(IN _serviceId INT,IN _employmentTypeId VARCHAR(40),IN _userId INT)
BEGIN
	DECLARE front TEXT;
    DECLARE frontlen INT;
    DECLARE TempValue TEXT;
    DELETE FROM servicesemploymenttypes WHERE serviceId = _serviceId;
    iterator:
	LOOP  
    IF LENGTH(TRIM(_employmentTypeId)) = 0 OR _employmentTypeId IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_employmentTypeId,',',1);
    SET frontlen = LENGTH(front);
    SET TempValue = TRIM(front);
   INSERT INTO servicesemploymenttypes (serviceId,employmentTypeId,createdBy,modifiedBy) VALUES (_serviceId,TempValue,_userId,_userId);
    SET _employmentTypeId = INSERT(_employmentTypeId,1,frontlen + 1,'');
    END LOOP;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateServiceTypeDocuments`(IN _id INT, IN _serviceId INT, IN _documentId INT, IN _displayName VARCHAR(100), IN _documentCount INT, IN _isRequired BOOLEAN,IN _isPdf BOOLEAN, IN _userId INT,IN _employmentTypeId INT,IN _requiredForTransfer TINYINT,IN _requiredForNew TINYINT)
BEGIN
	UPDATE servicetypedocuments SET serviceId = _serviceId, documentId = _documentId, displayName = _displayName, documentCount = _documentCount, isRequired = _isRequired,isPdf = _isPdf,employmentTypeId = _employmentTypeId, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(),isRequiredForTransfer = _requiredForTransfer,isRequiredForNew = _requiredForNew WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateServiceTypes`(IN _id INT, IN _displayName VARCHAR(50), IN _description TEXT, IN _iconUrl TEXT, IN _colorCode VARCHAR(45), IN _userId INT)
BEGIN
	
    UPDATE servicetypes SET displayName =_displayName, description = _description, colorCode = _colorCode, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
	IF _iconUrl != '' THEN
		UPDATE servicetypes SET iconUrl =_iconUrl, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateTraining`(IN _id INT,IN _title VARCHAR(200),IN _url VARCHAR(200),IN _trainingCategoryId INT,IN _userId INT,IN _fileName VARCHAR(255),IN _documentType VARCHAR(45),IN _trainingSubCategoryId INT,IN _trainingAssingUserId TEXT,IN _trainingStatus VARCHAR(200),IN _roleIds VARCHAR(100),IN _completionTime INT)
BEGIN
     DECLARE front TEXT;
    DECLARE frontlen INT;
   DECLARE TempValue TEXT;
	IF _trainingSubCategoryId > 0 THEN
		UPDATE trainings SET title = _title,url = _url,trainingCategoryId = _trainingCategoryId,fileName = _fileName,documentType = _documentType,trainingSubCategoryId = _trainingSubCategoryId, modifiedDate = current_timestamp(),modifiedBy = _userId,assignRole = _roleIds,completionTime = _completionTime WHERE id = _id; 
	ELSE 
		UPDATE trainings SET title = _title,url = _url,trainingCategoryId = _trainingCategoryId,fileName = _fileName,documentType = _documentType,trainingSubCategoryId = null, modifiedDate = current_timestamp(),modifiedBy = _userId,assignRole = _roleIds,completionTime = _completionTime WHERE id = _id; 
	END IF;

   DELETE FROM assignuserstraining WHERE trainingId = _id;
    iterator:
	LOOP  
    IF LENGTH(TRIM(_trainingAssingUserId)) = 0 OR _trainingAssingUserId IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_trainingAssingUserId,',',1);
    SET frontlen = LENGTH(front);
    SET TempValue = TRIM(front);
   INSERT INTO assignuserstraining (trainingId,partnerId,trainingStatus,createdBy,modifiedBy) VALUES (_id,TempValue,_trainingStatus,_userId,_userId);
    SET _trainingAssingUserId = INSERT(_trainingAssingUserId,1,frontlen + 1,'');
    END LOOP;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateTrainingCategory`(IN _id INT,IN _name VARCHAR(100),IN _parentId INT,IN _userId INT)
BEGIN
	IF _parentId > 0 THEN
		UPDATE triningcategories SET name = _name,parentId=_parentId,modifiedDate = current_timestamp(),modifiedBy = _userId WHERE id = _id;
	ELSE
		UPDATE triningcategories SET name = _name,modifiedDate = current_timestamp(),modifiedBy = _userId WHERE id = _id;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateUser`(IN _id INT,IN _fullName TEXT, IN _gender VARCHAR(20), IN _email VARCHAR(256),IN _contactNo VARCHAR(20), IN _password TEXT, IN _profilePicUrl TEXT, IN _userId INT,IN _designation VARCHAR(200),IN _roleId INT)
BEGIN
	UPDATE users SET fullName = _fullName, gender = _gender, email = _email,contactNo = _contactNo, password = _password, profilePicUrl = _profilePicUrl, modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP(),designation = _designation WHERE id = _id;
    UPDATE userroles SET roleId = _roleId,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE userId = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminUpdateVisitingCard`(IN _id INT,IN _roleIds VARCHAR(100),IN _template TEXT,IN _dynamicFields VARCHAR(255), IN _location TEXT,IN _userId INT)
BEGIN
	DECLARE front TEXT;
    DECLARE frontlen INT;
    DECLARE TempValue TEXT;
    DELETE FROM rolesvisitingcards WHERE visitingcardId = _id;
    UPDATE visitingcards SET template = _template,dynamicFields = _dynamicFields, location=_location ,modifiedDate = CURRENT_TIMESTAMP,modifiedBy = _userId WHERE id = _id;
	iterator:
	LOOP  
    IF LENGTH(TRIM(_roleIds)) = 0 OR _roleIds IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_roleIds,',',1);
    SET frontlen = LENGTH(front);
    SET TempValue = TRIM(front);
	INSERT INTO rolesvisitingcards (visitingCardId,roleId,createdBy,modifiedBy) VALUES (_id,TempValue,_userId,_userId);
    SET _roleIds = INSERT(_roleIds,1,frontlen + 1,'');
    END LOOP;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminVerifiedPartner`(IN _id INT,IN userId INT)
BEGIN
	UPDATE partners SET isActive = !isActive WHERE id = _id;
    UPDATE users SET isDisabled = !isDisabled WHERE id = userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `checkContactNoExist`(IN _contactNo Varchar(20))
BEGIN
	SELECT users.id, users.email, roles.name as roleName FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN roles ON roles.id = userroles.roleId
	WHERE users.contactNo = _contactNo AND userroles.roleId = users.currentRoleId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `CheckContactNoExistWithServiceIdForOtherLoanAndOtherService`(IN _contactNo Varchar(20),IN _serviceId INT)
BEGIN
    SELECT customerotherloans.id , customerotherloans.userId  ,customerotherloans.serviceId  FROM customerotherloans 
	WHERE customerotherloans.contactNo = _contactNo AND customerotherloans.serviceId = _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerAcceptOffer`(IN _id INT,IN _customerloanId INT,IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	UPDATE customerloanoffers SET status = 'ACCEPT',modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
    UPDATE customerloanoffers SET status = 'REJECTED',modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id != _id AND customerLoanId = _customerloanId;
  		BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 13;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getHistory: LOOP
					FETCH cur_checkexist INTO fetchedId;
					IF finished = 1 THEN 
						LEAVE getHistory;
					END IF;
					IF (fetchedId) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist != 1 THEN		
			INSERT INTO customerloanstatushistory (customerloanId,loanStatusId,transactionDate,createdBy,modifiedBy) VALUES (_customerLoanId,13,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE customerloans SET statusId = 13 WHERE id = _customerLoanId;
        END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerCheckContactNoExist`(IN _contactNo Varchar(20))
BEGIN
	SELECT users.id, users.email FROM users 
    INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN roles ON roles.id = userroles.roleId
	INNER JOIN customers ON customers.userId = users.Id
	WHERE users.contactNo = _contactNo AND users.currentRoleId = 2;

END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerCheckContactNoExistForCreditCard`(IN _contactNo Varchar(20))
BEGIN
SELECT users.id, users.email,customercreditcards.id, customercreditcards.statusId  FROM users 
    INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN roles ON roles.id = userroles.roleId
	INNER JOIN customers ON customers.userId = users.Id
    LEFT JOIN customercreditcards ON customercreditcards.customerId = customers.Id
	WHERE users.contactNo = _contactNo  AND users.currentRoleId = 2 AND  customercreditcards.customerId IN ( SELECT id FROM customers where contactNo = _contactNo);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerCheckContactNoExistWithServiceId`(IN _contactNo Varchar(20),IN _serviceId INT)
BEGIN
SELECT users.id, users.email,customerloans.id, customerloans.statusId, customerloans.serviceId  FROM users 
    INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN roles ON roles.id = userroles.roleId
	INNER JOIN customers ON customers.userId = users.Id
    LEFT JOIN customerloans ON customerloans.customerId = customers.Id
	WHERE users.contactNo = _contactNo AND users.currentRoleId = 2 AND customerloans.serviceId = _serviceId AND customerloans.isDelete = 0;
    
    SELECT customerloanstatushistory.transactionDate FROM customerloanstatushistory LEFT JOIN customerloans ON customerloanstatushistory.customerLoanId = customerloans.id LEFT JOIN customers On customers.id = customerloans.customerId WHERE customerloanstatushistory.loanstatusId = 14 AND customers.contactNo = _contactNo AND customerloans.serviceId = _serviceId ORDER BY customerloans.id DESC limit 1;
	
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetBanners`(IN _roleId INT)
BEGIN
	SELECT * FROM banners WHERE isActive = 1 AND (fromDate <= CURRENT_TIMESTAMP() || fromDate IS NULL) AND (toDate >= CURRENT_TIMESTAMP() || toDate IS NULL) AND isDelete = 0 AND roleId = _roleId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetBusinessLoanByCustomerLoanId`(IN _customerId INT, IN _customerLoanId INT)
BEGIN

	SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
    , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
	FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN customers ON customers.userId = users.id 
	LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
	WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2) AND customeraddresses.addressTypeId = 1;
    
    SELECT customerloans.*, employmenttypes.name as employmentType, services.displayName as displayName, services.name as serviceName FROM customerloans 
	LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
	LEFT JOIN services ON  services.id = customerloans.serviceId
	WHERE customerloans.id = _customerLoanId;
	
	SELECT customerloandocuments.*, documentmasters.name as documentName, servicetypedocuments.isPdf FROM customerloandocuments 
	LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
	LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
	WHERE customerloandocuments.customerloanId = _customerLoanId;
	
	SELECT customerloanbusinessdetails.*, companytypes.name as companyType, industrytypes.name as industryTypes,businessexperience.name as businessExperience
	, businessnatures.name as businessNatures, businessannualprofits.name businessAnnualProfits, banks.name banks FROM customerloanbusinessdetails
	LEFT JOIN companytypes ON companytypes.id = customerloanbusinessdetails.companyTypeId
	LEFT JOIN industrytypes ON industrytypes.id = customerloanbusinessdetails.industryTypeId
	LEFT JOIN businessexperience ON businessexperience.id = customerloanbusinessdetails.businessExperienceId
	LEFT JOIN businessnatures ON businessnatures.id = customerloanbusinessdetails.businessNatureId
	LEFT JOIN businessannualprofits ON businessannualprofits.id = customerloanbusinessdetails.businessAnnualProfitId
	LEFT JOIN banks ON banks.id = customerloanbusinessdetails.primaryBankId
	WHERE customerloanbusinessdetails.customerloanId = _customerLoanId;
	
	SELECT customerloancurrentresidentdetails.*, residenttypes.name residentType FROM customerloancurrentresidentdetails
	LEFT JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId WHERE customerloancurrentresidentdetails.customerLoanId = _customerLoanId;

	SELECT * FROM loancompletescreenhistory WHERE customerloanId = _customerLoanId;
            
	SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
	FROM customerloanstatushistory 
	INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
	WHERE customerloanId = _customerLoanId;
    
     SELECT offers.*,banks.name as bankName FROM offers 
	INNER JOIN banks ON offers.bankId = banks.id 
	WHERE offers.isShared = 1 AND offers.customerLoanId = _customerLoanId;
    
	SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
		
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetCompleteIncompleteCreditCardRequest`(IN _customerId INT)
BEGIN
	SELECT customercreditcards.*,customercreditcards.creditCardTransactionDate as applyDate, creditcardstatuses.status,customercreditcardoffer.referenceNo as referenceNo,banks.name as bankName,banks.id as bankId FROM customercreditcards
    LEFT JOIN creditcardstatuses on creditcardstatuses.id = customercreditcards.statusId
	INNER JOIN customercreditcardoffer on customercreditcardoffer.customerCreditCardId = customercreditcards.id
    INNER JOIN bankcreditcard on bankcreditcard.id =  customercreditcardoffer.bankCreditCardId
    INNER JOIN banks on banks.id = bankcreditcard.bankId
	WHERE  customercreditcards.customerId = _customerId AND customercreditcards.statusId = 7
    ORDER BY customercreditcards.id DESC;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetCreditCardByCustomerCreditCardId`(IN _customerId INT, IN _customerCreditCardId INT)
BEGIN
    
    
	SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
	, customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
	FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN customers ON customers.userId = users.id 
	LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
	WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2);
	
	SELECT customercreditcards.* FROM customercreditcards 
    WHERE customercreditcards.id = _customerCreditCardId;
	
	 SELECT customercreditcardemploymentdetail.*
            FROM customercreditcardemploymentdetail 
            WHERE customercreditcardemploymentdetail.creditCardId = _customerCreditCardId;
	
	
	
	 SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2);
            
            SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId =2 AND userroles.roleId IN(2);
	
           SELECT * FROM creditcardcompletescreenhistory WHERE customerCreditCardId = _customerCreditCardId;
            
           SELECT customercreditcardstatushistory.*, creditcardstatuses.status AS creditCardStatus, creditcardstatuses.isDataEditable AS isDataEditable 
            FROM customercreditcardstatushistory 
            INNER JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcardstatushistory.creditCardStatusId 
            WHERE customerCreditCardId IN(_customerCreditCardId);
            
            SELECT customercreditcardoffer.*, banks.id as bankId,banks.name as bankName FROM customercreditcardoffer
            INNER JOIN bankcreditcard ON bankcreditcard.id =  customercreditcardoffer.bankCreditCardId
			INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE customerCreditCardId IN(_customerCreditCardId);
    
	
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetCustomerLoansByStatusId`(IN _customerId INT, IN _statusId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
    DECLARE customerLoanIds TEXT DEFAULT "";
    DECLARE getQuery TEXT DEFAULT "";
    
     DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											INNER JOIN customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											WHERE customerloanstatushistory.loanStatusId = _statusId AND 
                                            customerloans.customerId = _customerId
                                            LIMIT _fetchRecords OFFSET _startIndex;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
        SET @customerLoanIds="";
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				ELSE
					IF @customerLoanIds !="" THEN
						SET @customerLoanIds = CONCAT_WS(',', @customerLoanIds, cCustomerLoanId);
					ELSE
						SET @customerLoanIds = cCustomerLoanId;
					END IF;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan;
        
        IF @customerLoanIds!="" THEN
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            WHERE customers.id =", _customerId," AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2);");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName,services.name as serviceName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.id IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
            , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
            FROM customerloanemploymentdetails 
            LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
            LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
            LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
            WHERE customerloanemploymentdetails.customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
			
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM customerloanspouses WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloandocuments.*, documentmasters.name as documentName, servicetypedocuments.isPdf FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM customerloanreferences WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
        ELSE
			SELECT "No Loans Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetDocumentByServiceId`(IN _serviceId INT)
BEGIN
	SELECT servicetypedocuments.*, services.displayName as serviceDisplayName, services.name as servicesName, documentmasters.name as documentName
	FROM servicetypedocuments 
	INNER JOIN services ON services.id = servicetypedocuments.serviceId
	INNER JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
	WHERE serviceId = _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetGeneratedOffer`(IN _customerLoanId INT)
BEGIN
	SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId = _customerLoanId AND clf.isShared = 1 AND clf.status IS NULL;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetHomeLoanByCustomerLoanId`(IN _customerId INT, IN _customerLoanId INT)
BEGIN
    SELECT customerloanpropertydetails.*, propertytypes.name as propertyType FROM customerloanpropertydetails 
	INNER JOIN propertytypes ON propertytypes.id = customerloanpropertydetails.propertyTypeId 
	WHERE customerloanpropertydetails.customerloanId = _customerLoanId;
    
	SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
	, customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
	FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN customers ON customers.userId = users.id 
	LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
	WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2);
	
	SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
	LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
	LEFT JOIN services ON  services.id = customerloans.serviceId
	WHERE customerloans.id = _customerLoanId;
	
	SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
	, companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
	FROM customerloanemploymentdetails 
	LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
	LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
	LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
	WHERE customerloanemploymentdetails.customerloanId = _customerLoanId;
	
	
	
	SELECT customerloancoapplicants.*, maritalstatuses.status as maritalStatus, coapplicantrelations.name as coApplicantRelation FROM customerloancoapplicants 
	INNER JOIN maritalstatuses ON maritalstatuses.id = customerloancoapplicants.maritalStatusId
	INNER JOIN coapplicantrelations ON coapplicantrelations.id = customerloancoapplicants.coApplicantRelationId
	WHERE customerloancoapplicants.customerloanId = _customerLoanId;
	
	SELECT customerloancoapplicantemploymentdetails.*, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
	, companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
	, designations.name as designation, employmentnatures.name employmentNature, employmentservicetypes.name as employmentServiceType
	FROM customerloancoapplicantemploymentdetails
	INNER JOIN employmenttypes ON employmenttypes.id = customerloancoapplicantemploymentdetails.employmentTypeId
	LEFT JOIN companyaddresses ON  companyaddresses.id = customerloancoapplicantemploymentdetails.companyAddressId
	LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
	LEFT JOIN designations ON designations.id = customerloancoapplicantemploymentdetails.designationId
	LEFT JOIN employmentnatures ON employmentnatures.id = customerloancoapplicantemploymentdetails.employmentNatureId
	LEFT JOIN employmentservicetypes ON employmentservicetypes.id = customerloancoapplicantemploymentdetails.employmentServiceTypeId
	WHERE customerloancoapplicantemploymentdetails.customerloanId = _customerLoanId;
	
	SELECT customerloancurrentresidentdetails.*,residenttypes.name as residentType FROM customerloancurrentresidentdetails
	INNER JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId
	WHERE customerloancurrentresidentdetails.customerloanId = _customerLoanId;
    
    SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2);
	
	SELECT customerloandocuments.* ,documentmasters.name as documentName, servicetypedocuments.isPdf FROM customerloandocuments 
	LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
	LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
	WHERE customerloandocuments.customerloanId = _customerLoanId;
	
	SELECT * FROM loancompletescreenhistory WHERE customerloanId = _customerLoanId;
	
	SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
	FROM customerloanstatushistory 
	INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
	WHERE customerloanId IN(_customerLoanId);
    
	SELECT offers.*,banks.name as bankName FROM offers 
	INNER JOIN banks ON offers.bankId = banks.id 
	WHERE offers.isShared = 1 AND offers.customerLoanId = _customerLoanId;
    
    SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails
	WHERE customerloantransferpropertydetails.customerloanId = _customerLoanId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetIncompleteBusinessLoanRequest`(IN _customerId INT, IN _serviceId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
      DECLARE dateDiff INT DEFAULT 0;
        DECLARE  rejectedDate date;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
       BEGIN 
      DECLARE cur_getdate CURSOR FOR SELECT customerloanstatushistory.transactionDate FROM customerloanstatushistory LEFT JOIN customerloans ON customerloanstatushistory.customerLoanId = customerloans.id LEFT JOIN customers On customers.id = customerloans.customerId WHERE customerloanstatushistory.loanstatusId = 14 AND customers.id = _customerId AND customerloans.serviceId = _serviceId ORDER BY customerloans.id DESC limit 1 ;
         DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_getdate;
        cur_getdate_loop: LOOP
				FETCH cur_getdate INTO rejectedDate;
                IF finished = 1 THEN
					LEAVE cur_getdate_loop;
				END IF;
            END LOOP cur_getdate_loop;
        CLOSE cur_getdate;
        IF rejectedDate THEN
           SET @dateDiff = rejectedDate;
		ELSE 
	       	 SET @dateDiff = CURRENT_TIMESTAMP();
        END IF;
	END;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
											WHERE customerloans.serviceId = _serviceId AND customerId = _customerId  AND customerloans.isDelete = 0
                                            AND (loancompletescreenhistory.isCompleted = false OR  customerloans.statusId !=15)
                                             AND (customerloans.statusId != 14 OR datediff(CURRENT_TIMESTAMP(), @dateDiff) <= 90)
                                             AND customerloans.isDelete = 0;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan;
        IF cCustomerLoanId > 0 THEN
			SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
            WHERE customers.id = _customerId AND users.isDelete = 0 AND customeraddresses.addressTypeId = 1  AND users.isActive = 1 AND userroles.roleId IN(2);
            
			SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.serviceId = _serviceId AND customerloans.id = cCustomerLoanId;
            
            SELECT customerloandocuments.* FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId = cCustomerLoanId;
            
            SELECT customerloanbusinessdetails.*, companytypes.name as companyType, industrytypes.name as industryTypes, businessexperience.name as businessExperience
			, businessnatures.name as businessNatures, businessannualprofits.name businessAnnualProfits, banks.name banks FROM customerloanbusinessdetails
			LEFT JOIN companytypes ON companytypes.id = customerloanbusinessdetails.companyTypeId
			LEFT JOIN industrytypes ON industrytypes.id = customerloanbusinessdetails.industryTypeId
			LEFT JOIN businessexperience ON businessexperience.id = customerloanbusinessdetails.businessExperienceId
			LEFT JOIN businessnatures ON businessnatures.id = customerloanbusinessdetails.businessNatureId
			LEFT JOIN businessannualprofits ON businessannualprofits.id = customerloanbusinessdetails.businessAnnualProfitId
			LEFT JOIN banks ON banks.id = customerloanbusinessdetails.primaryBankId
            WHERE customerloanbusinessdetails.customerloanId = cCustomerLoanId;
            
            SELECT customerloancurrentresidentdetails.*, residenttypes.name residentType FROM customerloancurrentresidentdetails
			LEFT JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId WHERE customerloancurrentresidentdetails.customerLoanId = cCustomerLoanId;
            
            SELECT * FROM loancompletescreenhistory WHERE customerloanId = cCustomerLoanId;
            
            SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(cCustomerLoanId);
            
 SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId = cCustomerLoanId AND clf.isShared = 1 AND clf.status IS NULL;
            
           SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId = cCustomerLoanId;
		ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetIncompleteCreditCardRequest`(IN _customerId INT, IN _serviceId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerCreditCardId INT DEFAULT 0;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customercreditcard CURSOR FOR SELECT customercreditcards.id FROM customercreditcards 
											   inner join creditcardcompletescreenhistory on creditcardcompletescreenhistory.customerCreditCardId = customercreditcards.id
                                               LEFT join customercreditcardstatushistory on customercreditcardstatushistory.customerCreditCardId = customercreditcards.id
										       LEFT join creditcardstatuses on creditcardstatuses.id = customercreditcardstatushistory.creditCardStatusId
                                               WHERE customercreditcards.customerId = _customerId 
                                               AND (creditcardcompletescreenhistory.isCompleted = false OR customercreditcards.statusId != 7);
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customercreditcard;
			cur_customercreditcard: LOOP
				FETCH cur_customercreditcard INTO cCustomerCreditCardId;
                IF finished = 1 THEN
					LEAVE cur_customercreditcard;
				END IF;
            END LOOP cur_customercreditcard;
        CLOSE cur_customercreditcard;
        IF cCustomerCreditCardId > 0 THEN
		
            
            SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2);
            
			SELECT customercreditcards.* FROM customercreditcards 
            WHERE customercreditcards.id = cCustomerCreditCardId ;
		
            SELECT customercreditcardemploymentdetail.*
            FROM customercreditcardemploymentdetail 
            WHERE customercreditcardemploymentdetail.creditCardId = cCustomerCreditCardId;
            
             SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2);
            
            SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId =2 AND userroles.roleId IN(2);
			
			
            
			
            
			
            
			SELECT * FROM creditcardcompletescreenhistory WHERE customerCreditCardId = cCustomerCreditCardId;
            
           SELECT customercreditcardstatushistory.*, creditcardstatuses.status AS creditCardStatus, creditcardstatuses.isDataEditable AS isDataEditable 
            FROM customercreditcardstatushistory 
            INNER JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcardstatushistory.creditCardStatusId 
            WHERE customerCreditCardId IN(cCustomerCreditCardId);
            
              SELECT customercreditcardoffer.*, banks.id as bankId,banks.name as bankName FROM customercreditcardoffer
            INNER JOIN bankcreditcard ON bankcreditcard.id =  customercreditcardoffer.bankCreditCardId
			INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE customerCreditCardId IN(cCustomerCreditCardId);
            
			
		ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetIncompleteHomeLoanRequest`(IN _customerId INT, IN _serviceId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
     DECLARE dateDiff INT DEFAULT 0;
        DECLARE  rejectedDate date;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
       BEGIN 
      DECLARE cur_getdate CURSOR FOR SELECT customerloanstatushistory.transactionDate FROM customerloanstatushistory LEFT JOIN customerloans ON customerloanstatushistory.customerLoanId = customerloans.id LEFT JOIN customers On customers.id = customerloans.customerId WHERE customerloanstatushistory.loanstatusId = 14 AND customers.id = _customerId AND customerloans.serviceId = _serviceId ORDER BY customerloans.id DESC limit 1 ;
         DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_getdate;
        cur_getdate_loop: LOOP
				FETCH cur_getdate INTO rejectedDate;
                IF finished = 1 THEN
					LEAVE cur_getdate_loop;
				END IF;
            END LOOP cur_getdate_loop;
        CLOSE cur_getdate;
        IF rejectedDate THEN
           SET @dateDiff = rejectedDate;
		ELSE 
	       	 SET @dateDiff = CURRENT_TIMESTAMP();
        END IF;
	END;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
											WHERE customerloans.serviceId = _serviceId AND customerId = _customerId AND customerloans.isDelete = 0
                                            AND (loancompletescreenhistory.isCompleted = false OR customerloans.statusId != 15)
                                                AND (customerloans.statusId != 14 OR datediff(CURRENT_TIMESTAMP(), @dateDiff) <= 90)
                                                AND customerloans.isDelete = 0;
                                         
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan;
        IF cCustomerLoanId > 0 THEN
            SELECT customerloanpropertydetails.*, propertytypes.name as propertyType FROM customerloanpropertydetails 
            INNER JOIN propertytypes ON propertytypes.id = customerloanpropertydetails.propertyTypeId 
            WHERE customerloanpropertydetails.customerloanId = cCustomerLoanId;
            
			SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2);
            
            SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.serviceId = _serviceId AND customerloans.id = cCustomerLoanId;
            
            SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
            , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
            FROM customerloanemploymentdetails 
            LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
            LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
            LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
            WHERE customerloanemploymentdetails.customerloanId = cCustomerLoanId;
            
            
            SELECT customerloancoapplicants.*, maritalstatuses.status as maritalStatus, coapplicantrelations.name as coApplicantRelation FROM customerloancoapplicants 
			INNER JOIN maritalstatuses ON maritalstatuses.id = customerloancoapplicants.maritalStatusId
			INNER JOIN coapplicantrelations ON coapplicantrelations.id = customerloancoapplicants.coApplicantRelationId
            WHERE customerloancoapplicants.customerloanId = cCustomerLoanId;
            
            SELECT customerloancoapplicantemploymentdetails.*, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
			, companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
			, designations.name as designation, employmentnatures.name employmentNature, employmentservicetypes.name as employmentServiceType
			FROM customerloancoapplicantemploymentdetails
			INNER JOIN employmenttypes ON employmenttypes.id = customerloancoapplicantemploymentdetails.employmentTypeId
			LEFT JOIN companyaddresses ON  companyaddresses.id = customerloancoapplicantemploymentdetails.companyAddressId
			LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
			LEFT JOIN designations ON designations.id = customerloancoapplicantemploymentdetails.designationId
			LEFT JOIN employmentnatures ON employmentnatures.id = customerloancoapplicantemploymentdetails.employmentNatureId
			LEFT JOIN employmentservicetypes ON employmentservicetypes.id = customerloancoapplicantemploymentdetails.employmentServiceTypeId
            WHERE customerloancoapplicantemploymentdetails.customerloanId = cCustomerLoanId;
            
            SELECT customerloancurrentresidentdetails.*,residenttypes.name as residentType FROM customerloancurrentresidentdetails
			INNER JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId
            WHERE customerloancurrentresidentdetails.customerloanId = cCustomerLoanId;
            
            SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2);
            
            SELECT customerloandocuments.* FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId = cCustomerLoanId;
            
            SELECT * FROM loancompletescreenhistory WHERE customerloanId = cCustomerLoanId;
            
            SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(cCustomerLoanId);
            
            SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId = cCustomerLoanId AND clf.isShared = 1 AND clf.status IS NULL;
            
			SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails
            WHERE customerloantransferpropertydetails.customerloanId = cCustomerLoanId;
        ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetIncompletePersonalLoanRequest`(IN _customerId INT, IN _serviceId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE dateDiff INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
    DECLARE  rejectedDate date;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN 
      DECLARE cur_getdate CURSOR FOR SELECT customerloanstatushistory.transactionDate FROM customerloanstatushistory LEFT JOIN customerloans ON customerloanstatushistory.customerLoanId = customerloans.id LEFT JOIN customers On customers.id = customerloans.customerId WHERE customerloanstatushistory.loanstatusId = 14 AND customers.id = _customerId AND customerloans.serviceId = _serviceId ORDER BY customerloans.id DESC limit 1 ;
         DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_getdate;
        cur_getdate_loop: LOOP
				FETCH cur_getdate INTO rejectedDate;
                IF finished = 1 THEN
					LEAVE cur_getdate_loop;
				END IF;
            END LOOP cur_getdate_loop;
        CLOSE cur_getdate;
        IF rejectedDate THEN
           SET @dateDiff = rejectedDate;
		ELSE 
	       	 SET @dateDiff = CURRENT_TIMESTAMP();
        END IF;
	END;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
											WHERE customerloans.serviceId = _serviceId AND customerId = _customerId AND customerloans.isDelete = 0
                                            AND (loancompletescreenhistory.isCompleted = false OR customerloans.statusId !=15 )
                                          AND (customerloans.statusId != 14 OR datediff(CURRENT_TIMESTAMP(), @dateDiff) <= 90)
                                          AND customerloans.isDelete = 0;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan;
        IF cCustomerLoanId > 0 THEN
        
			SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2);
            
			SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.serviceId = _serviceId AND customerloans.id = cCustomerLoanId;
            
			SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
            , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
            FROM customerloanemploymentdetails 
            LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
            LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
            LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
            WHERE customerloanemploymentdetails.customerloanId = cCustomerLoanId;
			
			SELECT * FROM customerloanspouses WHERE customerloanId = cCustomerLoanId;
            
			SELECT customerloandocuments.* FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId = cCustomerLoanId;		
			
			SELECT customerloanreferences.*,customerreferenceaddresses.* FROM customerloanreferences
			LEFT JOIN customerreferenceaddresses ON  customerreferenceaddresses.customerLoanReferenceId = customerloanreferences.id
			WHERE customerloanId = cCustomerLoanId;
            
            
			SELECT * FROM loancompletescreenhistory WHERE customerloanId = cCustomerLoanId;
            
            SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(cCustomerLoanId);
            
			 SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId = cCustomerLoanId AND clf.isShared = 1 AND clf.status IS NULL;
            
            SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customeraddresses.city,customeraddresses.state,customeraddresses.district
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 5 AND userroles.roleId IN(2);
            
            SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId = cCustomerLoanId;
		ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetLoanDetail`(IN _customerLoanId INT)
BEGIN
	SELECT customerloandetail.*,banks.name AS bankName,customers.fullName AS customerName,customers.contactNo AS customerContactNo FROM customerloandetail LEFT JOIN banks ON banks.id = customerloandetail.bankId LEFT JOIN customerloans ON customerloans.id = customerloandetail.customerLoanId LEFT JOIN customers ON customers.id = customerloans.customerId WHERE customerloandetail.customerLoanId = _customerLoanId AND customerloandetail.isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetMaritalStatus`()
BEGIN
	SELECT * FROM maritalstatuses;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetMasterDataByServiceId`(IN _serviceId INT)
BEGIN
	SELECT * FROM maritalstatuses;
    
    SELECT servicetypedocuments.*, services.displayName as serviceDisplayName, services.name as servicesName, documentmasters.name as documentName,documentmasters.maxSize as maxSize 
	FROM servicetypedocuments 
	INNER JOIN services ON services.id = servicetypedocuments.serviceId
	INNER JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
	WHERE serviceId = _serviceId;
    
    SELECT employmenttypes.*,parentType.id  as parentTypeId, parentType.name as parentTypeName FROM employmenttypes 
	LEFT JOIN employmenttypes as parentType ON parentType.id = employmenttypes.parentId 
	INNER JOIN servicesemploymenttypes ON servicesemploymenttypes.employmentTypeId = employmenttypes.id 
    WHERE servicesemploymenttypes.serviceId = _serviceId AND servicesemploymenttypes.isActive = 1 AND servicesemploymenttypes.isDelete = 0 AND employmenttypes.isActive = 1 AND employmenttypes.isDelete = 0;
    
    SELECT * FROM companytypes;
    
    SELECT * FROM industrytypes;
    
    SELECT * FROM residenttypes;
    
    SELECT * FROM banks;
    
    SELECT * FROM loanagainstcollteral;
    
    SELECT * FROM businessannualprofits;
    
    SELECT * FROM businessannualsales;
    
    SELECT * FROM businessexperience;
    
    SELECT * FROM businessnatures;
    
	SELECT * FROM propertytypes;
    
    SELECT * FROM employmentservicetypes;
    
    SELECT * FROM employmentnatures;
    
    select * from coapplicantrelations;
    
    select * from addresstypes;
    
    select * from tenure;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetNonDisbursedLoan`(IN _customerId INT)
BEGIN
	select id FROM customerloans WHERE customerId = _customerId AND isDelete = 0  AND (statusId IS NULL OR statusId NOT IN (14,15,8));
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetProfessionType`()
BEGIN
	SELECT * FROM professiontypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetServiceEmploymentTypes`(IN _serviceId INT)
BEGIN
	SELECT employmenttypes.* FROM employmenttypes INNER JOIN servicesemploymenttypes ON servicesemploymenttypes.employmentTypeId = employmenttypes.id 
    WHERE servicesemploymenttypes.serviceId = _serviceId AND servicesemploymenttypes.isActive = 1 AND servicesemploymenttypes.isDelete = 0 AND employmenttypes.isActive = 1 AND employmenttypes.isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetServices`()
BEGIN
	SELECT services.*, servicetypes.name as serviceType, servicetypes.displayName as serviceTypeDisplayName, servicetypes.description as serviceTypeDescription, servicetypes.iconUrl as serviceTypeIconUrl, servicetypes.colorCode as serviceTypeColorCode FROM services INNER JOIN servicetypes ON servicetypes.id = services.serviceTypeId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerGetServicesByServiceTypeId`(IN _serviceTypeId INT)
BEGIN
	SELECT * FROM services WHERE serviceTypeId = _serviceTypeId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertCustomerLoanSpouseDetail`(IN _id INT, IN _customerLoanId INt, IN _name VARCHAR(100), IN _contactNo VARCHAR(45), IN _spouseRelationId INT, IN _userId INT)
BEGIN
	IF _id>0 THEN
		UPDATE customerloanspouses SET customerLoanId=_customerLoanId, name=_name, contactNo=_contactNo, spouseRelationId=_spouseRelationId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId
        WHERE id = _id;
    ELSE
		INSERT INTO customerloanspouses(customerLoanId, name, contactNo, spouseRelationId, createdBy, modifiedBy) VALUES(_customerLoanId, _name, _contactNo, _spouseRelationId, _userId, _userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdateCreditCardEmploymentDetail`(IN _creditCardId INT, IN _creditCardEmploymentDetailId INT, IN _employmentTypeId INT,IN _companyName varchar(100),IN _professionName varchar(100),IN _bankId INT,IN _bankAccountNo varchar(45),IN _lastItr TEXT,IN _educationTypeId INT,IN _customerId INT, IN _officeContactNo varchar(45) ,IN _userId INT, IN _partnerId INT)
BEGIN
    IF _creditCardEmploymentDetailId >0 THEN
       UPDATE customercreditcardemploymentdetail SET employmentTypeId=_employmentTypeId,creditCardId = _creditCardId, companyName =_companyName,professionName = _professionName,officeContactNo = _officeContactNo, bankId = _bankId,bankAccountNo = _bankAccountNo, lastItr = _lastItr,educationTypeId = _educationTypeId ,modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardEmploymentDetailId;
	ELSE 
		INSERT INTO customercreditcardemploymentdetail(employmentTypeId, creditCardId, companyName, professionName,bankId,bankAccountNo,lastItr,educationTypeId,officeContactNo,createdBy, modifiedBy) VALUES(_employmentTypeId, _creditCardId, _companyName,_professionName,_bankId, _bankAccountNo,_lastItr,_educationTypeId,_officeContactNo,_userId, _userId);
        SET @creditCardEmploymentDetailId = LAST_INSERT_ID();
	END IF;
    UPDATE creditcardcompletescreenhistory SET completeScreen = 2 WHERE customerCreditCardId = _creditCardId AND completeScreen < 2;
    
    IF _creditCardEmploymentDetailId >0 THEN
		SELECT _creditCardId as creditCardId,_creditCardEmploymentDetailId as creditCardEmploymentDetailId ;
    ELSE
       SELECT _creditCardId as creditCardId,@creditCardEmploymentDetailId as creditCardEmploymentDetailId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdateCustomerCreditCardOffer`(IN _id INT, IN _customerCreditCardId INT, IN _bankCreditCardId INT, IN _referenceNo VARCHAR(45)
, IN _userId INT)
BEGIN
	IF (_id = 0  || _id = null) THEN
		INSERT INTO customercreditcardoffer(customerCreditCardId, bankCreditCardId, referenceNo, createdBy, modifiedBy) 
        VALUES(_customerCreditCardId, _bankCreditCardId, _referenceNo, _userId, _userId);
        INSERT INTO customercreditcardstatushistory(customerCreditCardId,creditcardStatusId,createdBy,modifiedBy) VALUES(_customerCreditCardId, 2, _userId, _userId);
        UPDATE customercreditcards SET statusId = 2, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerCreditCardId;
    ELSE
		UPDATE customercreditcardoffer SET customerCreditCardId = _customerCreditCardId, bankCreditCardId = _bankCreditCardId, referenceNo = _referenceNo, modifiedBy = _userId
        , modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
        INSERT INTO customercreditcardstatushistory(customerCreditCardId,creditcardStatusId,createdBy,modifiedBy) VALUES(_customerCreditCardId, 2, _userId, _userId);
        UPDATE customercreditcards SET statusId = 2, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerCreditCardId;
    END IF;
    SELECT creditcardstatuses.status as status FROM  creditcardstatuses WHERE id = 2; 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdateCustomerLoan`(IN _customerLoanId INT, IN _serviceId INT, IN _customerId INT, IN _employmentTypeId INT, IN _loanAmount DECIMAL(15,2), IN _motherName VARCHAR(100), IN _fatherContactNo VARCHAR(15), IN _userId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    IF _customerLoanId>0 THEN
		SET @UpdateQuery = "";
        SET @SetStatement = "";
        
        SET @UpdateQuery =  "UPDATE customerloans SET modifiedDate = '";
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
        
         IF _employmentTypeId >0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentTypeId = ",_employmentTypeId);
        END IF;
        
		IF _loanAmount > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", loanAmount = ",_loanAmount);
        END IF;
        
		IF _motherName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", motherName = '",_motherName,"'");
        END IF;
        
		IF _fatherContactNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", fatherContactNo = '",_fatherContactNo,"'");
        END IF;
        
		SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerLoanId);
        PREPARE stmt FROM @UpdateQuery;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
        
    ELSE
		INSERT INTO customerloans(serviceId, loanAmount, customerId, employmentTypeId, motherName, fatherContactNo, createdBy, modifiedBy) VALUES(_serviceId, _loanAmount, _customerId, _employmentTypeId, _motherName, _fatherContactNo, _userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdateCustomerLoanSpouseDetail`(IN _id INT, IN _customerLoanId INt, IN _name VARCHAR(100), IN _contactNo VARCHAR(45), IN _spouseRelationId INT, IN _userId INT)
BEGIN
	IF _id>0 THEN
		UPDATE customerloanspouses SET customerLoanId=_customerLoanId, name=_name, contactNo=_contactNo, spouseRelationId=_spouseRelationId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId
        WHERE id = _id;
    ELSE
		INSERT INTO customerloanspouses(customerLoanId, name, contactNo, spouseRelationId, createdBy, modifiedBy) VALUES(_customerLoanId, _name, _contactNo, _spouseRelationId, _userId, _userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdateLoanDocuments`(IN _id INT, IN _customerLoanId INT, IN _serviceTypeDocumentId INT, IN _documentId INT, IN _documentUrl TEXT, IN _userId INT)
BEGIN
	IF _id>0 THEN
		UPDATE customerloandocuments SET customerLoanId=_customerLoanId, serviceTypeDocumentId=_serviceTypeDocumentId, documentId=_documentId, decumentUrl=_documentUrl, modifiedBy=_userId,
        modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
    ELSE
		INSERT INTO customerloandocuments(customerLoanId, serviceTypeDocumentId, documentId, decumentUrl, createdBy, modifiedBy) VALUES(_customerLoanId, _serviceTypeDocumentId, _documentId
        , _documentUrl, _userId, _userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInsertUpdatePersonalLoanEmploymentDetail`(IN _customerloanId INT, IN _customerLoanEmploymentId INT, IN _employmentTypeId INT, IN _monthlyIncode DECIMAL(15,2)
, IN _companyName VARCHAR(100), IN _officeCode VARCHAR(8), IN _serviceId INT, IN _customerId INT, IN _userId INT, IN _partnerId INT,IN _loanType VARCHAR(50))
BEGIN
	IF _customerLoanId >0 THEN
		UPDATE customerloans SET employmentTypeId=_employmentTypeId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId,loanType = _loanType WHERE id = _customerloanId;
    ELSE
		INSERT INTO customerloans(serviceId, customerId, employmentTypeId, createdBy, modifiedBy,loanType) VALUES(_serviceId, _customerId, _employmentTypeId, _userId, _userId,_loanType);
        SET @customerLoanId = LAST_INSERT_ID();
        INSERT INTO customerloanemploymentdetails(customerloanId, monthlyIncome, companyName, officePincode, createdBy, modifiedBy) VALUES(@customerLoanId, _monthlyIncode, _companyName
        , _officeCode, _userId, _userId);
        SET @customerLoanEmploymentId = LAST_INSERT_ID();
        INSERT INTO loancompletescreenhistory(customerLoanId,isCompleted,completeScreen) VALUES(@customerLoanId, false, 2);
        IF _partnerId>0 THEN
			INSERT INTO partnerscustomerloans(customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(@customerLoanId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
        SELECT @customerLoanId as customerLoanId,@customerLoanEmploymentId as customerLoanEmploymentId;
    END IF;
    
    IF _customerLoanEmploymentId>0 THEN
		UPDATE customerloanemploymentdetails SET monthlyIncome=_monthlyIncode, companyName=_companyName, officePincode=_officeCode, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId
        WHERE id = _customerLoanEmploymentId;
    END IF;
    
    IF _customerLoanId >0 THEN
		SELECT _customerLoanId as customerLoanId,_customerLoanEmploymentId as customerLoanEmploymentId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerInserUpdateLoanEmploymentDetail`(IN _id INT, IN _customerLoanId INT, IN _monthlyIncome DECIMAL(15,2), IN _otherIncome DECIMAL(15,2), IN _companyTypeId INT
, IN _companyName VARCHAR(100), IN _companyAddressId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20)
, IN _cityId INT, IN _officePincode VARCHAR(8), IN _designationId INT, IN _designation VARCHAR(100), IN _employmentNatureId INT, IN _employmentServiceTypeId INT
, IN _currentCompanyExperience DECIMAL(5,2), IN _experienceInProfession DECIMAL(5,2), IN _userId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    
	IF _id>0 THEN
    -- Update
		IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId, modifiedDate=CURRENT_TIMESTAMP()
            , modifiedBy=_userId WHERE id = _companyAddressId;
		ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
			SET @companyAddressId = LAST_INSERT_ID();
        END IF;
		IF _companyAddressId>0 THEN
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _customerloanId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerloanId = ",_customerloanId);
			END IF;                
			IF _monthlyIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
			END IF;                
			IF _otherIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", otherIncome = ",_otherIncome);
			END IF;
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;
			IF _companyName!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
			END IF;
			IF _companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",_companyAddressId);
			END IF;
			IF _officePincode!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", officePincode = '",_officePincode,"'");
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designationId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = ",_designation);
			END IF;
			IF _employmentNatureId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentNatureId = ",_employmentNatureId);
			END IF;
			IF _employmentServiceTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentServiceTypeId = ",_employmentServiceTypeId);
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			IF _experienceInProfession >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", experienceInProfession = ",_experienceInProfession);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_id);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		ELSE
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _customerloanId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerloanId = ",_customerloanId);
			END IF;                
			IF _monthlyIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
			END IF;                
			IF _otherIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", otherIncome = ",_otherIncome);
			END IF;
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;
			IF _companyName!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
			END IF;
			IF @companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",@companyAddressId);
			END IF;
			IF _officePincode!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", officePincode = '",_officePincode,"'");
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designationId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = ",_designation);
			END IF;
			IF _employmentNatureId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentNatureId = ",_employmentNatureId);
			END IF;
			IF _employmentServiceTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentServiceTypeId = ",_employmentServiceTypeId);
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			IF _experienceInProfession >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", experienceInProfession = ",_experienceInProfession);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_id);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		END IF; 
    ELSE
    -- Insert
    INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
    VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
    SET @companyAddressId = LAST_INSERT_ID();
    
    INSERT customerloanemploymentdetails(customerLoanId, monthlyIncome, otherIncome, companyTypeId, companyName, companyAddressId, officePincode, cityId, designationId, designation
    , employmentNatureId, employmentServiceTypeId, currentCompanyExperience, experienceInProfession, createdBy, modifiedBy) VALUES(_customerLoanId, _monthlyIncome, _otherIncome, _companyTypeId
    , _companyName, @companyAddressId, _pincode, _cityId, _designationId, _designation, _employmentNatureId, _employmentServiceTypeId, _currentCompanyExperience, _experienceInProfession, _userId, _userId);

    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdateCustomer`(IN _userId INT, IN _customerId INT, IN _fullName VARCHAR(200), IN _birthdate DATETIME, IN _panCardNo VARCHAR(20), IN _alternativeContactNo VARCHAR(15), IN _gender VARCHAR(15), IN _maritalStatusId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    DECLARE WhereStatement TEXT DEFAULT "";
    
    IF _customerId>0 THEN
		SET @UpdateQuery = "";
        SET @SetStatement = "";
        
        SET @UserUpdateQuery = "";
        SET @UserSetStatement = "";
        
        SET @UpdateQuery =  "UPDATE customers SET modifiedDate = '";
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
        
        SET @UserUpdateQuery =  "UPDATE users SET modifiedDate = '";
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, CURRENT_TIMESTAMP(),"'");
		
        IF _fullName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", fullName = '",_fullName,"'");
            SET @UserSetStatement = CONCAT_WS('', @UserSetStatement, ", fullName = '",_fullName,"'");
        END IF;
        
        IF _birthdate IS NOT NULL THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", birthdate = '",_birthdate,"'");
        END IF;
        
        IF _panCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", panCardNo = '",_panCardNo,"'");
        END IF;
        
        IF _alternativeContactNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", alternativeContactNo = '",_alternativeContactNo,"'");
        END IF;
        
        IF _gender != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", gender = '",_gender,"'");
            SET @UserSetStatement = CONCAT_WS('', @UserSetStatement, ", gender = '",_gender,"'");
        END IF;
        
        IF _maritalStatusId != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", maritalStatusId = ",_maritalStatusId);
        END IF;
        
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerId);
        PREPARE stmt FROM @UpdateQuery;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
    
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, @UserSetStatement," WHERE id = ",_userId);
        PREPARE stmt_user FROM @UserUpdateQuery;
		EXECUTE stmt_user;
		DEALLOCATE PREPARE stmt_user;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdateCustomerProfile`(IN _userId INT, IN _customerId INT, IN _fullName VARCHAR(200), IN _contactNo VARCHAR(15), IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20)
, IN _birthdate DATETIME,IN _email VARCHAR(200))
BEGIN
	UPDATE customers SET fullName=_fullName, contactNo=_contactNo, panCardNo=_panCardNo, aadhaarCardNo=_aadhaarCardNo, birthdate=_birthdate WHERE id = _customerId;
    UPDATE users SET fullName=_fullName, contactNo=_contactNo,email = _email WHERE id = _userId;
    SELECT profilePicUrl from users where id =_userId;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdateCustomerProfileWithPic`(IN _userId INT, IN _customerId INT, IN _fullName VARCHAR(200), IN _contactNo VARCHAR(15), IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20)
, IN _birthdate DATETIME,IN _profilePicUrl TEXT,IN _email VARCHAR(200))
BEGIN
	UPDATE customers SET fullName=_fullName, contactNo=_contactNo, panCardNo=_panCardNo, aadhaarCardNo=_aadhaarCardNo, birthdate=_birthdate WHERE id = _customerId;
    UPDATE users SET fullName=_fullName, contactNo=_contactNo, profilePicUrl = _profilePicUrl,email = _email WHERE id = _userId;
    SELECT profilePicUrl from users where id =_userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdatePersonalLoanAmount`(IN _customerLoanId INT, IN _loanAmount DECIMAL(15,2),IN _tenureId INT, IN _userId INT)
BEGIN
	UPDATE customerloans SET loanAmount=_loanAmount,tenureId = _tenureId ,modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerloanId;
    UPDATE loancompletescreenhistory SET completeScreen = 3 WHERE customerLoanId=_customerLoanId AND completeScreen < 3;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdatePersonalLoanBasicDetail`(IN _customerId INT, IN _alternativeContactNo VARCHAR(15), IN _gender VARCHAR(15), IN _maritalStatusId INT, IN _customerLoanId INT
, IN _motherName VARCHAR(100), IN _fatherContactNo VARCHAR(15), IN _userId INT, IN _customerLoanSpouseId INT, IN _spouseName VARCHAR(100), IN _spouseContactNo VARCHAR(45),IN _fatherName VARCHAR(100),
IN _customerAddressId INT,IN _addressTypeId INT,IN _label varchar(100),IN _addressLine1 varchar(100),IN _addressLine2 varchar(100),IN _pincode varchar(15),
IN _city varchar(100),IN _cityId INT,IN _state varchar(100),IN _district varchar(100),IN _loanAmountTakenExisting DECIMAL(15,2),IN  _approxDate VARCHAR(100),IN _topupAmount DECIMAL(15,2),IN _approxCurrentEMI DECIMAL(15,2),IN _bankId INT,IN _loanType VARCHAR(40))
BEGIN

	DECLARE finished INT DEFAULT 0;
    DECLARE _existId INT DEFAULT 0;
	UPDATE customers SET alternativeContactNo=_alternativeContactNo, gender=_gender, maritalStatusId=_maritalStatusId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId 
    WHERE id = _customerId;
	UPDATE customerloans SET motherName=_motherName, fatherContactNo=_fatherContactNo,fatherName = _fatherName, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId,loanType = _loanType WHERE id = _customerloanId;
    IF _loanType != 'New' THEN
		
		IF 	EXISTS(SELECT 1 FROM customerloantransferpropertydetails) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select customerLoanId FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				gettransfercustomerloan: LOOP
					FETCH cur_checkexist INTO _existId;
					IF finished = 1 THEN 
						LEAVE gettransfercustomerloan;
					END IF;
					IF _existId THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting,approxDate = _approxDate,topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI,bankId = _bankId,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE customerLoanId  = _customerLoanId;	
		ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
        ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
	END IF;
    IF _customerLoanSpouseId>0 THEN
		UPDATE customerloanspouses SET name=_spouseName, contactNo=_spouseContactNo, modifiedDate=CURRENT_TIMESTAMP() , modifiedBy=_userId WHERE id =_customerLoanSpouseId;
        SELECT _customerLoanSpouseId AS customerLoanspouseId;
    ELSE
		INSERT INTO customerloanspouses(customerLoanId,name,contactNo,createdBy,modifiedBy) VALUES(_customerLoanId, _spouseName, _spouseContactNo, _userId, _userId);
        SET @customerLoanspouseId = LAST_INSERT_ID();
        SELECT @customerLoanspouseId AS customerLoanspouseId;
    END IF;
	IF _customerAddressId > 0 THEN
       UPDATE customeraddresses SET label = _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,addressTypeId = _addressTypeId,city= _city,cityId = _cityId,pincode = _pincode,state = _state,district = _district, modifiedDate=CURRENT_TIMESTAMP() , modifiedBy=_userId WHERE id =_customerAddressId;
	   SELECT _customerAddressId AS customerAddressId;
	ELSE 
	   INSERT INTO customeraddresses(customerId,label,addressLine1,addressLine2,pincode,city,cityId,state,district,addressTypeId,createdBy,modifiedBy) VALUES(_customerId,_label,_addressLine1,_addressLine2,_pincode,_city,_cityId,_state,_district,_addressTypeId,_userId, _userId);
	   SET @customerAddressId = LAST_INSERT_ID();
	   SELECT @customerAddressId AS customerAddressId;
	END IF;
   -- UPDATE loancompletescreenhistory SET completeScreen = 4 WHERE customerLoanId=_customerLoanId AND completeScreen < 4;
   UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId=_customerLoanId AND completeScreen < 5;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdatePersonalLoanMoreEmploymentDetail`(IN _customerLoanId INT,IN _customerLoanEmploymentId INT, IN _companyTypeId INT, IN _companyAddressId INT, IN _addressTypeId INT
, IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _city VARCHAR(200), IN _district VARCHAR(200)
, IN _state VARCHAR(200), IN _designation VARCHAR(100), IN _currentCompanyExperience DECIMAL(10,2), IN _userId INT, IN _email VARCHAR(256))
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    
	IF _customerLoanEmploymentId>0 THEN
    -- Update
		IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId
            , city=_city, district=_district, state=_state, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _companyAddressId;
            
            SELECT _companyAddressId AS companyAddressId;
		ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
			SET @companyAddressId = LAST_INSERT_ID();
            SELECT @companyAddressId AS companyAddressId;
        END IF;
		IF _companyAddressId>0 THEN
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;	
			IF _companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",_companyAddressId);
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = '",_designation,"'");
			END IF;
            IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerLoanEmploymentId);
            PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		ELSE
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;
			IF @companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",@companyAddressId);
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = '",_designation,"'");
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerLoanEmploymentId);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		END IF; 
    
    END IF;
    
    UPDATE users SET email = _email WHERE id = _userId;
       UPDATE loancompletescreenhistory SET completeScreen = 4 WHERE customerLoanId=_customerLoanId AND completeScreen < 4;
   -- UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId=_customerLoanId AND completeScreen < 5;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerUpdateUserEmail`(IN _userId INT, IN _email VARCHAR(256))
BEGIN
	UPDATE users SET email = _email WHERE id = _userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerVerifyContactNo`(IN _countryCode VARCHAR(6), IN _contactNo VARCHAR(15), IN _email VARCHAR(256), IN _temporaryCode VARCHAR(45), IN _appId INT
, IN _deviceId VARCHAR(300), IN _fcmToken VARCHAR(500), IN _deviceManufacturer VARCHAR(300), IN _deviceModel VARCHAR(100), IN _sessionToken TEXT, IN _appVersion VARCHAR(100)
, IN _partnerUserId INT, IN _rewardTypeId INT, IN _rewarsCoin DECIMAL(15,3))
BEGIN
	DECLARE finished_check INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
	DECLARE cRoleId INT DEFAULT 0;
    
    DECLARE finished INT DEFAULT 0;
    DECLARE session_done INT DEFAULT 0;
    DECLARE deviceDetail_done INT DEFAULT 0;
    DECLARE cIsDisabled INT DEFAULT 1;
    DECLARE cRoleName VARCHAR(45) DEFAULT NULL;
    DECLARE cAppId INT DEFAULT 0;
    DECLARE dAppId INT DEFAULT 0;
	DECLARE dfcmToken VARCHAR(500) DEFAULT NULL;
	DECLARE dDeviceId VARCHAR(100) DEFAULT NULL;
	
    DECLARE insertDeviceDetailFlag INT DEFAULT 0;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_user_check CURSOR FOR SELECT users.id as userId, userroles.roleId as roleId FROM users LEFT JOIN userroles ON userroles.userId = users.id WHERE users.contactNo = _contactNo;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished_check = 1;
			OPEN  cur_user_check;
				cur_user_check_loop: LOOP
					FETCH cur_user_check INTO cUserId, cRoleId;
                    
                    IF finished_check = 1 THEN
						LEAVE cur_user_check_loop;
					END IF;
                    
                END LOOP cur_user_check_loop;
			CLOSE cur_user_check;
            IF cUserId = 0 THEN
				INSERT INTO users(countryCode,contactNo,isDisabled,email,currentRoleId) VALUES(_countryCode,_contactNo,0,_email,2);
                SET @userId = LAST_INSERT_ID();
                SET @createdBy = @userId;
                SET cUserId = @userId;
                                
                IF _partnerUserId > 0 THEN
					SET @createdBy = _partnerUserId;
                END IF;
                
                INSERT INTO userroles(userId,roleId,createdBy,modifiedBy) VALUES(@userId, 2, @createdBy, @createdBy);                
                INSERT INTO customers(userId, temporaryCode, contactNo, createdBy, modifiedBy,currentRoleId) VALUES(@userId, _temporaryCode, _contactNo, @createdBy, @createdBy,2);
                SET @customerId = LAST_INSERT_ID();
                INSERT INTO customeraddresses(customerId,createdBy,modifiedBy,addressTypeId) VALUES(@customerId, @createdBy, @createdBy,1);
                
                INSERT INTO userscratchcards(userId, value, rewardType, createdBy, modifiedBy) VALUES(@userId, _rewarsCoin, _rewardTypeId, @userId, @userId);
                
                INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
				VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
            END IF;
            SET insertDeviceDetailFlag = 0;
            BEGIN
				DECLARE cur_user CURSOR FOR SELECT users.id, users.isDisabled, roles.id as roleId, roles.name as roleName FROM users 
											INNER JOIN userroles ON userroles.userId = users.id 
											INNER JOIN roles ON roles.id = userroles.roleId
											INNER JOIN customers ON customers.userId = users.Id
											WHERE users.contactNo = _contactNo AND userroles.roleId IN(2);
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
				OPEN  cur_user;
					cur_user_loop: LOOP
						FETCH cur_user INTO cUserId, cIsDisabled, cRoleId, cRoleName;
						IF finished = 1 THEN
							LEAVE cur_user_loop;
						END IF;
						IF cUserId>0 AND cRoleId >0 AND cIsDisabled=0 THEN
							BEGIN
								DECLARE cur_session CURSOR FOR SELECT usersessions.appId FROM users INNER JOIN usersessions ON users.id = usersessions.userId WHERE usersessions.sessionToken = (SELECT se.sessionToken FROM usersessions se WHERE se.userId = cUserId  ORDER BY userId DESC LIMIT 1)  AND usersessions.expireAt > CURDATE();
								DECLARE CONTINUE HANDLER FOR NOT FOUND SET session_done = 1;
								OPEN  cur_session;
									cur_get_session: LOOP
										FETCH cur_session INTO cAppId;
										IF session_done = 1 THEN
											LEAVE cur_get_session;
										END IF;
										IF cRoleId = 2 THEN
											BEGIN
												DECLARE cur_deviceDetails CURSOR FOR SELECT userdevicedetail.appId, userdevicedetail.deviceId, userdevicedetail.fcmToken FROM userdevicedetail  WHERE userdevicedetail.userId = cUserId;
												DECLARE CONTINUE HANDLER FOR NOT FOUND SET deviceDetail_done = 1;
												OPEN  cur_deviceDetails;
													cur_get_deviceDetails:LOOP
														FETCH cur_deviceDetails INTO dAppId, dDeviceId, dfcmToken;
														IF deviceDetail_done = 1 THEN
															IF (@insertDeviceDetailFlag = 0 OR @insertDeviceDetailFlag IS NULL) THEN
																INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
																VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
                                                                SET @insertDeviceDetailFlag = 1;
                                                            END IF;
															LEAVE cur_get_deviceDetails;
														END IF;
														IF dAppId > 0 THEN
															IF cAppId > 0 THEN
																IF cAppId != dAppId THEN
																	INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
																	VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
                                                                    SET @insertDeviceDetailFlag = 1;
																ELSE 
																	UPDATE userdevicedetail SET deviceId = _deviceId,fcmToken = _fcmToken , deviceManufacturer = _deviceManufacturer, deviceModel = _deviceModel, modifiedDate = current_timestamp()  WHERE userId= cUserId;
                                                                    SET @insertDeviceDetailFlag = 1;
                                                                     
																END IF;
															ELSE
																IF dDeviceId != _deviceId OR dfcmToken != _fcmToken THEN
																	UPDATE userdevicedetail SET deviceId = _deviceId,fcmToken = _fcmToken , deviceManufacturer = _deviceManufacturer, deviceModel = _deviceModel, modifiedDate = current_timestamp() WHERE userId= cUserId;
                                                                    SET @insertDeviceDetailFlag  = 1;
																END IF;
															END IF;
														ELSE
															INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
															VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
                                                            SET @insertDeviceDetailFlag  = 1;
														END IF;
													END LOOP cur_get_deviceDetails;
												CLOSE cur_deviceDetails;
											END;
										END IF;
									END LOOP cur_get_session;
								CLOSE cur_session;
							END;
						ELSE 
							LEAVE cur_user_loop;
						END IF;
					END LOOP cur_user_loop;
				CLOSE cur_user;
				IF cIsDisabled = 0 THEN
					SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = cUserId;
					
					INSERT INTO usersessions(sessionToken, appId, expireAt, userId) VALUES(_sessionToken, _appId, TIMESTAMPADD(DAY,60,CURRENT_TIMESTAMP()), cUserId);
					
					SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
                    , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
                    FROM users 
                    INNER JOIN userroles ON userroles.userId = users.id 
                    INNER JOIN customers ON customers.userId = users.id 
                    LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
                    WHERE users.contactNo = _contactNo  AND customeraddresses.addressTypeId = 1 AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2);
				ELSE
					SELECT 'User Not Verified' as message;
				END IF;
			END;
            
        END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `customerVerifySessionToken`(IN _sessionToken TEXT, IN _appId INT, IN _deviceId VARCHAR(300), IN _fcmToken VARCHAR(500), IN _deviceManufacturer VARCHAR(300), IN _deviceModel VARCHAR(100), IN _appVersion VARCHAR(100))
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    
    SET @LastUpdateID := 0;
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
    UPDATE usersessions SET usersessions.modifiedDate = CURRENT_TIMESTAMP(), expireAt=TIMESTAMPADD(DAY,60,CURRENT_TIMESTAMP()), id = (SELECT @LastUpdateID := id)  WHERE sessionToken = _sessionToken;
    BEGIN
		DECLARE cur_user CURSOR FOR SELECT users.id FROM users INNER JOIN usersessions ON users.id = usersessions.userId WHERE usersessions.sessionToken = _sessionToken AND usersessions.expireAt > CURDATE() AND users.isDisabled = 0;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
		OPEN  cur_user;
			cur_user_loop: LOOP
				FETCH cur_user INTO cUserId;
					IF finished = 1 THEN
						LEAVE cur_user_loop;
					END IF;
			END LOOP cur_user_loop;
		CLOSE cur_user;
        IF cUserId>0 THEN
			SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = cUserId;
            SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
            WHERE users.id = cUserId AND customeraddresses.addressTypeId = 1  AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2);
        ELSE
			SELECT 'User Not Verified' as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `disabledPartner`(IN _id INT,IN userId INT)
BEGIN
	UPDATE partners SET isActive = !isActive WHERE id = _id;
    UPDATE users SET isDisabled = !isDisabled WHERE id = userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarCheckDSAByCode`(IN _dsaCode VARCHAR(45))
BEGIN
	SELECT * FROM partners WHERE permanentCode = _dsaCode;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarEducationTypes`()
BEGIN
	SELECT * FROM educationtypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetAssignTrainingsByPartnerId`(IN _partnerId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SELECT assignuserstraining.*, trainings.trainingCategoryId, trainings.title, trainings.url, trainings.fileName, trainings.documentType, trainings.trainingSubCategoryId
	, triningcategories.name as trainingCategory, sc.name as trainingSubCategory,trainings.completionTime FROM assignuserstraining
	INNER JOIN trainings ON trainings.id = assignuserstraining.trainingId
	INNER JOIN triningcategories ON triningcategories.id = trainings.trainingCategoryId
	LEFT JOIN triningcategories as sc ON sc.id = trainings.trainingSubCategoryId
    WHERE assignuserstraining.partnerId = _partnerId ORDER BY id DESC LIMIT _fetchRecords OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetBanks`()
BEGIN
	SELECT * FROM banks;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetCommissionType`()
BEGIN
	SELECT * FROM commissiontypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetDesignation`()
BEGIN
	SELECT * FROM designations;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetDocuments`()
BEGIN
	SELECT * FROM documentmasters;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetEducationTypes`()
BEGIN
	SELECT * FROM educationtypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetEmploymentTypes`()
BEGIN
	SELECT employmenttypes.*,parentType.id  as parentTypeId, parentType.name as parentTypeName FROM employmenttypes 
	LEFT JOIN employmenttypes as parentType ON parentType.id = employmenttypes.parentId 
    WHERE  employmenttypes.isActive = 1 AND employmenttypes.isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerBankDetail`(IN _partnerId INT)
BEGIN
	SELECT partnerbankdetails.*, banks.name as bankName FROM partnerbankdetails INNER JOIN banks ON banks.id = partnerbankdetails.bankId WHERE partnerbankdetails.partnerId =  _partnerId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerById`(IN _partnerId INT)
BEGIN
	 SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, roles.name as roleName, partners.*
    , partneraddress.id as partnerAddressId, partneraddress.addressTypeId as addressTypeId, partneraddress.label as label, partneraddress.addressLine1 as addressLine1
	, partneraddress.addressLine2 as addressLine2, partneraddress.pincode as pincode, partneraddress.cityId as cityId, cities.name as city,districts.name as district,states.name as state, addresstypes.name as addressType, partnereducations.id as partnerEducationId
	, partnereducations.educationTypeId, partnereducations.id as partnerEducationId, educationtypes.name as educationType, partnereducations.resume as resume, partnereducations.passingYear as passingYear, partnereducations.otherDetail as otherDetail
    FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
    INNER JOIN roles ON roles.id = userroles.roleId
	INNER JOIN partners ON partners.userId = users.id
	LEFT JOIN partneraddress ON partneraddress.partnerId = partners.id 
    LEFT JOIN cities ON cities.id = partneraddress.cityId
    LEFT JOIN districts ON cities.districtId = districts.id
    LEFT JOIN states ON states.id = districts.stateId
	LEFT JOIN addresstypes ON addresstypes.id = partneraddress.addressTypeId
	LEFT JOIN partnereducations ON partnereducations.partnerId = partners.id 
	LEFT JOIN educationtypes ON educationtypes.id = partnereducations.educationTypeId
    WHERE partners.id = _partnerId;

	SELECT partnereducations.*, educationtypes.name FROM partnereducations 
	INNER JOIN educationtypes ON educationtypes.id = partnereducations.educationTypeId WHERE partnereducations.partnerId = _partnerId;

	SELECT partnerdocuments.*, documentmasters.name from partnerdocuments INNER JOIN documentmasters ON documentmasters.id = partnerdocuments.documentId WHERE partnerdocuments.partnerId = _partnerId;

	SELECT bankloanpartnercommissions.*, banks.name as bankName, commissiontypes.name as commissionType, services.name as serviceName FROM bankloanpartnercommissions 
	INNER JOIN banks ON banks.id = bankloanpartnercommissions.bankId
	INNER JOIN commissiontypes ON commissiontypes.id = bankloanpartnercommissions.commissionTypeId
	INNER JOIN services ON services.id = bankloanpartnercommissions.serviceId WHERE bankloanpartnercommissions.partnerId = _partnerId;
    
	SELECT customerloans.*, services.name as serviceName, customers.fullName, users.profilePicUrl FROM partnerscustomerloans 
    INNER JOIN customerloans ON customerloans.id =  partnerscustomerloans.customerLoanId  AND customerloans.isDelete = 0
    INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN users ON users.id = customers.userId
	INNER JOIN services ON services.Id = customerloans.serviceId
    
    WHERE partnerscustomerloans.partnerId = _partnerId
    ORDER BY customerloans.id DESC;
    
	SELECT customers.*, users.profilePicUrl FROM partnerscustomerloans 
    INNER JOIN customerloans ON customerloans.id =  partnerscustomerloans.customerLoanId
    INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN users ON users.id = customers.userId
	INNER JOIN services ON services.Id = customerloans.serviceId
    
    WHERE partnerscustomerloans.partnerId = _partnerId GROUP BY customers.id
    ORDER BY customers.id DESC;
    
    select assignuserstraining.*, trainings.title as title, trainings.url as url, trainings.fileName as fileName, trainings.documentType as documentType,trainings.trainingCategoryId,trainings.trainingSubCategoryId,triningcategories.name as categoryName
	from assignuserstraining INNER JOIN trainings ON trainings.id = assignuserstraining.trainingId INNER JOIN triningcategories ON triningcategories.id = trainings.trainingCategoryId WHERE assignuserstraining.partnerId = _partnerId ORDER BY assignuserstraining.id DESC;
    
    SELECT partneraddress.*, addresstypes.name as addressType  from partneraddress INNER JOIN addresstypes ON addresstypes.id = partneraddress.addressTypeId 
    WHERE partneraddress.partnerId = _partnerId;
    
    SELECT visitingCardId,location FROM partnervisitingcards WHERE partnerId = _partnerId;
    
    SELECT partners.id,partners.fullName,partners.contactNo,partners.gender,partners.panCardNo,partners.cityId,partners.temporaryCode,partners.permanentCode,partners.companyName,partners.companyTypeId,partners.businessName,partners.isDelete,partners.createdDate,partners.isActive,cities.name as city,companytypes.name as companyType FROM partners 
    INNER JOIN users ON partners.userId = users.id 
    INNER JOIN userroles ON userroles.userId = partners.userId 
    LEFT JOIN companytypes ON companytypes.id = partners.companyTypeId 
    LEFT JOIN cities ON cities.id = partners.cityId 
    WHERE userroles.roleId = 5 AND partners.createdBy = (SELECT userId FROM partners WHERE id = _partnerId); 
    
    SELECT partners.id,partners.fullName,partners.contactNo,partners.gender,partners.panCardNo,partners.cityId,partners.temporaryCode,partners.permanentCode,partners.companyName,partners.companyTypeId,partners.businessName,partners.isDelete,partners.createdDate,partners.isActive,cities.name as city,companytypes.name as companyType,roles.name as roleName FROM partners 
    INNER JOIN userroles ON partners.userId = userroles.userId 
    INNER JOIN roles ON userroles.roleId = roles.id 
	LEFT JOIN companytypes ON companytypes.id = partners.companyTypeId 
    LEFT JOIN cities ON cities.id = partners.cityId 
    WHERE partners.parentPartnerId = _partnerId AND userroles.roleId NOT IN (5);
    
    SELECT userwallet.coin as totalCoin,userwallethistory.*,rewardtypes.name FROM userwallethistory
    LEFT JOIN rewardtypes ON userwallethistory.rewardType = rewardtypes.id
    LEFT JOIN users ON users.id = userwallethistory.userId
    LEFT JOIN partners ON partners.userId = users.id
    LEFT JOIN userwallet ON userwallethistory.userWalletId = userwallet.id
	WHERE partners.id = _partnerId;  
    
	SELECT partnercommissionhistory.*,partnerinvoice.url,customers.fullName as customerName,services.name as serviceName,customerloans.createdDate as applyDate FROM partnercommissionhistory LEFT JOIN partnerinvoice ON partnerinvoice.partnerCommissionHistoryId = partnercommissionhistory.id LEFT JOIN customerloandetail ON customerloandetail.id = partnercommissionhistory.loanDetailId LEFT JOIN customerloans ON customerloans.id = customerloandetail.customerLoanId LEFT JOIN customers ON customers.id = customerloans.customerId LEFT JOIN services ON services.id = customerloans.serviceId WHERE partnercommissionhistory.partnerId = _partnerId AND partnercommissionhistory.type = 'IN';
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerByParentPartnerId`(IN _partnerId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SET @sql = CONCAT("SELECT users.id as userId, users.profilePicUrl, users.contactNo, partners.permanentCode,partners.id as partnerId ,  userroles.roleId as roleId, roles.name as roleName, partners.fullName  FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	Left JOIN roles ON roles.id = userroles.roleId
	INNER JOIN partners ON partners.userId = users.id
	WHERE partners.parentPartnerId =", _partnerId," AND partners.isDelete = 0
    LIMIT ", _fetchRecords," OFFSET ", _startIndex," 
    ");
    PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerByRoleIdandPartnerId`(IN _partnerId INT,IN _roleIds TEXT,IN _startIndex INT,IN _fetchrecords INT)
BEGIN
        SET @sql = CONCAT_WS('',"SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, roles.name as roleName, partners.* 
        , partneraddress.id as partnerAddressId, partneraddress.addressTypeId as addressTypeId, partneraddress.label as label, partneraddress.addressLine1 as addressLine1
        , partneraddress.addressLine2 as addressLine2, partneraddress.pincode as pincode, partneraddress.cityId as cityId, cities.name as city, addresstypes.name as addressType
    , partnereducations.id as partnerEducationId, partnereducations.educationTypeId, partnereducations.id as partnerEducationId, educationtypes.name as educationType
    , partnereducations.resume as resume, partnereducations.instituteName as instituteName, partnereducations.passingYear as passingYear, partnereducations.otherDetail as otherDetail FROM users 
        INNER JOIN userroles ON userroles.userId = users.id 
        INNER JOIN roles ON roles.id = userroles.roleId
        INNER JOIN partners ON partners.userId = users.id
        LEFT JOIN partneraddress ON partneraddress.partnerId = partners.id 
    LEFT JOIN cities ON cities.id = partneraddress.cityId
        LEFT JOIN addresstypes ON addresstypes.id = partneraddress.addressTypeId
        LEFT JOIN partnereducations ON partnereducations.partnerId = partners.id 
        LEFT JOIN educationtypes ON educationtypes.id = partnereducations.educationTypeId
        WHERE partners.parentPartnerId =", _partnerId, " AND partners.isDelete = 0 AND  userroles.roleId IN(",_roleIds,")");
    IF _startIndex >= 0 AND _fetchRecords >0 THEN
    SET @sql = CONCAT_WS('',@sql," LIMIT ", _fetchRecords," OFFSET ", _startIndex);
    END IF;
    PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerCommission`(IN _partnerId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SELECT bankloanpartnercommissions.*, banks.name as bankName, commissiontypes.name as commissionType, services.name as serviceName FROM bankloanpartnercommissions 
	INNER JOIN banks ON banks.id = bankloanpartnercommissions.bankId
    INNER JOIN commissiontypes ON commissiontypes.id = bankloanpartnercommissions.commissionTypeId
    INNER JOIN services ON services.id = bankloanpartnercommissions.serviceId WHERE bankloanpartnercommissions.partnerId = _partnerId
    LIMIT _fetchRecords OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetPartnerRoles`()
BEGIN
	SELECT * FROM roles WHERE name NOT IN('ADMINISTRATOR','CUSTOMERS','SUBDSA');
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetProfessionTypes`()
BEGIN
	SELECT * FROM professiontypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarGetVisitingCard`(IN _roleId INT,IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SELECT COUNT(visitingcards.id) as totalCount FROM visitingcards INNER JOIN rolesvisitingcards ON visitingcards.id = rolesvisitingcards.visitingCardId WHERE rolesvisitingcards.roleId = _roleId AND visitingcards.isActive = 1 AND visitingcards.isDelete = 0;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT visitingcards.* FROM visitingcards INNER JOIN rolesvisitingcards ON visitingcards.id = rolesvisitingcards.visitingCardId WHERE rolesvisitingcards.roleId = ", _roleId," AND visitingcards.isActive = 1 AND visitingcards.isDelete = 0 ORDER BY visitingcards.id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertPartner`(IN _roleId INT, IN _temporaryCode VARCHAR(45), IN _fullName VARCHAR(200), IN _gender VARCHAR(20), IN _email VARCHAR(256), IN _countryCode VARCHAR(6), IN _contactNo VARCHAR(45)
, IN _aadhaarCardNo VARCHAR(20), IN _panCardNo VARCHAR(20), IN _cityId INT, IN _companyName VARCHAR(100), IN _professionTypeId INT, IN _workExperience DECIMAL(5,2), IN _haveOffice BOOLEAN
, IN _businessName VARCHAR(100) , IN _businessAddress TEXT,  IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _workAddressCityId INT,IN _jobType VARCHAR(45), IN _gstNo VARCHAR(20), IN _commitment DECIMAL(13,3), IN _referralCode VARCHAR(45), IN _parentPartnerId INT, IN _designationId INT,IN _userId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_user CURSOR FOR SELECT users.id FROM users WHERE users.contactNo = _contactNo;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_user;
			cur_user_loop: LOOP
				FETCH cur_user INTO cUserId;
                IF finished = 1 THEN
					LEAVE cur_user_loop;
				END IF;
            END LOOP cur_user_loop;
        CLOSE cur_user;
        IF cUserId>0 THEN
			SELECT 'Contact No Already Exist' as message;
        ELSE
			INSERT INTO users(fullName, gender, email, countryCode, contactNo, isDisabled,createdBy,modifiedBy,currentRoleId) VALUES(_fullName, _gender, _email, _countryCode, _contactNo, true,_userId,_userId,_roleId);
			SET @userId = LAST_INSERT_ID();
			INSERT INTO userroles(userId, roleId) VALUES(@userId, _roleId);
			INSERT INTO 
			partners(userId, temporaryCode, fullName, gender, contactNo, aadhaarCardNo, panCardNo, cityId, companyName, professionTypeId, workExperience, haveOffice, businessName, businessAddress, addressLine1, addressLine2, pincode, workAddressCityId, jobType,  gstNo, commitment, referralCode,currentBadgeId,parentPartnerId, designationId,createdBy,modifiedBy) 
			VALUES(@userId, _temporaryCode, _fullName, _gender, _contactNo, _aadhaarCardNo, _panCardNo, _cityId, _companyName, _professionTypeId, _workExperience, _haveOffice, _businessName, _businessAddress, _addressLine1, _addressLine2, _pincode, _workAddressCityId , _jobType, _gstNo, _commitment, _referralCode,1, _parentPartnerId, _designationId,_userId,_userId);
			SET @insertId = LAST_INSERT_ID();
            SELECT @insertId as insertId;
            INSERT INTO partnerbadges (partnerId,badgeId,createdBy,modifiedBy) VALUES (@insertId,1,_userId,_userId);
            SELECT 1 as currentBadgeId;
           
            SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = @userId;
            SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, partners.* FROM users 
            INNER JOIN userroles ON userroles.userId = users.id INNER JOIN partners ON partners.userId = users.id 
            WHERE users.id = @userId;
			SELECT partnerdocuments.url as profilePicUrl FROM partnerdocuments 
            WHERE partnerId = @insertId;
            IF _parentPartnerId>0 THEN
				SELECT partners.* FROM partners WHERE id = _parentPartnerId;             
            END IF;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertPartnerDocument`(IN _partnerId INT, IN _documentId INT, IN _url TEXT)
BEGIN
	INSERT INTO partnerdocuments(partnerId, documentId, url) VALUES(_partnerId, _documentId, _url);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertPartnerEducation`(IN _partnerId INT, IN _educationTypeId INT, IN _resume TEXT, IN _instituteName TEXT, IN _passingYear INT, IN _otherDetail TEXT)
BEGIN
	INSERT INTO partnereducations(partnerId, educationTypeId, resume, instituteName, passingYear, otherDetail) VALUES(_partnerId, _educationTypeId, _resume, _instituteName, _passingYear, _otherDetail);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertPartnerInNetwork`(IN _partnerId INT, IN _networkPartnerId INT, IN _userId INT)
BEGIN
	INSERT INTO partnernetworks(partnerId, networkPartnerId, createdBy, modifiedBy) VALUES(_partnerId, _networkPartnerId, _userId, _userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertPartnerInTeam`(IN _partnerId INT, IN _teamPartnerId INT, IN _userId INT)
BEGIN
	INSERT INTO partnerteams(partnerId, teamPartnerId, createdBy, modifiedBy) VALUES(_partnerId, _teamPartnerId, _userId, _userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInsertUpdateCommission`(IN _bankLoanPartnerCommissionId INT, IN _partnerId INT, IN _commissionTypeId INT, IN _bankId INT, IN _serviceId INT
, IN _commissionTemplateId INT, IN _commission DECIMAL(5,2), IN _userId INT)
BEGIN
	DECLARE cBankLoanCommissionId INT DEFAULT 0;
    DECLARE finished INT DEFAULT 0;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_bank_loan_commission CURSOR FOR SELECT bankloancommissions.id FROM bankloancommissions WHERE bankloancommissions.bankId = _bankId AND bankloancommissions.serviceId = _serviceId;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
            OPEN  cur_bank_loan_commission;
				cur_bank_loan_commission_loop: LOOP
					FETCH cur_bank_loan_commission INTO cBankLoanCommissionId;
                    
                    IF finished = 1 THEN
						LEAVE cur_bank_loan_commission_loop;
					END IF;
                    
                END LOOP cur_bank_loan_commission_loop;
			CLOSE cur_bank_loan_commission;
            -- SELECT cBankLoanCommissionId, _bankLoanPartnerCommissionId;
            IF cBankLoanCommissionId >0 THEN
				IF _bankLoanPartnerCommissionId>0 THEN
					UPDATE bankloanpartnercommissions SET partnerId=_partnerId, bankLoanCommissionId=cBankLoanCommissionId, commissionTypeId=_commissionTypeId, bankId=_bankId, serviceId=_serviceId
                    , commissionTemplateId = _commissionTemplateId, commission=_commission, modifiedBy=_userId, modifiedDate=CURRENT_TIMESTAMP() WHERE id = _bankLoanPartnerCommissionId;
                    SELECT _bankLoanPartnerCommissionId as bankLoanPartnerCommissionId;
                ELSE
					INSERT INTO bankloanpartnercommissions(partnerId, bankLoanCommissionId, commissionTypeId, bankId, serviceId, commissionTemplateId, commission, createdBy, modifiedBy) 
						VALUES(_partnerId, cBankLoanCommissionId, _commissionTypeId, _bankId, _serviceId, _commissionTemplateId, _commission, _userId, _userId);
					SET @insertId = LAST_INSERT_ID();
					SELECT @insertId as bankLoanPartnerCommissionId;                    
                END IF;
			ELSE
				SELECT "Bank Loan Commision is Not Set" as message;
            END IF;
        END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarInserUpdateBankDetail`(IN _partnerBankDetailId INT, IN _partnerId INT, IN _bankId INT, IN _accountHolderName TEXT, IN _accountNo VARCHAR(50), IN _ifscCode VARCHAR(45)
, IN _userId INT)
BEGIN
	IF _partnerBankDetailId > 0 THEN
		UPDATE partnerbankdetails SET bankId = _bankId, accountHolderName = _accountHolderName, accountNo = _accountNo, ifscCode = _ifscCode, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId
        WHERE id = _partnerBankDetailId;
        
        SELECT partnerbankdetails.*, banks.name as bankName FROM partnerbankdetails INNER JOIN banks ON banks.id = partnerbankdetails.bankId WHERE partnerbankdetails.id =  _partnerBankDetailId;
    ELSE
		INSERT INTO partnerbankdetails(partnerId, bankId, accountHolderName, accountNo, ifscCode, createdBy, modifiedBy) 
        VALUES(_partnerId, _bankId, _accountHolderName, _accountNo, _ifscCode, _userId, _userId);
        SET @insertId = LAST_INSERT_ID();
        
        SELECT partnerbankdetails.*, banks.name as bankName FROM partnerbankdetails INNER JOIN banks ON banks.id = partnerbankdetails.bankId WHERE partnerbankdetails.id =  @insertId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarLogin`(IN _contactNo VARCHAR(15), IN _appId INT, IN _deviceId VARCHAR(300), IN _fcmToken VARCHAR(500), IN _deviceManufacturer VARCHAR(300), IN _deviceModel VARCHAR(100), IN _sessionToken TEXT, IN _appVersion VARCHAR(100))
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE session_done INT DEFAULT 0;
    DECLARE deviceDetail_done INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cIsDisabled INT DEFAULT 1;
    DECLARE cRoleId INT DEFAULT 0;
    DECLARE cRoleName VARCHAR(45) DEFAULT NULL;
    DECLARE cParentPartnerId INT DEFAULT 0;
    DECLARE cAppId INT DEFAULT 0;
    DECLARE dAppId INT DEFAULT 0;
	DECLARE dfcmToken VARCHAR(500) DEFAULT NULL;
	DECLARE dDeviceId VARCHAR(100) DEFAULT NULL;
     DECLARE insertDeviceDetailFlag INT DEFAULT 0;
     
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
    
	START TRANSACTION;
     SET @insertDeviceDetailFlag = 0;
    BEGIN
   
		DECLARE cur_user CURSOR FOR SELECT users.id, users.isDisabled, roles.id as roleId, roles.name as roleName, partners.parentPartnerId FROM users 
									INNER JOIN userroles ON userroles.userId = users.id 
									INNER JOIN roles ON roles.id = userroles.roleId
									INNER JOIN partners ON partners.userId = users.Id
									WHERE users.contactNo = _contactNo AND userroles.roleId IN(3,4,5,6);
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
		OPEN  cur_user;
			cur_user_loop: LOOP

				FETCH cur_user INTO cUserId, cIsDisabled, cRoleId, cRoleName, cParentPartnerId;
                IF finished = 1 THEN
					LEAVE cur_user_loop;
				END IF;
               
                IF cUserId>0 AND cRoleId >0 AND cIsDisabled=0 THEN
               
					BEGIN                  
						DECLARE cur_session CURSOR FOR SELECT usersessions.appId FROM users INNER JOIN usersessions ON users.id = usersessions.userId WHERE usersessions.sessionToken = (SELECT se.sessionToken FROM usersessions se WHERE se.userId = cUserId  ORDER BY id DESC LIMIT 1)  AND usersessions.expireAt > CURDATE();
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET session_done = 1;
                        OPEN  cur_session;
							cur_get_session: LOOP
								FETCH cur_session INTO cAppId;
                                IF session_done = 1 THEN
									LEAVE cur_get_session;
								END IF;
                                IF cRoleId > 2 THEN
                               
									BEGIN
										DECLARE cur_deviceDetails CURSOR FOR SELECT userdevicedetail.appId, userdevicedetail.deviceId, userdevicedetail.fcmToken FROM userdevicedetail  WHERE userdevicedetail.userId = cUserId;
										DECLARE CONTINUE HANDLER FOR NOT FOUND SET deviceDetail_done = 1;
                                        OPEN  cur_deviceDetails;
											cur_get_deviceDetails:LOOP
												FETCH cur_deviceDetails INTO dAppId, dDeviceId, dfcmToken;
                                                IF deviceDetail_done = 1 THEN
                                              
                                           IF (@insertDeviceDetailFlag = 0 OR @insertDeviceDetailFlag IS NULL) THEN
                                       
								
													INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
													VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
												SET @insertDeviceDetailFlag = 1;
												END IF;
                                                	LEAVE cur_get_deviceDetails;
                                                END IF;
                                               
                                                IF dAppId > 0 THEN
                                               
													IF cAppId > 0 THEN
														IF cAppId != dAppId THEN
															INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
															VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
                                                              SET @insertDeviceDetailFlag = 1;
                                                        ELSE 
															UPDATE userdevicedetail SET deviceId = _deviceId,fcmToken = _fcmToken , deviceManufacturer = _deviceManufacturer, deviceModel = _deviceModel, modifiedDate = current_timestamp()  WHERE userId= cUserId;
                                                         SET @insertDeviceDetailFlag = 1;
                                                       END IF;
                                                    ELSE
														IF dDeviceId != deviceId OR dfcmToken != fcmToken THEN
															UPDATE userdevicedetail SET deviceId = _deviceId,fcmToken = _fcmToken , deviceManufacturer = _deviceManufacturer, deviceModel = _deviceModel, modifiedDate = current_timestamp() WHERE userId= cUserId;
                                                         SET @insertDeviceDetailFlag = 1;
														END IF;
                                                    END IF;
												ELSE

													INSERT INTO userdevicedetail (userId, appId, deviceId, fcmToken, deviceLocation, deviceManufacturer, deviceModel, appVersion)
													VALUES(cUserId, _appId, _deviceId, _fcmToken, NULL, _deviceManufacturer, _deviceModel, _appVersion);
													SET @insertDeviceDetailFlag = 1;
                                              END IF;
                                            END LOOP cur_get_deviceDetails;
                                        CLOSE cur_deviceDetails;
									END;
                                END IF;
                            END LOOP cur_get_session;
                        CLOSE cur_session;
                    END;
                ELSE 
                    LEAVE cur_user_loop;
                END IF;
            END LOOP cur_user_loop;
		CLOSE cur_user;
		IF cIsDisabled = 0 THEN
			SELECT users.currentRoleId as roleId, roles.name From users INNER JOIN roles ON roles.id = users.currentRoleId WHERE users.id = cUserId;
            
            INSERT INTO usersessions(sessionToken, appId, expireAt, userId) VALUES(_sessionToken, _appId, TIMESTAMPADD(DAY,60,CURRENT_TIMESTAMP()), cUserId);
            
            SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, users.currentRoleId as roleId, partners.* FROM users INNER JOIN userroles ON userroles.userId = users.id INNER JOIN partners ON partners.userId = users.id WHERE users.contactNo = _contactNo AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(3,4,5,6);
			
            SELECT partnerdocuments.url as profilePicUrl FROM partnerdocuments WHERE partnerId in (select id from partners where userId in (select id from users where contactNo = _contactNo)  );
            
            SELECT partneraddress.*, cities.name as city, districts.name as district, districts.id as districtId, states.name as state, states.id as stateId 
            FROM partneraddress LEFT JOIN cities ON cities.id = partneraddress.cityId LEFT JOIN districts ON districts.id = cities.districtId 
            LEFT JOIN states ON states.id = districts.stateId WHERE partneraddress.partnerId = (select partners.id from partners WHERE partners.userId = cUserId);
            
            SELECT partnereducations.* FROM partnereducations  WHERE partnereducations.partnerId = (select partners.id from partners WHERE partners.userId = cUserId);
         
            -- IF cParentPartnerId>0 THEN
				SELECT partners.* FROM partners WHERE id = cParentPartnerId;
             
            -- END IF;
			
            SELECT partners.* FROM partners  WHERE partners.id = (select partners.id from partners WHERE partners.userId = cUserId);
            
            
		ELSE
			SELECT 'User Not Verified' as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarPartnerAddress`(IN _partnerId INT, IN _addressTypeId INT, IN _label VARCHAR(45), IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT)
BEGIN
	INSERT INTO partneraddress(partnerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId) VALUES(_partnerId, _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarSignUp`(IN _roleId INT, IN _temporaryCode VARCHAR(45), IN _fullName VARCHAR(200), IN _gender VARCHAR(20), IN _email VARCHAR(256), IN _countryCode VARCHAR(6), IN _contactNo VARCHAR(45)
, IN _aadhaarCardNo VARCHAR(20), IN _panCardNo VARCHAR(20), IN _cityId INT, IN _companyName VARCHAR(100), IN _professionTypeId INT, IN _workExperience DECIMAL(5,2), IN _haveOffice BOOLEAN
, IN _businessName VARCHAR(100), IN _businessAddress TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _workAddressCityId INT,IN _jobType VARCHAR(45), IN _gstNo VARCHAR(20), IN _commitment DECIMAL(13,3), IN _referralCode VARCHAR(45), IN _parentPartnerId INT, IN _designationId INT
, IN _badgeId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
	BEGIN
		DECLARE cur_user CURSOR FOR SELECT users.id FROM users WHERE users.contactNo = _contactNo;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_user;
			cur_user_loop: LOOP
				FETCH cur_user INTO cUserId;
                IF finished = 1 THEN
					LEAVE cur_user_loop;
				END IF;
            END LOOP cur_user_loop;
        CLOSE cur_user;
        IF cUserId>0 THEN
			SELECT 'Contact No Already Exist' as message;
        ELSE
			INSERT INTO users(fullName, gender, email, countryCode, contactNo, isDisabled,currentRoleId) VALUES(_fullName, _gender, _email, _countryCode, _contactNo, true,_roleId);
			SET @userId = LAST_INSERT_ID();
			INSERT INTO userroles(userId, roleId) VALUES(@userId, _roleId);
			INSERT INTO 
			partners(userId, temporaryCode, fullName, gender, contactNo, aadhaarCardNo, panCardNo, cityId, companyName, professionTypeId, workExperience, haveOffice, businessName, businessAddress,  addressLine1, addressLine2, pincode, workAddressCityId, jobType, gstNo, commitment, referralCode, parentPartnerId, designationId, currentBadgeId) 
			VALUES(@userId, _temporaryCode, _fullName, _gender, _contactNo, _aadhaarCardNo, _panCardNo, _cityId, _companyName, _professionTypeId, _workExperience, _haveOffice, _businessName, _businessAddress,  _addressLine1, _addressLine2, _pincode, _workAddressCityId , _jobType, _gstNo, _commitment, _referralCode, _parentPartnerId, _designationId, _badgeId);
			SET @insertId = LAST_INSERT_ID();
			SELECT @insertId as insertId,@userId as userId;
            INSERT INTO partnerbadges(partnerId, badgeId, createdBy, modifiedBy) VALUES(@insertId, _badgeId, @userId, @userId);
        END IF;
    END;
 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarUpdatePartner`(IN _partnerId INT, IN _userId INT,IN _fullName VARCHAR(200), IN _gender VARCHAR(20), IN _email VARCHAR(256), IN _contactNo VARCHAR(45)
, IN _aadhaarCardNo VARCHAR(20), IN _panCardNo VARCHAR(20), IN _cityId INT, IN _companyName VARCHAR(100), IN _professionTypeId INT, IN _workExperience DECIMAL(5,2), IN _haveOffice BOOLEAN
, IN _businessName VARCHAR(100), IN _businessAddress TEXT, IN _businessaddressLine1 TEXT, IN _businessaddressLine2 TEXT, IN _businesspincode VARCHAR(10), IN _workAddressCityId INT, IN _jobType VARCHAR(45), IN _gstNo VARCHAR(20), IN _commitment DECIMAL(13,3), IN _referralCode VARCHAR(45), IN _parentPartnerId INT
, IN _designationId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";

	UPDATE users SET fullName = _fullName, gender = _gender, email = _email, contactNo = _contactNo WHERE id = _userId;
    SET @UpdateQuery = "";
	SET @SetStatement = "";
        
    SET @UpdateQuery =  CONCAT_WS('',"UPDATE partners SET modifiedDate = '" ,CURRENT_TIMESTAMP(),"',addressLine2 = '",_businessaddressLine2,"'") ;
	
    
    IF _fullName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", fullName = '",_fullName,"'");
	END IF;
    IF _gender != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", gender = '",_gender,"'");
	END IF;
    IF _contactNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", contactNo = '",_contactNo,"'");
	END IF;
    IF _aadhaarCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", aadhaarCardNo = '",_aadhaarCardNo,"'");
	END IF;
    IF _panCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", panCardNo = '",_panCardNo,"'");
	END IF;
    IF _cityId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
	END IF;
    IF _companyName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
	END IF;
    IF _professionTypeId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", professionTypeId = ",_professionTypeId);
	END IF;
    IF _workExperience > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", workExperience = ",_workExperience);
	END IF;
    IF _haveOffice != '' THEN
   			SET @SetStatement = CONCAT_WS('', @SetStatement, ", haveOffice = '",_haveOffice,"'");
	END IF;
    IF _businessName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", businessName = '",_businessName,"'");
	END IF;
    IF _businessAddress != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", businessAddress = '",_businessAddress,"'");
	END IF;
    IF _gstNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", gstNo = '",_gstNo,"'");
	END IF;
    IF _commitment > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", commitment = ",_commitment);
	END IF;
	IF _referralCode != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", referralCode = '",_referralCode,"'");
	END IF;
    IF _parentPartnerId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", parentPartnerId = ",_parentPartnerId);
	END IF;
	IF _designationId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
	END IF;
    IF _businessaddressLine1 != '' THEN
		SET @SetStatement = CONCAT_WS('', @SetStatement, ", addressLine1 = '",_businessaddressLine1,"'");
	END IF;
	IF _businesspincode != '' THEN
		SET @SetStatement = CONCAT_WS('', @SetStatement, ", pincode = '",_businesspincode,"'");
	END IF;
     IF _workAddressCityId != '' THEN
		SET @SetStatement = CONCAT_WS('', @SetStatement, ", workAddressCityId = ",_workAddressCityId);
	END IF;
     IF _jobType != '' THEN
		SET @SetStatement = CONCAT_WS('', @SetStatement, ", jobType = '",_jobType,"'");
	END IF;
	
	SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_partnerId);
	PREPARE stmt FROM @UpdateQuery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarUpdatePartnerAddress`(IN _partnerAddressId INT, IN _partnerId INT, IN _addressTypeId INT, IN _label VARCHAR(45), IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT)
BEGIN
	UPDATE partneraddress SET partnerId = _partnerId, addressTypeId = _addressTypeId, label = _label, addressLine1= _addressLine1, addressLine2 = _addressLine2, pincode = _pincode
    , cityId = _cityId WHERE id = _partnerAddressId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarUpdatePartnerEducation`(IN _partnerEducationId INT,IN _partnerId INT, IN _educationTypeId INT, IN _resume TEXT, IN _instituteName TEXT, IN _passingYear INT
, IN _otherDetail TEXT)
BEGIN
	UPDATE partnereducations SET partnerId = _partnerId, educationTypeId =  _educationTypeId, resume = _resume, instituteName = _instituteName, passingYear = _passingYear
    , otherDetail = _otherDetail WHERE id = _partnerEducationId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarUpdatePartnerProfile`(IN _userId INT, IN _partnerId INT, IN _fullName VARCHAR(200), IN _contactNo VARCHAR(15), IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20)
, IN _gender VARCHAR(20), IN _partnerAddressId INT, IN _addressTypeId INT, IN _label VARCHAR(45), IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT
, IN _companyName VARCHAR(100), IN _professionTypeId INT, IN _workExperience DECIMAL(5,2), IN _haveOffice BOOLEAN, IN _businessName VARCHAR(100), IN _businessAddress TEXT
, IN _businessaddressLine1 TEXT, IN _businessaddressLine2 TEXT, IN _businesspincode VARCHAR(10), IN _workAddressCityId INT, IN _jobType VARCHAR(45), IN _gstNo VARCHAR(20)
, IN _commitment DECIMAL(13,3))
BEGIN
	UPDATE partners SET fullName=_fullName, contactNo=_contactNo, panCardNo=_panCardNo, aadhaarCardNo=_aadhaarCardNo, gender = _gender, cityId = _cityId, companyName = _companyName
    , professionTypeId = _professionTypeId, workExperience = _workExperience, haveOffice = _haveOffice, businessName = _businessName, businessAddress = _businessAddress
    , addressLine1 = _businessaddressLine1, addressLine2 = _businessaddressLine2, pincode = _businesspincode, workAddressCityId = _workAddressCityId, jobType = _jobType, gstNo = _gstNo
    , commitment = _commitment
    WHERE id = _partnerId;
    
    UPDATE partneraddress SET partnerId = _partnerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2, pincode = _pincode
    , cityId = _cityId WHERE id = _partnerAddressId;
    
    UPDATE users SET fullName=_fullName, contactNo=_contactNo, gender = _gender WHERE id = _userId;
    
    SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = _userId;
    
    SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, partners.* 
    FROM users INNER JOIN userroles ON userroles.userId = users.id INNER JOIN partners ON partners.userId = users.id 
    WHERE users.id = _userId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(3,4,5,6);
    
    SELECT partneraddress.*, cities.name as city, districts.name as district, districts.id as districtId, states.name as state, states.id as stateId 
    FROM partneraddress LEFT JOIN cities ON cities.id = partneraddress.cityId LEFT JOIN districts ON districts.id = cities.districtId 
    LEFT JOIN states ON states.id = districts.stateId WHERE partneraddress.partnerId = (select partners.id from partners WHERE partners.userId = _userId);
    
    SELECT partnereducations.* FROM partnereducations  WHERE partnereducations.partnerId = (select partners.id from partners WHERE partners.userId = _userId);
	
    SELECT partners.* FROM partners WHERE id = (select partners.parentPartnerId from partners WHERE partners.userId = _userId);
	SELECT currentBadgeId FROM partners WHERE id = _partnerId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarUpdatePartnerProfileWithPic`(IN _userId INT, IN _partnerId INT, IN _fullName VARCHAR(200), IN _contactNo VARCHAR(15), IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20)
, IN _gender VARCHAR(20), IN _partnerAddressId INT, IN _addressTypeId INT, IN _label VARCHAR(45), IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT
, IN _companyName VARCHAR(100), IN _professionTypeId INT, IN _workExperience DECIMAL(5,2), IN _haveOffice BOOLEAN, IN _businessName VARCHAR(100), IN _businessAddress TEXT
, IN _businessaddressLine1 TEXT, IN _businessaddressLine2 TEXT, IN _businesspincode VARCHAR(10), IN _workAddressCityId INT, IN _jobType VARCHAR(45), IN _gstNo VARCHAR(20)
, IN _commitment DECIMAL(13,3), IN _profilePicUrl TEXT)
BEGIN
	UPDATE partners SET fullName=_fullName, contactNo=_contactNo, panCardNo=_panCardNo, aadhaarCardNo=_aadhaarCardNo, gender = _gender, cityId = _cityId, companyName = _companyName
    , professionTypeId = _professionTypeId, workExperience = _workExperience, haveOffice = _haveOffice, businessName = _businessName, businessAddress = _businessAddress
    , addressLine1 = _businessaddressLine1, addressLine2 = _businessaddressLine2, pincode = _businesspincode, workAddressCityId = _workAddressCityId, jobType = _jobType, gstNo = _gstNo, commitment = _commitment
    WHERE id = _partnerId;
    
    UPDATE partneraddress SET partnerId = _partnerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2, pincode = _pincode
    , cityId = _cityId WHERE id = _partnerAddressId;
    
    UPDATE users SET fullName=_fullName, contactNo=_contactNo, gender = _gender, profilePicUrl = _profilePicUrl WHERE id = _userId;
     UPDATE partnerdocuments SET  url = _profilePicUrl WHERE partnerId = _partnerId;
    SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = _userId;
    
    SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, partners.* 
    FROM users INNER JOIN userroles ON userroles.userId = users.id INNER JOIN partners ON partners.userId = users.id 
    WHERE users.id = _userId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(3,4,5,6);
    
    SELECT partneraddress.*, cities.name as city, districts.name as district, districts.id as districtId, states.name as state, states.id as stateId 
    FROM partneraddress LEFT JOIN cities ON cities.id = partneraddress.cityId LEFT JOIN districts ON districts.id = cities.districtId 
    LEFT JOIN states ON states.id = districts.stateId WHERE partneraddress.partnerId = (select partners.id from partners WHERE partners.userId = _userId);
    
    SELECT partnereducations.* FROM partnereducations  WHERE partnereducations.partnerId = (select partners.id from partners WHERE partners.userId = _userId);
	
    SELECT partners.* FROM partners WHERE id = (select partners.parentPartnerId from partners WHERE partners.userId = _userId);
    SELECT currentBadgeId FROM partners WHERE id = _partnerId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaBazarVerifySessionToken`(IN _sessionToken TEXT, IN _appId INT, IN _deviceId VARCHAR(300), IN _fcmToken VARCHAR(500), IN _deviceManufacturer VARCHAR(300), IN _deviceModel VARCHAR(100), IN _appVersion VARCHAR(100))
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
    DECLARE cParentPartnerId INT DEFAULT 0;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    
    SET @LastUpdateID := 0;
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
    UPDATE usersessions SET usersessions.modifiedDate = CURRENT_TIMESTAMP(), expireAt=TIMESTAMPADD(DAY,60,CURRENT_TIMESTAMP()), id = (SELECT @LastUpdateID := id)  WHERE sessionToken = _sessionToken;
    BEGIN
		DECLARE cur_user CURSOR FOR SELECT users.id, partners.parentPartnerId FROM users 
									INNER JOIN userroles ON userroles.userId = users.id 
									INNER JOIN usersessions ON users.id = usersessions.userId 
                                    INNER JOIN partners ON partners.userId = users.Id
									WHERE usersessions.sessionToken = _sessionToken 
                                    AND usersessions.expireAt > CURDATE() 
                                    AND users.isDisabled = 0 
                                    AND userroles.roleId IN(3,4,5,6);
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
		OPEN  cur_user;
			cur_user_loop: LOOP
				FETCH cur_user INTO cUserId, cParentPartnerId;
					IF finished = 1 THEN
						LEAVE cur_user_loop;
					END IF;
			END LOOP cur_user_loop;
		CLOSE cur_user;
        IF cUserId>0 THEN
			SELECT roles.id, roles.name From userroles INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.userId = cUserId;
            
            SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, partners.* FROM users INNER JOIN userroles ON userroles.userId = users.id INNER JOIN partners ON partners.userId = users.id WHERE users.id = cUserId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(3,4,5,6);
            SELECT partnerdocuments.url as profilePicUrl FROM partnerdocuments WHERE partnerId in (select id from partners where userId in (select userId from usersessions where sessionToken = _sessionToken)  );
            
            SELECT partneraddress.*, cities.name as city, districts.name as district, districts.id as districtId, states.name as state, states.id as stateId 
            FROM partneraddress LEFT JOIN cities ON cities.id = partneraddress.cityId LEFT JOIN districts ON districts.id = cities.districtId 
            LEFT JOIN states ON states.id = districts.stateId WHERE partneraddress.partnerId = (select partners.id from partners WHERE partners.userId = cUserId);
            
            SELECT partnereducations.* FROM partnereducations  WHERE partnereducations.partnerId = (select partners.id from partners WHERE partners.userId = cUserId);
            
           -- IF cParentPartnerId>0 THEN
				SELECT partners.* FROM partners WHERE id = cParentPartnerId;
           -- END IF;
            
            SELECT partners.* FROM partners  WHERE partners.id = (select partners.id from partners WHERE partners.userId = cUserId);
            
        ELSE
			SELECT 'User Not Verified' as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaDeleteLeads`(IN _leadId int)
BEGIN
	SET @sql = CONCAT('UPDATE leads
		SET isDelete = 1
		WHERE leads.id  IN (', _leadId,')');
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `dsaLeadAssignToPartner`(IN _leadId INT,IN _partnerId INT,IN _userId INT,IN _assignById INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
    
	BEGIN
			DECLARE cur_checkexist cursor for select id FROM leadstatushistory WHERE leadId = _leadId AND leadStatusId = 3;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getHistory: LOOP
					FETCH cur_checkexist INTO fetchedId;
					IF finished = 1 THEN 
						LEAVE getHistory;
					END IF;
					IF (fetchedId) THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist != 1 THEN		
			INSERT INTO leadstatushistory (leadId,leadStatusId,transactionDate,createdBy,modifiedBy) VALUES (_leadId,3,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE leads SET assignedById = _assignById,assignToPartnerId = _partnerId,assignOn = CURRENT_TIMESTAMP(),modifiedBY = _userId, leadStatusId = 3 WHERE id = _leadId;
		ELSE 
		   UPDATE leads SET assignedById = _assignById,assignToPartnerId = _partnerId,assignOn = CURRENT_TIMESTAMP(),modifiedBY = _userId, leadStatusId = 3  WHERE id = _leadId;
		END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `generateReferLink`(IN _userId INt, IN _roleId INT, IN _linkKey TEXT, IN _referCount INT)
BEGIN
	INSERT INTO referlinks(userId, roleId, linkKey, referCount, createdBy, modifiedBy) values(_userId, _roleId, _linkKey, _referCount, _userId, _userId);
    SET @referLinkId = LAST_INSERT_ID();
    SELECT * FROM referlinks WHERE id = @referLinkId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getAssignedLeadsOfNetwork`(IN _partnerId VARCHAR(200), IN _startIndex INt, IN _fetchRecords INT)
BEGIN
    SET @sql = CONCAT('SELECT leads.*,leads.id as leadId,services.name, customers.id as customerId, customers.temporaryCode as temporaryCode, customers.permanentCode as permanentCode, customers.fullName as fullName, customers.birthdate as birthdate
					, customers.gender as gender, customers.alternativeContactNo as alternativeContactNo, customers.maritalStatusId as maritalStatusId,customeraddresses.id as customerAddressId, customeraddresses.addressTypeId as addressTypeId
					, customeraddresses.label as label, customeraddresses.addressLine1 as addressLine1, customeraddresses.addressLine2 as addressLine2, customeraddresses.pincode as pincode, customeraddresses.cityId as cityId
					, customeraddresses.city as city, customeraddresses.district as district, customeraddresses.state as state ,partners.fullName as partnername , roles.name as rolename, leadstatuses.name as status 
					FROM leads 
					INNER JOIN services ON services.id = leads.serviceId 
					LEFT JOIN customers ON customers.contactNo = leads.contactNo
                    LEFT JOIN partners ON partners.id = leads.assignToPartnerId
					LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
                    INNER JOIN userroles ON userroles.userId = partners.userId 
	                INNER JOIN roles ON roles.id = userroles.roleId
                     LEFT JOIN leadstatuses ON leadstatuses.id = leads.leadStatusId
					WHERE  leads.assignToPartnerId  IN (', _partnerId,')   LIMIT ',_fetchRecords,' OFFSET ',_startIndex);
	
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCityByPincode`(IN _pincode VARCHAR(10))
BEGIN
	SELECT cities.*, districts.name as districtName, states.id as stateId, states.name as stateName FROM cities INNER JOIN districts ON districts.id = cities.districtId INNER JOIN states ON states.id = districts.stateId WHERE cities.pincode = _pincode;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCommissionTemplateByBankAndServiceId`(IN _bankId int,IN _serviceId int)
BEGIN
	SELECT commissiontemplate.*, commissiontypes.name as commissionTypeName, services.name as serviceName, banks.name as bankName FROM commissiontemplate
    INNER JOIN commissiontypes ON commissiontypes.id = commissiontemplate.commissionTypeId 
    INNER JOIN services ON services.id = commissiontemplate.serviceId 
    INNER JOIN banks ON banks.id = commissiontemplate.bankId 
    WHERE commissiontemplate.bankId= _bankId AND commissiontemplate.serviceId= _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCompanyCategoryType`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	SELECT * FROM companycategorytype WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCompletedVisitingCard`(IN _partnerId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
	
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM partnervisitingcards WHERE partnerId = ",_partnerId);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCustomerLoanListByStatusId`(IN _customerId INT, IN _statusId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SELECT customerloans.*, services.name as serviceName,customerloans.loanTransactionDate as applyDate, loanstatuses.status FROM customerloans
	INNER JOIN services ON services.Id = customerloans.serviceId
    LEFT JOIN loanstatuses on loanstatuses.id = customerloans.statusId
	WHERE customerloans.statusId = _statusId AND customerloans.customerId = _customerId
    ORDER BY customerloans.id DESC
	LIMIT _fetchRecords OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCustomerLoanRejectionReason`(IN _customerLoanId INT)
BEGIN
	SELECT * FROM customerloanrejectionreason WHERE customerLoanId = _customerLoanId AND isDelete =0 AND isActive = 1;
    SELECT * FROM reasons WHERE customerLoanId = _customerLoanId AND isDelete =0 AND isActive = 1;
    SELECT customers.fullName as customerName,customers.contactNo as customerContactNo from customers LEFT JOIN customerloans ON customerloans.customerId = customers.id WHERE customerloans.id = _customerLoanId  ;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getCustomerPersonalLoanByCustomerLoanId`(IN _customerId INT, IN _customerLoanId INT)
BEGIN
	SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
	FROM users 
	INNER JOIN userroles ON userroles.userId = users.id 
	INNER JOIN customers ON customers.userId = users.id 
	WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2);
            
	SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName,services.name as serviceName FROM customerloans 
	LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
	LEFT JOIN services ON  services.id = customerloans.serviceId
	WHERE customerloans.id = _customerLoanId AND customerloans.isDelete = 0;
    
    SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
	, companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
	FROM customerloanemploymentdetails 
	LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
	LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
	LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
	WHERE customerloanemploymentdetails.customerloanId = _customerLoanId;
    
    SELECT * FROM customerloanspouses WHERE customerloanId = _customerLoanId;
    
    SELECT customerloandocuments.*, documentmasters.name as documentName, servicetypedocuments.isPdf FROM customerloandocuments 
	LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
	LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
	WHERE customerloandocuments.customerloanId = _customerLoanId;
    
    SELECT customerloanreferences.*,customerreferenceaddresses.* FROM customerloanreferences
    LEFT JOIN customerreferenceaddresses ON  customerreferenceaddresses.customerLoanReferenceId = customerloanreferences.id
    WHERE customerloanId = _customerLoanId;
    
    SELECT * FROM loancompletescreenhistory WHERE customerloanId = _customerLoanId;
     
    SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
	FROM customerloanstatushistory 
	INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
	WHERE customerloanId = _customerLoanId;
    
    SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId = _customerLoanId AND clf.isShared = 1 AND clf.status IS NULL;
   
    SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customeraddresses.city,customeraddresses.state,customeraddresses.district
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id = _customerId AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 5 AND userroles.roleId IN(2);
            
   SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getDSABazaarCompletedVisitingCard`(IN _partnerId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
	
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM partnervisitingcards WHERE partnerId = ",_partnerId);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getFaqCategories`()
BEGIN
	SELECT * FROM faqcategories WHERE isDelete = 0 ORDER BY id desc ;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getLeadAssignByPartnerId`(IN _partnerId VARCHAR(200), IN _startIndex INt, IN _fetchRecords INT)
BEGIN
	SET @sql = CONCAT('SELECT leads.*,leads.id as leadId,services.name, customers.id as customerId, customers.temporaryCode as temporaryCode, customers.permanentCode as permanentCode, customers.fullName as fullName, customers.birthdate as birthdate
					, customers.gender as gender, customers.alternativeContactNo as alternativeContactNo, customers.maritalStatusId as maritalStatusId,customeraddresses.id as customerAddressId, customeraddresses.addressTypeId as addressTypeId
					, customeraddresses.label as label, customeraddresses.addressLine1 as addressLine1, customeraddresses.addressLine2 as addressLine2, customeraddresses.pincode as pincode, customeraddresses.cityId as cityId
					, customeraddresses.city as city, customeraddresses.district as district, customeraddresses.state as state
					FROM leads 
					INNER JOIN services ON services.id = leads.serviceId 
					LEFT JOIN customers ON customers.contactNo = leads.contactNo
					LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
					WHERE leads.assignToPartnerId  IN (', _partnerId,') AND leads.isDelete = 0 AND customeraddresses.addressTypeId = 1   LIMIT ',_fetchRecords,' OFFSET ',_startIndex);
	
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getLeadAssignByPartnerToNetwork`(IN _userId VARCHAR(200), IN _startIndex INt, IN _fetchRecords INT)
BEGIN
	SET @sql = CONCAT('SELECT leads.*,leads.id as leadId,services.name, customers.id as customerId, customers.temporaryCode as temporaryCode, customers.permanentCode as permanentCode, customers.fullName as fullName, customers.birthdate as birthdate
					, customers.gender as gender, customers.alternativeContactNo as alternativeContactNo, customers.maritalStatusId as maritalStatusId,customeraddresses.id as customerAddressId, customeraddresses.addressTypeId as addressTypeId
					, customeraddresses.label as label, customeraddresses.addressLine1 as addressLine1, customeraddresses.addressLine2 as addressLine2, customeraddresses.pincode as pincode, customeraddresses.cityId as cityId
					, customeraddresses.city as city, customeraddresses.district as district, customeraddresses.state as state ,partners.fullName as partnername , roles.name as rolename 
					FROM leads 
					INNER JOIN services ON services.id = leads.serviceId 
					LEFT JOIN customers ON customers.contactNo = leads.contactNo
                    LEFT JOIN partners ON partners.id = leads.assignToPartnerId
					LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
                    INNER JOIN userroles ON userroles.userId = partners.userId 
	                INNER JOIN roles ON roles.id = userroles.roleId
					WHERE  leads.assignedById  IN (', _userId,') LIMIT ',_fetchRecords,' OFFSET ',_startIndex);
	
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getLeadGeneratedByUserId`(IN _userIds TEXT, IN _startIndex INt, IN _fetchRecords INT)
BEGIN
	SET @sql = CONCAT('SELECT leads.*,leads.id as leadId,services.name, leadaddresses.id as leadaddressesid, leadaddresses.addressTypeId as addressTypeId
					, leadaddresses.label as label, leadaddresses.addressLine1 as addressLine1, leadaddresses.addressLine2 as addressLine2, leadaddresses.pincode as pincode, leadaddresses.cityId as cityId
					, leadaddresses.district as district, leadaddresses.state as state, leadstatuses.name as leadstatus 
					FROM leads 
					INNER JOIN services ON services.id = leads.serviceId 
                    LEFT JOIN leadaddresses ON leadaddresses.leadId = leads.id
	                LEFT JOIN leadstatuses ON leadstatuses.id = leads.leadStatusId
					WHERE leads.createdBy IN  (', _userIds,') AND leads.leadStatusId = 1 AND leads.isDelete = 0 LIMIT ',_fetchRecords,' OFFSET ',_startIndex);
	
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getLoanStatus`()
BEGIN
	SELECT * FROM loanstatuses ORDER BY displayOrder;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getOrders`(IN _startIndex INT,IN _fetchRecords INT,IN _userId INT,IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200),IN _statusId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE filterQuery TEXT DEFAULT "";
	SET @StartIndexQuery = "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @filterQuery = "";
     IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(orders.createdDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(orders.createdDate) <= '",_toDate,"'");
	END IF;
    IF _statusId > 0 THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND orders.orderStatusId = ",_statusId);
	END IF;
	SET @SqlQueryCount = '';
    SET @SqlQueryCount = CONCAT_WS('',"SELECT COUNT(orders.id) as totalCount FROM orders 
	LEFT JOIN orderaddresses ON orderaddresses.orderId = orders.id
    LEFT JOIN orderstatuses ON orderstatuses.id = orders.orderStatusId
    LEFT JOIN products ON orders.productId = products.id
    WHERE orders.userId = ",_userId,@filterQuery);
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @SqlQuery = '';
    SET @SqlQuery = CONCAT_WS('',"SELECT orders.*,orderaddresses.id as orderAddressId,orderaddresses.addressTypeId,orderaddresses.label,orderaddresses.addressLine1,orderaddresses.addressLine2,orderaddresses.pincode,orderaddresses.cityId,orderaddresses.city,orderaddresses.district,orderaddresses.state,orderstatuses.status as orderStatus,products.name as productName,products.imageUrl,products.coin 
    FROM orders 
    LEFT JOIN orderaddresses ON orderaddresses.orderId = orders.id
    LEFT JOIN orderstatuses ON orderstatuses.id = orders.orderStatusId
    LEFT JOIN products ON orders.productId = products.id WHERE orders.userId = ",_userId,@filterQuery," ORDER BY orders.transactionDate DESC",@startIndexQuery);
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `GetOtherLoansByuserId`(IN _userId INT,IN _serviceTypeId INT,IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	SELECT customerotherloans.*, employmenttypes.name as employementtypename FROM customerotherloans INNER JOIN employmenttypes ON employmenttypes.id = customerotherloans.employmentTypeId WHERE customerotherloans.userId =  _userId AND customerotherloans.serviceTypeId = _serviceTypeId LIMIT _fetchRecord OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getParnerCommission`(IN _partnerIds TEXT, IN _startIndex INT, IN _fetchRecords INT,IN _loanTypeId INT,IN _fromDate VARCHAR(100),IN _toDate VARCHAR(100))
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE totalCommissionQuery TEXT DEFAULT '';
	SET @filterQuery = '';
    IF _loanTypeId > 0 THEN
		SET @filterQuery = CONCAT_WS(''," AND customerloans.serviceId = ",_loanTypeId);
	END IF;
	IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(partnercommissionhistory.createdDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(partnercommissionhistory.createdDate) <= '",_toDate,"'");
	END IF;
	SET @totalCommissionQuery = '';
    SET @totalCommissionQuery = CONCAT_WS(''," SELECT SUM(partnercommissionhistory.commission)as totalcommission FROM partnercommissionhistory INNER JOIN partners ON partnercommissionhistory.partnerId = partners.id
    LEFT JOIN customerloandetail ON partnercommissionhistory.loanDetailId = customerloandetail.id
    LEFT JOIN customerloans ON customerloandetail.customerLoanId = customerloans.id
    LEFT JOIN customers ON customerloans.customerId = customers.Id
    LEFT JOIN services ON customerloans.serviceId = services.id
    LEFt JOIN partnerinvoice ON partnerinvoice.partnercommissionhistoryId = partnercommissionhistory.id WHERE partnercommissionhistory.partnerId IN(",_partnerIds,") AND partnercommissionhistory.type = 'IN' AND partnercommissionhistory.isReleased = true ",@filterQuery);
    PREPARE totalCommissionStmt FROM @totalCommissionQuery;
    EXECUTE totalCommissionStmt;
    DEALLOCATE PREPARE totalCommissionStmt;
   
    SET @sqlQuery = CONCAT_WS('', "SELECT partnercommissionhistory.*,partnerinvoice.url,partnerinvoice.invoiceNumber, partners.fullName as partnerName, customers.fullName as customerName, customerloans.createdDate as applydate, services.name as loanType,customerloandetail.amountDisbursed,banks.name as bankName
    FROM partnercommissionhistory
    INNER JOIN partners ON partnercommissionhistory.partnerId = partners.id
    LEFT JOIN customerloandetail ON partnercommissionhistory.loanDetailId = customerloandetail.id
    LEFT JOIN customerloans ON customerloandetail.customerLoanId = customerloans.id
    LEFT JOIN customers ON customerloans.customerId = customers.Id
    LEFT JOIN services ON customerloans.serviceId = services.id
    LEFt JOIN partnerinvoice ON partnerinvoice.partnercommissionhistoryId = partnercommissionhistory.id
     LEFT JOIN banks ON customerloandetail.bankId = banks.id
    WHERE partnercommissionhistory.partnerId IN (",_partnerIds,") AND partnercommissionhistory.type = 'IN' AND partnercommissionhistory.isReleased = true ",@filterQuery);
    IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @sqlQuery = CONCAT_WS('', @sqlQuery, " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;  
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getPartnerCustomers`(IN _partnerId INT, IN _startIndex INt, IN _fetchRecords INT)
BEGIN
	SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
	, customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
    FROM users 
    INNER JOIN userroles ON userroles.userId = users.id 
    INNER JOIN customers ON customers.userId = users.id 
    LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
    WHERE customeraddresses.addressTypeId = 1 AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)
    AND customers.id IN(select customerId from partnercustomers WHERE partnerId = _partnerId) 
    LIMIT _fetchRecords OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getPartnerLoanListByStatusId`(IN _partnerId INT, IN _statusId INT, IN _startIndex INT, IN _fetchRecords INT, IN _serviceIds TEXT
, IN _fromDate VARCHAR(200), IN _toDate VARCHAR(200))
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
	DECLARE filterQuery TEXT DEFAULT '';
	SET @filterQuery = "";
	SET @sqlQuery = CONCAT_WS('', "SELECT customerloans.*,customers.fullName, customers.userId, services.name as serviceName,customerloans.loanTransactionDate as applyDate, loanstatuses.status FROM customerloans
	inner JOIN services ON services.Id = customerloans.serviceId
    LEFT JOIN loanstatuses on loanstatuses.id = customerloans.statusId
    inner join customers  on customers.id = customerloans.customerId
    WHERE customerloans.statusId =", _statusId ,"  AND customerloans.id IN (select customerLoanId from partnerscustomerloans where partnerId = ",_partnerId,")");
    
    IF (_serviceIds != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND services.id IN(",_serviceIds,")");
    END IF;
    IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(customerloans.createdDate) <= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(customerloans.createdDate) >= '",_toDate,"'");
	END IF;
    
    SET @sqlQuery = CONCAT_WS('',@sqlQuery,@filterQuery," ORDER BY customerloans.id DESC LIMIT ",_fetchRecords," OFFSET ", _startIndex);
    
    PREPARE stmt FROM @sqlQuery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getProduct`(IN _startIndex INT,IN _fetchRecords INT,IN _searchString VARCHAR(200),IN _minCoin INT,IN _maxCoin INT)
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    DECLARE sqlQueryCount TEXT DEFAULT '';
    DECLARE StartIndexQuery TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    SET @startIndexQuery = '';
    /*IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;*/
    
    SET @filterQuery = '';
	IF _searchString != '' THEN
		SET @filterQuery =CONCAT_WS('',@filterQuery," AND (products.name LIKE '%",_searchString,"%')" );
    END IF;
    IF (_minCoin > 0) THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND coin <=",_minCoin);
	END IF;
    IF (_maxCoin > 0 ) THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND coin >=",_maxCoin);
	END IF;
    SET @sqlQueryCount = '';
    SET @sqlQueryCount = CONCAT_WS(''," SELECT COUNT(id) as totalCount FROM products WHERE isDelete = 0 AND isActive = 1",@filterQuery);
    PREPARE countStmt FROM @sqlQueryCount;
	EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @sqlQuery = '';
    SET @sqlQuery = CONCAT_WS(''," SELECT * FROM products WHERE isDelete = 0 AND isActive = 1",@filterQuery," ORDER BY id DESC",@startIndexQuery);
    PREPARE stmt FROM @sqlQuery;
	EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getRewardCoin`(IN _rewardTypeId INT, IN _minLoanFile INT, IN _maxLoanFile INT)
BEGIN
	SET @getQuery = "";
	SET @getQuery = CONCAT_WS(' ', " SELECT * FROM rewardcoin WHERE rewardTypeId = ",_rewardTypeId);
            
	IF _minLoanFile>0 THEN
		SET @getQuery = CONCAT_WS(' ', "AND minLoanFile >= ",_minLoanFile);
	END IF;
    IF _maxLoanFile>0 THEN
		SET @getQuery = CONCAT_WS(' ', "AND maxLoanFile >= ",_maxLoanFile);
    END IF;
     
	PREPARE stmt FROM @getQuery;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getServiceEmploymentTypes`(IN _serviceId INT)
BEGIN
	SELECT * FROM employmenttypes INNER JOIN servicesemploymenttypes ON servicesemploymenttypes.employmentTypeId = employmenttypes.id WHERE servicesemploymenttypes.serviceId = _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getUsersScratchCards`(IN _userId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    
	IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(userscratchcards.id) as totalCount FROM userscratchcards WHERE userId = ",_userId);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT * FROM userscratchcards WHERE userId = ',_userId,' ORDER BY userscratchcards.id DESC ',@StartIndexQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getuserWallet`(IN _userId INT)
BEGIN
	SELECT * FROM userwallet WHERE userId = _userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `getUserWalletHistory`(IN _userWalletId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    
	IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(userwallethistory.id) as totalCount FROM userwallethistory WHERE userWalletId = ", _userWalletId);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT userwallethistory.*,rewardtypes.name as rewardTypeName FROM userwallethistory INNER JOIN rewardtypes on rewardtypes.id = userwallethistory.rewardType WHERE userWalletId = ', _userWalletId,' ORDER BY userwallethistory.id DESC ',@StartIndexQuery);
   
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
	SELECT * FROM userwallethistory WHERE userWalletId = _userWalletId ORDER BY id DESC;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `InsertCustomerOtherLoanDetail`(IN _userId INT, IN _serviceId INT, IN _serviceTypeId INT, IN _fullName TEXT,IN _birthdate DATETIME, IN _panCardNo VARCHAR(20),IN _aadhaarCardNo VARCHAR(20), IN _ContactNo VARCHAR(15),  IN _email VARCHAR(256), IN _employmentTypeId INT, IN _monthlyIncome decimal(15,2), IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _city VARCHAR(200), IN _distict VARCHAR(200)
, IN _state VARCHAR(200) )
BEGIN
		INSERT INTO customerotherloans(userId, serviceId, serviceTypeId, fullName, birthdate, panCardNo, aadhaarCardNo, contactNo, email, employmentTypeId, monthlyincome, label, addressline1, addressline2, pincode, cityId, city, distict, state,  createdBy, modifiedBy) 
		VALUES(_userId, _serviceId, _serviceTypeId, _fullName, _birthdate, _panCardNo, _aadhaarCardNo, _ContactNo, _email, _employmentTypeId,  _monthlyIncome, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _distict, _state , _userId, _userId );
		SET @insertId = LAST_INSERT_ID();    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertOrder`(IN _orderId INT,IN _userId INT,IN _productId INT,IN _quantity DECIMAL(15,3),IN _unitCoin DECIMAL(15,3),IN _addressTypeId INT,IN _label TEXT,IN _addressLine1 TEXT,IN _addressLine2 TEXT,IN _pincode VARCHAR(10),IN _cityId INT,IN _city VARCHAR(100),IN _district VARCHAR(100),IN _state VARCHAR(100))
BEGIN
	IF _orderId > 0 THEN
		UPDATE orders SET userId = _userId,productId = _productId,quantity = _quantity,unitCoin = _unitCoin,totalCoin = _quantity * _unitCoin,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _orderId;
		UPDATE orderaddresses SET addressTypeId = _addressTypeId,label = _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,pincode = _pincode,cityId = _cityId,city = _city,district = _district,state = _state,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE orderId = _orderId;
    ELSE 
		INSERT INTO orders (userId,productId,quantity,unitCoin,totalCoin,transactionDate,orderStatusId,createdBy,modifiedBy) VALUES (_userId,_productId,_quantity,_unitCoin,(_quantity * _unitCoin),CURRENT_TIMESTAMP(),1,_userId,_userId);
		SET _orderId = LAST_INSERT_ID();
        INSERT INTO orderstatushistory (orderId,orderStatusId,transactionDate,createdBy,modifiedBy) VALUES (_orderId,1,CURRENT_TIMESTAMP(),_userId,_userId);
        INSERT INTO orderaddresses (orderId,addressTypeId,label,addressLine1,addressLine2,pincode,cityId,city,district,state,createdBy,modifiedBy) VALUES (_orderId,_addressTypeId,_label,_addressLine1,_addressLine2,_pincode,_cityId,_city,_district,_state,_userId,_userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `InsertUpdateBusinessLoanBasicDetail`(IN _customerId INT, IN _userId INT, IN _customerLoanId INT, IN _customerLoanBusinessDetailId INT, IN _customerAddressId INT
, IN _customerLoanCurrentResidentTypeId INT, IN _fullName VARCHAR(200),IN _birthdate DATETIME,IN _gender VARCHAR(15), IN _panCardNo VARCHAR(20), IN _maritalStatusId INT, IN _cityId INT, IN _pincode VARCHAR(10), IN _loanAmount DECIMAL(15,2)
, IN _employmentTypeId INT, IN _loanAgainstCollateralId INT, IN _serviceId INT, IN _businessAnnualSale INT, IN _businessExperienceId INT, IN _email VARCHAR(256), IN _residentTypeId INT, IN _partnerId INT,IN _currentUserId INT,IN _loanAmountTakenExisting DECIMAL(15,2),IN  _approxDate VARCHAR(100),IN _topupAmount DECIMAL(15,2),IN _approxCurrentEMI DECIMAL(15,2),IN _bankId INT,IN _loanType VARCHAR(40))
BEGIN    
	DECLARE finished INT DEFAULT 0;
    DECLARE _existId INT DEFAULT 0;
	UPDATE customers SET gender=_gender, fullName=_fullName, birthdate = _birthdate ,panCardNo = _panCardNo, maritalStatusId = _maritalStatusId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerId;
    
    IF _customerAddressId>0 THEN
		UPDATE customeraddresses SET customerId = _customerId, cityId = _cityId, pincode = _pincode, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerAddressId;
    ELSE
		INSERT INTO customeraddresses(customerId,cityId,pincode, createdBy, modifiedBy) VALUES(_customerId,_cityId,_pincode, _userId, _userId);
        SET _customerAddressId = LAST_INSERT_ID();
    END IF;
    
    IF _customerLoanId>0 THEN
		UPDATE customerloans SET serviceId = _serviceId, loanAmount = _loanAmount, customerId = _customerId, employmentTypeId = _employmentTypeId, loanAgainstCollateralId = _loanAgainstCollateralId
        , modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId,loanType = _loanType WHERE id = _customerLoanId;
        
        
    ELSE
		INSERT INTO customerloans(serviceId, loanAmount, customerId, employmentTypeId, loanAgainstCollateralId, createdBy, modifiedBy,loanType) VALUES(_serviceId, _loanAmount, _customerId, _employmentTypeId, _loanAgainstCollateralId, _userId, _userId,_loanType);
        SET _customerLoanId = LAST_INSERT_ID();
		INSERT INTO loancompletescreenhistory(customerLoanId,isCompleted,completeScreen) VALUES(_customerLoanId, false, 1);
           IF _loanType != 'New' THEN
           INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdby,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
           END IF;
	END IF;
    
      IF _loanType != 'New' THEN
			IF 	EXISTS(SELECT 1 FROM customerloantransferpropertydetails) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select customerLoanId FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				gettransfercustomerloan: LOOP
					FETCH cur_checkexist INTO _existId;
					IF finished = 1 THEN 
						LEAVE gettransfercustomerloan;
					END IF;
					IF _existId THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting,approxDate = _approxDate,topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI,bankId = _bankId,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE customerLoanId  = _customerLoanId;	
		ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
        ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdby,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		END IF;
        END IF;
    
     IF _partnerId>0 THEN
			INSERT INTO partnerscustomerloans(customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(_customerLoanId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
    
    IF _currentUserId>0 THEN
		UPDATE users SET email = _email, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_currentUserId WHERE id = _currentUserId;
    END IF;
    
    IF _customerLoanBusinessDetailId>0 THEN
		UPDATE customerloanbusinessdetails SET customerLoanId = _customerLoanId, businessAnnualSale = _businessAnnualSale, businessExperienceId = _businessExperienceId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerLoanBusinessDetailId;
    ELSE
		INSERT INTO customerloanbusinessdetails(customerLoanId,businessAnnualSale,businessExperienceId, createdBy, modifiedBy) VALUES(_customerLoanId, _businessAnnualSale, _businessExperienceId, _userId, _userId);
        SET _customerLoanBusinessDetailId = LAST_INSERT_ID();
    END IF;
    
    IF _customerLoanCurrentResidentTypeId>0 THEN
		UPDATE customerloancurrentresidentdetails SET residentTypeId = _residentTypeId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerLoanCurrentResidentTypeId;
    ELSE
		INSERT INTO customerloancurrentresidentdetails(customerLoanId, residentTypeId, createdBy, modifiedBy) VALUES(_customerLoanId, _residentTypeId, _userId, _userId);
        SET _customerLoanCurrentResidentTypeId = LAST_INSERT_ID();
    END IF;
    
    SELECT _customerId, _customerAddressId, _customerLoanId, _customerLoanBusinessDetailId, _customerLoanCurrentResidentTypeId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateBusinessLoanBusinessDetail`(IN _customerLoanBusinessDetailId INT, IN _customerLoanId INT, IN _companyTypeId INT, IN _industryTypeId INT, IN _businessNatureId INT
, IN _businessAnnualProfitId INT, IN _primaryBankId INT, IN _currentlyPayEmi DECIMAL(15,3), IN _userId INT)
BEGIN
	UPDATE customerloanbusinessdetails SET companyTypeId = _companyTypeId, industryTypeId = _industryTypeId, businessNatureId = _businessNatureId, businessAnnualProfitId = _businessAnnualProfitId, currentlyPayEmi = _currentlyPayEmi
    , primaryBankId = _primaryBankId ,modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerLoanBusinessDetailId;
    
    UPDATE loancompletescreenhistory SET completeScreen = 2 WHERE customerLoanId=_customerLoanId AND completeScreen < 2;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `InsertUpdateBusinessLoanMoreBasicDetail`(IN _customerAddressId INT, IN _customerLoanBusinessDetailId INT, IN _addressTypeId INT, IN _label TEXT
, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _businessName VARCHAR(100), IN _businessGstNo VARCHAR(100), IN _userId INT,IN _customerLoanId INT)
BEGIN
	UPDATE customerloanbusinessdetails SET businessGstNo = _businessGstNo, businessName = _businessName, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId 
    WHERE id = _customerLoanBusinessDetailId;
    UPDATE customeraddresses SET addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2, modifiedDate=CURRENT_TIMESTAMP()
    , modifiedBy=_userId WHERE id = _customerAddressId;
    
    UPDATE loancompletescreenhistory SET completeScreen = 3 WHERE customerLoanId=_customerLoanId AND completeScreen < 3;
    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCoApplicantEmploymentDetail`(IN _customerloancoapplicantemploymentdetailId INT, IN _customerLoanCoApplicantId INT, IN _customerLoanId INT
, IN _monthlyIncome DECIMAL(15,2), IN _otherIncome DECIMAL(15,2), IN _companyTypeId INT, IN _companyName VARCHAR(100), IN _companyAddressId INT, IN _addressTypeId INT, IN _label TEXT
, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _officePincode VARCHAR(8), IN _designationId INT, IN _designation VARCHAR(100)
, IN _employmentNatureId INT, IN _employmentServiceTypeId INT, IN _currentCompanyExperience DECIMAL(5,2), IN _experienceInProfession DECIMAL(5,2), IN _employmentTypeId INT,IN _industryTypeId INT, IN _userId INT )
BEGIN

	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
	
    IF _customerloancoapplicantemploymentdetailId>0 THEN
		IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId, modifiedDate=CURRENT_TIMESTAMP()
            , modifiedBy=_userId WHERE id = _companyAddressId;
		ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
			SET _companyAddressId = LAST_INSERT_ID();
        END IF;
        IF _companyAddressId>0 THEN
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloancoapplicantemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _customerLoanCoApplicantId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerLoanCoApplicantId = ",_customerLoanCoApplicantId);
			END IF;
            IF _customerloanId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerloanId = ",_customerloanId);
			END IF;                
			IF _monthlyIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
			END IF;                
			IF _otherIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", otherIncome = ",_otherIncome);
			END IF;
            IF _employmentTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentTypeId = ",_employmentTypeId);
			END IF;
			IF _companyName!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
			END IF;
			IF _companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",_companyAddressId);
			END IF;
			IF _officePincode!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", officePincode = '",_officePincode,"'");
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designationId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
			END IF;
			IF _employmentNatureId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentNatureId = ",_employmentNatureId);
			END IF;
			IF _employmentServiceTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentServiceTypeId = ",_employmentServiceTypeId);
			END IF;
            IF _industryTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", industryTypeId = ",_industryTypeId);
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			IF _experienceInProfession >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", experienceInProfession = ",_experienceInProfession);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerloancoapplicantemploymentdetailId);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		END IF;
    ELSE
    INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
    VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
    SET _companyAddressId = LAST_INSERT_ID();
    
    INSERT customerloancoapplicantemploymentdetails(customerLoanCoApplicantId, customerLoanId, monthlyIncome, otherIncome, employmentTypeId, companyName, companyAddressId, officePincode
    , cityId, designationId, employmentNatureId, employmentServiceTypeId, industryTypeId,currentCompanyExperience, experienceInProfession, createdBy, modifiedBy) VALUES(_customerLoanCoApplicantId
    , _customerLoanId, _monthlyIncome, _otherIncome, _employmentTypeId, _companyName, _companyAddressId, _officePincode, _cityId, _designationId, _employmentNatureId
    , _employmentServiceTypeId,_industryTypeId, _currentCompanyExperience, _experienceInProfession, _userId, _userId);
	SET _customerloancoapplicantemploymentdetailId = LAST_INSERT_ID();

    END IF;
    
    UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId=_customerLoanId AND completeScreen < 5;
    
    SELECT _customerloancoapplicantemploymentdetailId as customerloancoapplicantemploymentdetailId, _companyAddressId as companyAddressId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCreditCardProfileDetail`(IN _customerId INT, IN _userId INT, IN _creditCardId INT, IN _fullName VARCHAR(200),IN _birthdate DATETIME,IN _gender VARCHAR(15), IN _panCardNo VARCHAR(20), IN _maritalStatusId INT,IN _otherCreditCardBankId INT,IN _maxCreditLimit varchar(45),IN _availableCreditLimit varchar(45),IN _isAlreadyCreditCard tinyint,IN _email varchar(200),IN _currentUserId INT,IN _partnerId INT)
BEGIN    
	UPDATE customers SET gender=_gender, fullName=_fullName, birthdate = _birthdate ,panCardNo = _panCardNo, maritalStatusId = _maritalStatusId, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerId;   
    
    IF _creditCardId>0 THEN
        IF _isAlreadyCreditCard = TRUE THEN
		UPDATE customercreditcards SET customerId = _customerId,isAlreadyCreditCard = _isAlreadyCreditCard ,otherCreditCardBankId = _otherCreditCardBankId,maxCreditLimit = _maxCreditLimit ,availableCreditLimit = _availableCreditLimit,
        modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardId;
        ELSE 
        UPDATE customercreditcards SET customerId = _customerId,isAlreadyCreditCard = _isAlreadyCreditCard ,otherCreditCardBankId = null,maxCreditLimit = null ,availableCreditLimit = null,
        modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _creditCardId;
        END IF;
    ELSE
		INSERT INTO customercreditcards(customerId,isAlreadyCreditCard,otherCreditCardBankId, maxCreditLimit,availableCreditLimit,createdBy, modifiedBy) VALUES(_customerId,_isAlreadyCreditCard,_otherCreditCardBankId,_maxCreditLimit,_availableCreditLimit, _userId, _userId);
        SET @creditCardId = LAST_INSERT_ID();
         IF _partnerId>0 THEN
			INSERT INTO partnercustomercreditcards(customerCreditCardId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(@creditCardId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
		INSERT INTO creditcardcompletescreenhistory(customerCreditCardId,isCompleted,completeScreen) VALUES(@creditCardId, false, 1);
         SELECT _customerId as customerId, @creditCardId as creditCardId;
	END IF;
    
    IF _currentUserId>0 THEN
		UPDATE users SET email = _email,fullName=_fullName ,gender=_gender, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_currentUserId WHERE id = _currentUserId;
    END IF;
    
    IF _creditCardId >0 THEN
    SELECT _customerId as customerId , _creditCardId as creditCardId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCustomerAddress`(IN _customerAddressId INT, IN _customerId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100), IN _district VARCHAR(100), IN _state VARCHAR(50),IN _customerLoanId INT, IN _userId INT)
BEGIN
	IF _customerAddressId > 0 THEN
		UPDATE customeraddresses SET customerId = _customerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2
        , pincode = _pincode, cityId = _cityId, city = _city, district = _district, state = _state, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerAddressId;
        
        UPDATE loancompletescreenhistory SET completeScreen = 3 WHERE customerLoanId=_customerLoanId AND completeScreen < 3;
        
        SELECT _customerAddressId as customerAddressId;
    ELSE 
		INSERT INTO customeraddresses(customerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) VALUES(_customerId
        , _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
        SET _customerAddressId = LAST_INSERT_ID();
        
        UPDATE loancompletescreenhistory SET completeScreen = 3 WHERE customerLoanId=_customerLoanId AND completeScreen < 3;
        
        SELECT _customerAddressId as customerAddressId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCustomerCreditCardAddress`(IN _customerAddressId INT, IN _customerId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100), IN _district VARCHAR(100), IN _state VARCHAR(50),IN _customerCrediCardId INT, IN _userId INT)
BEGIN
	IF _customerAddressId > 0 THEN
		UPDATE customeraddresses SET customerId = _customerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2
        , pincode = _pincode, cityId = _cityId, city = _city, district = _district, state = _state, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerAddressId;
        
        UPDATE creditcardcompletescreenhistory SET completeScreen = 3 WHERE customerCreditCardId =_customerCrediCardId AND completeScreen < 3;
        
        SELECT _customerAddressId as customerAddressId;
    ELSE 
		INSERT INTO customeraddresses(customerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) VALUES(_customerId
        , _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
        SET @customerAddressId = LAST_INSERT_ID();
        
        UPDATE creditcardcompletescreenhistory SET completeScreen = 3 WHERE customerCreditCardId = _customerCrediCardId AND completeScreen < 3;
        
        SELECT @customerAddressId as customerAddressId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCustomerCreditCardWorkAddress`(IN _customerAddressId INT, IN _customerId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100), IN _district VARCHAR(100), IN _state VARCHAR(50),IN _customerCrediCardId INT, IN _userId INT)
BEGIN
	IF _customerAddressId > 0 THEN
		UPDATE customeraddresses SET customerId = _customerId, addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2
        , pincode = _pincode, cityId = _cityId, city = _city, district = _district, state = _state, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerAddressId;
        
        UPDATE creditcardcompletescreenhistory SET completeScreen = 4 WHERE customerCreditCardId =_customerCrediCardId AND completeScreen < 4;
        
        SELECT _customerAddressId as customerAddressId;
    ELSE 
		INSERT INTO customeraddresses(customerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) VALUES(_customerId
        , _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, _userId, _userId);
        SET @customerAddressId = LAST_INSERT_ID();
        
        UPDATE creditcardcompletescreenhistory SET completeScreen = 4 WHERE customerCreditCardId = _customerCrediCardId AND completeScreen < 4;
        
        SELECT @customerAddressId as customerAddressId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateCustomerLoanPropertyDetail`(IN _customerLoanId INT, IN _serviceId INT, IN _loanAmount DECIMAL(15,2), IN _customerId INT, IN _customerLoanPropertyDetailId INT
, IN _propertyTypeId INT, IN _propertyPurchaseValue DECIMAL(15,2), IN _propertyCityId INT, IN _propertyCity VARCHAR(100), IN _propertyDistrict VARCHAR(100), IN _propertyState VARCHAR(100),IN _pincode VARCHAR(10),IN _addressLine1 TEXT, IN _addressLine2 TEXT
, IN _userId INT,IN _partnerId INT,IN _loanType varchar(45))
BEGIN
	IF _customerLoanId > 0 THEN
		UPDATE customerloans SET loanAmount = _loanAmount, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(),loanType = _loanType WHERE id = _customerLoanId;
        
        UPDATE customerloanpropertydetails SET propertyTypeId = _propertyTypeId, propertyPurchaseValue = _propertyPurchaseValue, loanType = _loanType ,propertyCityId = _propertyCityId, propertyCity = _propertyCity, pincode = _pincode, addressLine1 =_addressLine1,addressLine2 =_addressLine2
        , propertyDistrict = _propertyDistrict, propertyState = _propertyState, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerLoanPropertyDetailId;
        
        UPDATE loancompletescreenhistory SET completeScreen = 1 WHERE customerLoanId=_customerLoanId AND completeScreen < 1;
        
        SELECT _customerLoanId as customerLoanId, _customerLoanPropertyDetailId as customerLoanPropertyDetailId;
    ELSE
		INSERT INTO customerloans(serviceId, loanAmount, customerId, createdBy, modifiedBy.loanType) VALUES(_serviceId, _loanAmount, _customerId, _userId, _userId,_loanType);
        SET _customerLoanId = LAST_INSERT_ID();
        
        INSERT INTO customerloanpropertydetails(customerLoanId, propertyTypeId, propertyPurchaseValue, propertyCityId, propertyCity, propertyDistrict, propertyState, pincode,addressLine1,addressLine2,loanType,createdBy, modifiedBy) 
        VALUES(_customerLoanId, _propertyTypeId, _propertyPurchaseValue, _propertyCityId, _propertyCity, _propertyDistrict, _propertyState,_pincode,_addressLine1,_addressLine2,_loanType ,_userId, _userId);
        SET _customerLoanPropertyDetailId = LAST_INSERT_ID();
        
        IF _partnerId>0 THEN
			INSERT INTO partnerscustomerloans(customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(_customerLoanId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
        
        -- UPDATE loancompletescreenhistory SET completeScreen = 1 WHERE customerLoanId=_customerLoanId AND completeScreen < 1;
        INSERT INTO loancompletescreenhistory(customerLoanId,isCompleted,completeScreen) VALUES(_customerLoanId, false, 1);
        
        SELECT _customerLoanId as customerLoanId, _customerLoanPropertyDetailId as customerLoanPropertyDetailId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateHomeLoanCoApplicant`(IN _customerLoanCoApplicantId INT, IN _customerLoanId INT, IN _fullName VARCHAR(200), IN _birthdate DATETIME, IN _maritalStatusId INT
, IN _coApplicantRelationID INT, IN _userId INT)
BEGIN
	IF _customerLoanCoApplicantId > 0 THEN
		UPDATE customerloancoapplicants SET customerLoanId = _customerLoanId, fullName = _fullName, birthdate = _birthdate, maritalStatusId = _maritalStatusId, coApplicantRelationId = _coApplicantRelationId
        , modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _customerLoanCoApplicantId;
        
        SELECT _customerLoanCoApplicantId as customerLoanCoApplicantId;
    ELSE 
		INSERT INTO customerloancoapplicants(customerLoanId,fullName,birthdate,maritalStatusId,coApplicantRelationId,createdBy,modifiedBy) VALUES(_customerLoanId,_fullName,_birthdate,_maritalStatusId,_coApplicantRelationId,_userId,_userId);
        SET _customerLoanCoApplicantId = LAST_INSERT_ID();
        
        SELECT _customerLoanCoApplicantId as customerLoanCoApplicantId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateHomeLoanCurrentResidentDetail`(IN _customerloancurrentresidentdetailId INT, IN _customerLoanId INT, IN _residentTypeId INT, IN _rentAmount DECIMAL(10,3)
, IN _valueOfProperty DECIMAL(15,2), IN _monthlyHouseHold DECIMAL(15,3), IN _userId INT)
BEGIN
	IF _customerloancurrentresidentdetailId >0 THEN
		UPDATE customerloancurrentresidentdetails SET customerLoanId = _customerLoanId, residentTypeId = _residentTypeId, rentAmount = _rentAmount, valueOfProperty = _valueOfProperty
        , monthlyHouseHold = _monthlyHouseHold, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _customerloancurrentresidentdetailId;
    ELSE
		INSERT INTO customerloancurrentresidentdetails(customerLoanId, residentTypeId, rentAmount, valueOfProperty, monthlyHouseHold, createdBy, modifiedBy) 
        VALUES(_customerLoanId, _residentTypeId, _rentAmount, _valueOfProperty, _monthlyHouseHold, _userId, _userId);
        
        SET _customerloancurrentresidentdetailId = LAST_INSERT_ID();
    END IF;
    UPDATE loancompletescreenhistory SET completeScreen = 5 WHERE customerLoanId=_customerLoanId AND completeScreen < 5;
    
    SELECT _customerloancurrentresidentdetailId as customerloancurrentresidentdetailId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateHomeLoanCustomerDetail`(IN _customerLoanId INT,IN _motherName VARCHAR(200),IN _fatherContactNo VARCHAR(200) ,IN _userId INt, IN _customerId INT, IN _fullName VARCHAR(200), IN _birthdate DATETIME
, IN  _maritalStatusId INT, IN _panCardNo VARCHAR(20))
BEGIN
	IF _customerId>0 THEN
		SET @UpdateQuery = "";
        SET @SetStatement = "";
        
        SET @UserUpdateQuery = "";
        SET @UserSetStatement = "";
        
        SET @UpdateQuery =  "UPDATE customers SET modifiedDate = '";
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
        
        SET @UserUpdateQuery =  "UPDATE users SET modifiedDate = '";
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, CURRENT_TIMESTAMP(),"'");
		
        IF _fullName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", fullName = '",_fullName,"'");
            SET @UserSetStatement = CONCAT_WS('', @UserSetStatement, ", fullName = '",_fullName,"'");
        END IF;
        
        IF _birthdate IS NOT NULL THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", birthdate = '",_birthdate,"'");
        END IF;
        
        IF _panCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", panCardNo = '",_panCardNo,"'");
        END IF;
        
        IF _maritalStatusId != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", maritalStatusId = ",_maritalStatusId);
        END IF;
        
        SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerId);
        PREPARE stmt FROM @UpdateQuery;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
    
        SET @UserUpdateQuery = CONCAT_WS('', @UserUpdateQuery, @UserSetStatement," WHERE id = ",_userId);
        
        PREPARE stmt_user FROM @UserUpdateQuery;
		EXECUTE stmt_user;
		DEALLOCATE PREPARE stmt_user;
        
        UPDATE customerloans SET motherName = _motherName, fatherContactNo = _fatherContactNo, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerLoanId;
        
        UPDATE loancompletescreenhistory SET completeScreen = 2 WHERE customerLoanId=_customerLoanId AND completeScreen < 2;
        
        
        
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateHomeLoanCustomerEmploymentDetail`(IN _customerloanemploymentdetailId INT, IN _customerLoanId INT, IN _monthlyIncome DECIMAL(15,2)
, IN _otherIncome DECIMAL(15,2), IN _companyTypeId INT, IN _companyName VARCHAR(100), IN _companyAddressId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(20), IN _cityId INT, IN _officePincode VARCHAR(8), IN _designationId INT, IN _designation VARCHAR(100), IN _employmentNatureId INT
, IN _employmentServiceTypeId INT, IN _currentCompanyExperience DECIMAL(5,2), IN _experienceInProfession DECIMAL(5,2), IN _employmentTypeId INT, IN _industryTypeId INT, IN _userId INT)
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    
    UPDATE customerloans SET employmentTypeId = _employmentTypeId WHERE id = _customerLoanId;
    
	IF _customerloanemploymentdetailId>0 THEN
    -- Update
		IF _companyAddressId>0 THEN
			UPDATE companyaddresses SET addressTypeId=_addressTypeId, label=_label, addressLine1=_addressLine1, addressLine2=_addressLine2, pincode=_pincode, cityId=_cityId, modifiedDate=CURRENT_TIMESTAMP()
            , modifiedBy=_userId WHERE id = _companyAddressId;
		ELSE
			INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
			VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
			SET _companyAddressId = LAST_INSERT_ID();
        END IF;
		IF _companyAddressId>0 THEN
			SET @UpdateQuery = "";
			SET @SetStatement = "";
			
			SET @UpdateQuery =  "UPDATE customerloanemploymentdetails SET modifiedDate = '";
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, CURRENT_TIMESTAMP(),"'");
			
			IF _customerloanId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerloanId = ",_customerloanId);
			END IF;                
			IF _monthlyIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
			END IF;                
			IF _otherIncome >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", otherIncome = ",_otherIncome);
			END IF;
			IF _companyTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyTypeId = ",_companyTypeId);
			END IF;
			IF _companyName!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyName = '",_companyName,"'");
			END IF;
			IF _companyAddressId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", companyAddressId = ",_companyAddressId);
			END IF;
			IF _officePincode!='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", officePincode = '",_officePincode,"'");
			END IF;
			IF _cityId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
			END IF;
			IF _designationId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designationId = ",_designationId);
			END IF;
			IF _designation !='' THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", designation = ",_designation);
			END IF;
			IF _employmentNatureId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentNatureId = ",_employmentNatureId);
			END IF;
            IF _industryTypeId  >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", industryTypeId = ",_industryTypeId );
			END IF;
			IF _employmentServiceTypeId >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentServiceTypeId = ",_employmentServiceTypeId);
			END IF;
			IF _currentCompanyExperience >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", currentCompanyExperience = ",_currentCompanyExperience);
			END IF;
			IF _experienceInProfession >0 THEN
				SET @SetStatement = CONCAT_WS('', @SetStatement, ", experienceInProfession = ",_experienceInProfession);
			END IF;
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", modifiedBy = ",_userId);
			
			SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_customerloanemploymentdetailId);
			PREPARE stmt FROM @UpdateQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		END IF; 
    ELSE
    -- Insert
    INSERT INTO companyaddresses(addressTypeId, label, addressLine1, addressLine2, pincode, cityId, createdBy, modifiedBy) 
    VALUES(_addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _userId, _userId);
    SET _companyAddressId = LAST_INSERT_ID();
    
    INSERT customerloanemploymentdetails(customerLoanId, monthlyIncome, otherIncome, companyTypeId, companyName, companyAddressId, officePincode, cityId, designationId, designation
    , employmentNatureId,industryTypeId , employmentServiceTypeId, currentCompanyExperience, experienceInProfession, createdBy, modifiedBy) VALUES(_customerLoanId, _monthlyIncome, _otherIncome, _companyTypeId
    , _companyName, _companyAddressId, _pincode, _cityId, _designationId, _designation, _employmentNatureId,_industryTypeId ,_employmentServiceTypeId, _currentCompanyExperience, _experienceInProfession, _userId, _userId);
	SET _customerloanemploymentdetailId = LAST_INSERT_ID();

    END IF;
    
    UPDATE loancompletescreenhistory SET completeScreen = 4 WHERE customerLoanId=_customerLoanId AND completeScreen < 4;
    
    SELECT _customerloanemploymentdetailId as customerloanemploymentdetailId, _companyAddressId as companyAddressId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateLead`(IN _leadId INT, IN _customerUserId INT, IN _customerId INT, IN _countryCode varchar(6), IN _contactNo varchar(20), IN _customerFullName varchar(200)
, IN _temporaryCode VARCHAR(45), IN _serviceId INT, IN _loanAmount decimal(15,3), IN _customerAddressId INT, IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT
, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100), IN _district VARCHAR(100), IN _state VARCHAR(50), IN _email VARCHAR(256)
, IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20), IN _employmentTypeId INT, IN _userId INT, IN _leadStatusId INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
	DECLARE cRoleId INT DEFAULT 0;
    
   
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_user CURSOR FOR SELECT users.id as userId, userroles.roleId as roleId FROM users LEFT JOIN userroles ON userroles.userId = users.id WHERE users.contactNo = _contactNo;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
            OPEN  cur_user;
				cur_user_loop: LOOP
					FETCH cur_user INTO cUserId, cRoleId;
                   
                    IF finished = 1 THEN
						LEAVE cur_user_loop;
					END IF;
                    
                END LOOP cur_user_loop;
			CLOSE cur_user;
            SET @leadId = 0;
            IF cUserId = 0 THEN
				/*INSERT INTO users(fullName, countryCode, contactNo, isDisabled, createdBy, modifiedBy) VALUES(_customerFullName, _countryCode, _contactNo, 0, _userId, _userId);
                 SET @userId = LAST_INSERT_ID();
                INSERT INTO customers(userId, temporaryCode, fullName, contactNo, createdBy, modifiedBy) VALUES(@userId, _temporaryCode, _customerFullName, _contactNo, _userId, _userId);
                SET @customerId = LAST_INSERT_ID();
                INSERT INTO customeraddresses(customerId,addressTypeId,label,addressLine1,addressLine2,pincode,cityId,city,district,state,createdBy,modifiedBy) VALUES(@customerId,_addressTypeId,_label,_addressLine1,_addressLine2 ,_pincode,_cityId,
                _city, _district, _state,_userId,_userId); SET @customerAddressId = LAST_INSERT_ID();*/
				IF _leadId > 0 THEN
					SET @leadId = _leadId;
					UPDATE leads SET customerFullName = _customerFullName, contactNo = _contactNo, email = _email, serviceId = _serviceId, loanAmount = _loanAmount, pincode = _pincode
                        , cityId = _cityId, employmentTypeId = _employmentTypeId, panCardNo = _panCardNo, aadhaarCardNo = _aadhaarCardNo, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(), leadStatusId = _leadStatusId
                        WHERE id = _leadId;
                         UPDATE leadaddresses SET label =  _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,pincode = _pincode,cityId=_cityId,district = _district,state= _state,modifiedBy = _userId WHERE leadId = _leadId;
				ELSE
				INSERT INTO leads(customerFullName, contactNo, email, serviceId, loanAmount, pincode, cityId, employmentTypeId, panCardNo, aadhaarCardNo, createdBy, modifiedBy, leadStatusId) 
                VALUE(_customerFullName, _contactNo, _email, _serviceId, _loanAmount, _pincode, _cityId, _employmentTypeId, _panCardNo, _aadhaarCardNo, _userId, _userId,1);
                SET @leadId = LAST_INSERT_ID();
                   INSERT INTO leadaddresses (leadId,addressTypeId,label,addressLine1,addressLine2,pincode,cityId,district,state,createdBy,modifiedBy) VALUES (@leadId,1,_label,_addressLine1,_addressLine2,_pincode,_cityId,_district,_state,_userId,_userId);
                INSERT INTO leadstatushistory(leadId, leadStatusId, transactionDate) VALUES(@leadId, 1, CURRENT_TIMESTAMP());
                END IF;
                SELECT @leadId as leadId;
            ELSE
				IF cRoleId != 2 THEN
					SELECT "Contact No Already Used in DsaBazar App" as message;
				ELSE
                   
					IF (_leadId = 0 OR _leadId IS NULL)  THEN
						INSERT INTO leads(customerFullName, contactNo, email, serviceId, loanAmount, pincode, cityId, employmentTypeId, panCardNo, aadhaarCardNo, createdBy, modifiedBy , leadStatusId) 
						VALUE(_customerFullName, _contactNo, _email, _serviceId, _loanAmount, _pincode, _cityId, _employmentTypeId, _panCardNo, _aadhaarCardNo, _userId, _userId, 1);
						SET @leadId = LAST_INSERT_ID();
                        INSERT INTO leadaddresses (leadId,addressTypeId,label,addressLine1,addressLine2,pincode,cityId,district,state,createdBy,modifiedBy) VALUES (@leadId,1,_label,_addressLine1,_addressLine2,_pincode,_cityId,_district,_state,_userId,_userId);
						-- SELECT @leadId as insertId;
						INSERT INTO leadstatushistory(leadId, leadStatusId, transactionDate) VALUES(@leadId, 1, CURRENT_TIMESTAMP());
						SELECT @leadId as leadId;
                    ELSE
						
                        UPDATE leads SET customerFullName = _customerFullName, contactNo = _contactNo, email = _email, serviceId = _serviceId, loanAmount = _loanAmount, pincode = _pincode
                        , cityId = _cityId, employmentTypeId = _employmentTypeId, panCardNo = _panCardNo, aadhaarCardNo = _aadhaarCardNo, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(), leadStatusId = _leadStatusId
                        WHERE id = _leadId;
                        UPDATE leadaddresses SET label =  _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,pincode = _pincode,cityId=_cityId,district = _district,state= _state,modifiedBy = _userId WHERE leadId = _leadId;
                        SELECT  _leadId as leadId;
                        IF _customerId != 0 THEN
                        UPDATE customers SET  fullName = _customerFullName, contactNo = _contactNo,aadhaarCardNo= _aadhaarCardNo,panCardNo = _panCardNo, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() 
                        WHERE id = _customerId;
						
                        END IF;
                        
                        IF _customerAddressId != 0 THEN
						UPDATE customeraddresses SET addressTypeId = _addressTypeId, label = _label, addressLine1 = _addressLine1, addressLine2 = _addressLine2
                        , pincode = _pincode, cityId = _cityId, city = _city, district = _district, state = _state, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP()
                        WHERE id = _customerAddressId;
                        END IF;
						
                    END IF;
                END IF;
            END IF;
        END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `InsertUpdateRewardCoin`(IN _id INT, IN _rewardTypeId INT, IN _rewardCoin DECIMAL(15,3), IN _minLoanFile INT, IN _maxLoanFile INT, IN _userId INT)
BEGIN
	IF _id >0 THEN
		UPDATE rewardcoin SET rewardTypeId = _rewardTypeId, rewardCoin = _rewardCoin, minLoanFile = _minLoanFile, maxLoanFile = _maxLoanFile, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = _userId WHERE id = _id;
    ELSE
		INSERT INTO rewardcoin(rewardTypeId, rewardCoin, minLoanFile, maxLoanFile, createdBy, modifiedBy) VALUES(_rewardTypeId, _rewardCoin, _minLoanFile, _maxLoanFile, _userId, _userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `insertUpdateTransferCustomerLoanPropertyDetail`(IN _customerLoanId INT, IN _serviceId INT, IN _loanAmount DECIMAL(15,2), IN _customerId INT, IN _customerLoanPropertyDetailId INT
, IN _propertyTypeId INT, IN _propertyPurchaseValue DECIMAL(15,2), IN _propertyCityId INT, IN _propertyCity VARCHAR(100), IN _propertyDistrict VARCHAR(100), IN _propertyState VARCHAR(100),IN _pincode VARCHAR(10),IN _addressLine1 TEXT, IN _addressLine2 TEXT
, IN _userId INT,IN _partnerId INT,IN _loanAmountTakenExisting DECIMAL(15,2),IN _approxDate DATETIME,IN _topupAmount DECIMAL(15,2),IN _approxCurrentEMI DECIMAL(15,2),IN _bankId INT,IN _customerLoanTransferPropertyDetailId INT,IN _loanType varchar(45))
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE _existId INT DEFAULT 0;
	IF _customerLoanId > 0 THEN
		UPDATE customerloans SET loanAmount = _loanAmount, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP(),loanType= 'Bank Transfer' WHERE id = _customerLoanId;
        
        UPDATE customerloanpropertydetails SET propertyTypeId = _propertyTypeId, propertyPurchaseValue = _propertyPurchaseValue,loanType = _loanType,propertyCityId = _propertyCityId, propertyCity = _propertyCity, pincode = _pincode, addressLine1 =_addressLine1,addressLine2 =_addressLine2
        , propertyDistrict = _propertyDistrict, propertyState = _propertyState, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerLoanPropertyDetailId;

        UPDATE loancompletescreenhistory SET completeScreen = 1 WHERE customerLoanId=_customerLoanId AND completeScreen < 1;
       
    ELSE
		INSERT INTO customerloans(serviceId, loanAmount, customerId,loanType, createdBy, modifiedBy) VALUES(_serviceId, _loanAmount, _customerId,'Bank Transfer', _userId, _userId);
        SET _customerLoanId = LAST_INSERT_ID();
        
        INSERT INTO customerloanpropertydetails(customerLoanId, propertyTypeId, propertyPurchaseValue, propertyCityId, propertyCity, propertyDistrict, propertyState, pincode,addressLine1,addressLine2,loanType,createdBy, modifiedBy) 
        VALUES(_customerLoanId, _propertyTypeId, _propertyPurchaseValue, _propertyCityId, _propertyCity, _propertyDistrict, _propertyState,_pincode,_addressLine1,_addressLine2,_loanType, _userId, _userId);
        SET _customerLoanPropertyDetailId = LAST_INSERT_ID();
        
        IF _partnerId>0 THEN
			INSERT INTO partnerscustomerloans(customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) VALUES(_customerLoanId,_partnerId,CURRENT_TIMESTAMP(),_userId,_userId);
        END IF;
        
        -- UPDATE loancompletescreenhistory SET completeScreen = 1 WHERE customerLoanId=_customerLoanId AND completeScreen < 1;
        INSERT INTO loancompletescreenhistory(customerLoanId,isCompleted,completeScreen) VALUES(_customerLoanId, false, 1);

    END IF;
    		IF 	EXISTS(SELECT 1 FROM customerloantransferpropertydetails) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select customerLoanId FROM customerloantransferpropertydetails WHERE customerLoanId = _customerLoanId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				gettransfercustomerloan: LOOP
					FETCH cur_checkexist INTO _existId;
					IF finished = 1 THEN 
						LEAVE gettransfercustomerloan;
					END IF;
					IF _existId THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting,approxDate = _approxDate,topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI,bankId = _bankId,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE customerLoanId  = _customerLoanId;	
		ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		  SET _customerLoanTransferPropertyDetailId = LAST_INSERT_ID();
        END IF;
        ELSE
			INSERT INTO customerloantransferpropertydetails (customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdby,modifiedBy) VALUES (_customerLoanId,_loanAmountTakenExisting,_approxDate,_topupAmount,_approxCurrentEMI,_bankId,_userId,_userId);
		  SET _customerLoanTransferPropertyDetailId = LAST_INSERT_ID();
        END IF;
    
   /* IF _customerLoanTransferPropertyDetailId > 0 THEN
       UPDATE customerloantransferpropertydetails SET loanAmountTakenExisting = _loanAmountTakenExisting , approxDate = _approxDate , topupAmount = _topupAmount,approxCurrentEMI = _approxCurrentEMI, bankId =_bankId ,modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _customerLoanTransferPropertyDetailId ;
    ELSE 
       INSERT INTO customerloantransferpropertydetails(customerLoanId,loanAmountTakenExisting,approxDate,topupAmount,approxCurrentEMI,bankId,createdBy, modifiedBy) 
	   VALUES(_customerLoanId, _loanAmountTakenExisting, _approxDate, _topupAmount, _approxCurrentEMI, _bankId,_userId, _userId);
	   SET _customerLoanTransferPropertyDetailId = LAST_INSERT_ID();
	END IF;*/
     SELECT _customerLoanId as customerLoanId, _customerLoanPropertyDetailId as customerLoanPropertyDetailId , _customerLoanTransferPropertyDetailId as customerLoanTransferPropertyDetailId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `new_procedure`(IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(businessexperience.id) as totalCount FROM businessexperience WHERE isDelete = 0;
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM businessexperience WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerGetCustomerLoansByStatusId`(IN _partnerId INT, IN _statusId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
    DECLARE customerLoanIds TEXT DEFAULT "";
    DECLARE getQuery TEXT DEFAULT "";
    
     DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											INNER JOIN customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											INNER JOIN partnerscustomerloans ON partnerscustomerloans.customerLoanId = customerloans.id
                                            WHERE customerloanstatushistory.loanStatusId = _statusId AND  partnerscustomerloans.partnerId= _partnerId
                                            LIMIT _fetchRecords OFFSET _startIndex;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
        SET @customerLoanIds="";
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				ELSE
					IF @customerLoanIds !="" THEN
						SET @customerLoanIds = CONCAT_WS(',', @customerLoanIds, cCustomerLoanId);
					ELSE
						SET @customerLoanIds = cCustomerLoanId;
					END IF;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan;
        
        IF @customerLoanIds!="" THEN
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
			WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(", @customerLoanIds,") ) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.id IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
            , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
            FROM customerloanemploymentdetails 
            LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
            LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
            LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
            WHERE customerloanemploymentdetails.customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
			
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM customerloanspouses WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloandocuments.*, documentmasters.name as documentName, servicetypedocuments.isPdf FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM customerloanreferences WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(",@customerLoanIds,");");
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
			SET @getQuery = CONCAT(' SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId IN(',@customerLoanIds,')  AND clf.isShared = 1 AND clf.status IS NULL');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;  
           
              SET @getQuery = "";
            SET @getQuery = CONCAT('SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId IN(',@customerLoanIds,')');
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
        ELSE
			SELECT "No Loans Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerGetIncompleteBusinessLoanRequest`(IN _partnerId INT, IN _serviceId INT,IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
    DECLARE getQuery TEXT DEFAULT "";
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
    
    
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
                                            LEFT join partnerscustomerloans on partnerscustomerloans.customerLoanId=customerloans.id
											WHERE customerloans.serviceId = _serviceId AND partnerscustomerloans.partnerId = _partnerId
                                            AND (loancompletescreenhistory.isCompleted = false) LIMIT _fetchRecord OFFSET _startIndex;
		DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
        SET @customerLoanIds = "";
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				ELSE
					IF @customerLoanIds !="" THEN
						SET @customerLoanIds = CONCAT_WS(',', @customerLoanIds, cCustomerLoanId);
					ELSE
						SET @customerLoanIds = cCustomerLoanId;
					END IF;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan; 
        
        
		IF  @customerLoanIds!="" THEN
           SET @getQuery = "";
		   SET @getQuery = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
           , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
           FROM users 
           INNER JOIN userroles ON userroles.userId = users.id 
           INNER JOIN customers ON customers.userId = users.id 
           LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
           WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(', @customerLoanIds, ') ) AND users.isDelete = 0 AND customeraddresses.addressTypeId = 1 AND users.isActive = 1 AND userroles.roleId IN(2)');
		   
           PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;           
           
           SET @getQuery = "";
		   SET @getQuery = CONCAT('SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
           LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
           LEFT JOIN services ON  services.id = customerloans.serviceId
           WHERE customerloans.serviceId = ',_serviceId,' AND customerloans.id IN(', @customerLoanIds,')');
           PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt; 
            
           SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT customerloandocuments.* FROM customerloandocuments 
           LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
           LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
           WHERE customerloandocuments.customerloanId IN(', @customerLoanIds,')');
          PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
           
           SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT customerloanbusinessdetails.*, companytypes.name as companyType, industrytypes.name as industryTypes, businessexperience.name as businessExperience
		   , businessnatures.name as businessNatures, businessannualprofits.name businessAnnualProfits, banks.name banks FROM customerloanbusinessdetails
		   LEFT JOIN companytypes ON companytypes.id = customerloanbusinessdetails.companyTypeId
		   LEFT JOIN industrytypes ON industrytypes.id = customerloanbusinessdetails.industryTypeId
		   LEFT JOIN businessexperience ON businessexperience.id = customerloanbusinessdetails.businessExperienceId
		   LEFT JOIN businessnatures ON businessnatures.id = customerloanbusinessdetails.businessNatureId
		   LEFT JOIN businessannualprofits ON businessannualprofits.id = customerloanbusinessdetails.businessAnnualProfitId
		   LEFT JOIN banks ON banks.id = customerloanbusinessdetails.primaryBankId
		   WHERE customerloanbusinessdetails.customerloanId IN(', @customerLoanIds, ')');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
		   DEALLOCATE PREPARE stmt;
            
		   SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT customerloancurrentresidentdetails.*, residenttypes.name residentType FROM customerloancurrentresidentdetails
		   LEFT JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId WHERE customerloancurrentresidentdetails.customerLoanId IN(', @customerLoanIds, ')');
           PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
            
		   SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(', @customerLoanIds, ')');
           PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
            
		   SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
		   FROM customerloanstatushistory 
		   INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
           WHERE customerloanId IN(', @customerLoanIds, ')');
           PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
           
              SET @getQuery = "";
			SET @getQuery = CONCAT(' SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId IN(',@customerLoanIds,')  AND clf.isShared = 1 AND clf.status IS NULL');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;    
           
             SET @getQuery = "";
            SET @getQuery = CONCAT('SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId IN(',@customerLoanIds,')');
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		ELSE
		   SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerGetIncompleteCreditCardRequest`(IN _partnerId INT,IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerCreditCardId INT DEFAULT 0;
    DECLARE getQuery TEXT DEFAULT "";
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customercreditcard CURSOR FOR SELECT customercreditcards.id FROM customercreditcards
											      INNER JOIN creditcardcompletescreenhistory on creditcardcompletescreenhistory.customerCreditCardId = customercreditcards.id						
											      LEFT JOIN partnercustomercreditcards on partnercustomercreditcards.customerCreditCardId = customercreditcards.id
											      WHERE partnercustomercreditcards.partnerId = _partnerId LIMIT _fetchRecord OFFSET _startIndex;
                                                  -- AND (creditcardcompletescreenhistory.isCompleted = false);
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN cur_customercreditcard;
        SET @customerLoanCreditCardIds = "";
			cur_customercreditcard_loop: LOOP
				FETCH cur_customercreditcard INTO cCustomerCreditCardId;
                IF finished = 1 THEN
					LEAVE cur_customercreditcard_loop;
				ELSE
					IF @customerLoanCreditCardIds !="" THEN
						SET @customerLoanCreditCardIds = CONCAT_WS(',', @customerLoanCreditCardIds, cCustomerCreditCardId);
					ELSE
						SET @customerLoanCreditCardIds = cCustomerCreditCardId;
					END IF;
				END IF;
            END LOOP cur_customercreditcard_loop;
        CLOSE cur_customercreditcard; 
        
        IF  @customerLoanCreditCardIds!="" THEN
        
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN ( SELECT customercreditcards.customerId FROM customercreditcards WHERE customercreditcards.id IN(', @customerLoanCreditCardIds, ')) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2)');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;   
            
			SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customercreditcards.* FROM customercreditcards 
            WHERE customercreditcards.customerId IN( SELECT customercreditcards.customerId FROM customercreditcards WHERE customercreditcards.id IN(', @customerLoanCreditCardIds, '))');
			PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;   
            
			
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT(' SELECT customercreditcardemploymentdetail.*
            FROM customercreditcardemploymentdetail 
            WHERE customercreditcardemploymentdetail.creditCardId IN(', @customerLoanCreditCardIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt; 
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT(' SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customers.id as customerId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN ( SELECT customercreditcards.customerId FROM customercreditcards WHERE customercreditcards.id IN(', @customerLoanCreditCardIds, ')) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2)');
			PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT(' SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customers.id as customerId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN ( SELECT customercreditcards.customerId FROM customercreditcards WHERE customercreditcards.id IN(', @customerLoanCreditCardIds, ')) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId =2 AND userroles.roleId IN(2)');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT * FROM creditcardcompletescreenhistory WHERE customerCreditCardId IN(', @customerLoanCreditCardIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customercreditcardstatushistory.*, creditcardstatuses.status AS creditCardStatus, creditcardstatuses.isDataEditable AS isDataEditable 
            FROM customercreditcardstatushistory 
            INNER JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcardstatushistory.creditCardStatusId 
            WHERE customerCreditCardId IN(', @customerLoanCreditCardIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            
             SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customercreditcardoffer.*, banks.id as bankId,banks.name as bankName FROM customercreditcardoffer
            INNER JOIN bankcreditcard ON bankcreditcard.id =  customercreditcardoffer.bankCreditCardId
			INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE customerCreditCardId IN(', @customerLoanCreditCardIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
        ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerGetIncompleteHomeLoanRequest`(IN _partnerId INT, IN _serviceId INT,IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
    DECLARE getQuery TEXT DEFAULT "";
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
											LEFT join partnerscustomerloans on partnerscustomerloans.customerLoanId=customerloans.id
											WHERE customerloans.serviceId = _serviceId AND partnerscustomerloans.partnerId = _partnerId
                                            AND (loancompletescreenhistory.isCompleted = false) LIMIT _fetchRecord OFFSET _startIndex;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
        SET @customerLoanIds = "";
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				ELSE
					IF @customerLoanIds !="" THEN
						SET @customerLoanIds = CONCAT_WS(',', @customerLoanIds, cCustomerLoanId);
					ELSE
						SET @customerLoanIds = cCustomerLoanId;
					END IF;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan; 
        
        IF  @customerLoanIds!="" THEN
        
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloanpropertydetails.*, propertytypes.name as propertyType , customerloans.customerId FROM customerloanpropertydetails 
            INNER JOIN propertytypes ON propertytypes.id = customerloanpropertydetails.propertyTypeId 
            INNER JOIN customerloans ON customerloans.id = customerloanpropertydetails.customerLoanId
            WHERE customerloanpropertydetails.customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;   
            
			SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            , customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(', @customerLoanIds, ') ) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 1 AND userroles.roleId IN(2)');
			PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;   
            
			
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            WHERE customerloans.serviceId = ',_serviceId,' AND customerId IN (SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(', @customerLoanIds, '))');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt; 
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
            , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
            FROM customerloanemploymentdetails 
            LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
            LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
            LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
            WHERE customerloanemploymentdetails.customerloanId IN(', @customerLoanIds, ')');
			PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloancoapplicants.*, maritalstatuses.status as maritalStatus, coapplicantrelations.name as coApplicantRelation FROM customerloancoapplicants 
			INNER JOIN maritalstatuses ON maritalstatuses.id = customerloancoapplicants.maritalStatusId
			INNER JOIN coapplicantrelations ON coapplicantrelations.id = customerloancoapplicants.coApplicantRelationId
            WHERE customerloancoapplicants.customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloancoapplicantemploymentdetails.*, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
			, companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
			, designations.name as designation, employmentnatures.name employmentNature, employmentservicetypes.name as employmentServiceType
			FROM customerloancoapplicantemploymentdetails
			INNER JOIN employmenttypes ON employmenttypes.id = customerloancoapplicantemploymentdetails.employmentTypeId
			LEFT JOIN companyaddresses ON  companyaddresses.id = customerloancoapplicantemploymentdetails.companyAddressId
			LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
			LEFT JOIN designations ON designations.id = customerloancoapplicantemploymentdetails.designationId
			LEFT JOIN employmentnatures ON employmentnatures.id = customerloancoapplicantemploymentdetails.employmentNatureId
			LEFT JOIN employmentservicetypes ON employmentservicetypes.id = customerloancoapplicantemploymentdetails.employmentServiceTypeId
            WHERE customerloancoapplicantemploymentdetails.customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloancurrentresidentdetails.*,residenttypes.name as residentType FROM customerloancurrentresidentdetails
			INNER JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId
            WHERE customerloancurrentresidentdetails.customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customers.id as customerId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(', @customerLoanIds, ') ) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 3 AND userroles.roleId IN(2)');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloandocuments.* FROM customerloandocuments 
            LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
            LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
            WHERE customerloandocuments.customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
            FROM customerloanstatushistory 
            INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
            WHERE customerloanId IN(', @customerLoanIds, ')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
             SET @getQuery = "";
			SET @getQuery = CONCAT(' SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId IN(',@customerLoanIds,')  AND clf.isShared = 1 AND clf.status IS NULL');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;    
            
            SET @getQuery = "";
		    SET @getQuery = CONCAT('SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails
            WHERE customerloantransferpropertydetails.customerloanId IN(',@customerLoanIds,')');
            PREPARE stmt FROM @getQuery;
		    EXECUTE stmt;
	        DEALLOCATE PREPARE stmt;
            
        ELSE
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerGetIncompletePersonalLoanRequest`(IN _partnerId INT, IN _serviceId INT,IN _startIndex INT,IN _fetchRecord INT)
BEGIN
	DECLARE finished INT DEFAULT 0;
    DECLARE cUserId INT DEFAULT 0;
    DECLARE cCustomerLoanId INT DEFAULT 0;
     DECLARE cCustomerLoanIdForOffer INT DEFAULT 0;
    DECLARE getQuery TEXT DEFAULT "";
    
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN

     
     
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											inner join loancompletescreenhistory on loancompletescreenhistory.customerLoanId = customerloans.id
                                            LEFT join customerloanstatushistory on customerloanstatushistory.customerLoanId = customerloans.id
											LEFT join loanstatuses on loanstatuses.id = customerloanstatushistory.loanStatusId
                                            LEFT join partnerscustomerloans on partnerscustomerloans.customerLoanId=customerloans.id 
											WHERE customerloans.serviceId = _serviceId AND partnerscustomerloans.partnerId = _partnerId
                                            AND (loancompletescreenhistory.isCompleted = false) LIMIT _fetchRecord OFFSET _startIndex;
        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
        OPEN  cur_customerloan;
        SET @customerLoanIds = "";
			cur_customerloan_loop: LOOP
				FETCH cur_customerloan INTO cCustomerLoanId;
                IF finished = 1 THEN
					LEAVE cur_customerloan_loop;
				ELSE
					IF @customerLoanIds !="" THEN
						SET @customerLoanIds = CONCAT_WS(',', @customerLoanIds, cCustomerLoanId);
					ELSE
						SET @customerLoanIds = cCustomerLoanId;
					END IF;
				END IF;
            END LOOP cur_customerloan_loop;
        CLOSE cur_customerloan; 
        
       
        IF  @customerLoanIds!="" THEN
        SET @getQuery = "";
			SET @getQuery = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.* 
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
									WHERE customerloans.id IN(', @customerLoanIds, ') ) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
           
           SET @getQuery = "";
           SET @getQuery = CONCAT('SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName FROM customerloans 
           LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
           LEFT JOIN services ON  services.id = customerloans.serviceId
           WHERE customerloans.id IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
			
           SET @getQuery = ""; 
           SET @getQuery = CONCAT('SELECT customerloanemploymentdetails.*, companytypes.name AS companyTypeName, companyaddresses.addressTypeId, companyaddresses.label, companyaddresses.addressLine1
           , companyaddresses.addressLine2, companyaddresses.pincode, companyaddresses.cityId, companyaddresses.city, companyaddresses.district, companyaddresses.state, addresstypes.name as addressType
           FROM customerloanemploymentdetails 
           LEFT JOIN companytypes ON  companytypes.id = customerloanemploymentdetails.companyTypeId
           LEFT JOIN companyaddresses ON  companyaddresses.id = customerloanemploymentdetails.companyAddressId
           LEFT JOIN addresstypes ON  addresstypes.id = companyaddresses.addressTypeId
           WHERE customerloanemploymentdetails.customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";  
		   SET @getQuery = CONCAT('SELECT * FROM customerloanspouses WHERE customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
           
           SET @getQuery = "";  
		   SET @getQuery = CONCAT('SELECT customerloandocuments.* FROM customerloandocuments 
           LEFT JOIN servicetypedocuments ON servicetypedocuments.id = customerloandocuments.serviceTypeDocumentId
		   LEFT JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId
		   WHERE customerloandocuments.customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
		
           SET @getQuery = "";  
		   SET @getQuery = CONCAT('SELECT customerloanreferences.*,customerreferenceaddresses.* FROM customerloanreferences LEFT JOIN customerreferenceaddresses ON  customerreferenceaddresses.customerLoanReferenceId = customerloanreferences.id  WHERE customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
            
		   SET @getQuery = "";  
           SET @getQuery = CONCAT('SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;
		   
            SET @getQuery = "";  
		   SET @getQuery = CONCAT('SELECT customerloanstatushistory.*, loanstatuses.status AS loanStatus, loanstatuses.isDataEditable AS isDataEditable 
		   FROM customerloanstatushistory 
		   INNER JOIN loanstatuses ON loanstatuses.id = customerloanstatushistory.loanStatusId 
		   WHERE customerloanId IN(',@customerLoanIds,')');
	       PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt; 
           
           SET @getQuery = CONCAT(' SELECT clf.*,banks.name as bankName FROM customerloandetail as clf INNER JOIN banks ON clf.bankId = banks.id WHERE clf.isActive = 1 AND clf.isDelete = 0 AND clf.customerLoanId IN(',@customerLoanIds,')  AND clf.isShared = 1 AND clf.status IS NULL');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;     
           
			SET @getQuery = CONCAT('SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customeraddresses.city,customeraddresses.state,customeraddresses.district,customers.id as customerId
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN(	SELECT customerloans.customerId FROM customerloans 									
									WHERE customerloans.id IN(', @customerLoanIds, ')) AND users.isDelete = 0 AND users.isActive = 1 AND customeraddresses.addresstypeId = 5 AND userroles.roleId IN(2)');
		   PREPARE stmt FROM @getQuery;
		   EXECUTE stmt;
	       DEALLOCATE PREPARE stmt;  
            SET @getQuery = "";
            SET @getQuery = CONCAT('SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId IN(',@customerLoanIds,')');
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
		ELSE  
			SELECT "Data Not Available" as message;
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `partnerInsertVisitingCard`(IN _partnerId INT,IN _template TEXT, IN _location TEXT,IN _userId INT,IN _visitingCardId INT,IN _partnerVisitingCardId INT,IN _dynamicFields JSON)
BEGIN
	DECLARE partnerVisitingCardId INT DEFAULT 0;
    IF _partnerVisitingCardId > 0 THEN
	   UPDATE partnervisitingcards SET partnerId = _partnerId , template=_template, location = _location ,visitingCardId = _visitingCardId ,dynamicFields =_dynamicFields ,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _partnerVisitingCardId;
       SELECT _partnerVisitingCardId as partnerVisitingCardId;
	ELSE
		INSERT INTO partnervisitingcards (partnerId,template,location,visitingCardId,dynamicFields,createdBy,modifiedBy) VALUES (_partnerId,_template,_location,_visitingCardId,_dynamicFields,_userId,_userId);
    SET partnerVisitingCardId = LAST_INSERT_ID();
    END IF;
    SELECT partnerVisitingCardId as partnerVisitingCardId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `removeHomeLoanCoapplicant`(IN _customerLoanCoApplicantId VARCHAR(100))
BEGIN
  DECLARE front TEXT;
    DECLARE frontlen INT;
   DECLARE TempValue TEXT;
    iterator:
	LOOP  
    IF LENGTH(TRIM(_customerLoanCoApplicantId)) = 0 OR _customerLoanCoApplicantId IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_customerLoanCoApplicantId,',',1);
    SET frontlen = LENGTH(front);
    SET TempValue = TRIM(front);
  DELETE FROM customerloancoapplicantemploymentdetails WHERE customerLoanCoApplicantId = TempValue;
    DELETE FROM customerloancoapplicants WHERE id = TempValue;
    SET _customerLoanCoApplicantId = INSERT(_customerLoanCoApplicantId,1,frontlen + 1,'');
    END LOOP;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `userGetNotifications`(IN _userId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    
	IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(usersnotification.id) as totalCount FROM usersnotification WHERE userId = ",_userId);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT usersnotification.*,notificationtypes.name as notificationTypeName FROM usersnotification LEFT JOIN notificationtypes ON notificationtypes.id = usersnotification.notificationType  WHERE userId = ',_userId,' ORDER BY usersnotification.id DESC ',@StartIndexQuery);

    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;

    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `userUpdateScratchCardStatus`(IN _userScratchCardId INT, IN _value DECIMAL(15,3), IN _userId INT,IN _rewardType INT)
BEGIN
	DECLARE finished_check INT DEFAULT 0;
	DECLARE cUserWalletId INT DEFAULT 0;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_user_check CURSOR FOR SELECT userwallet.id as userWalletId FROM userwallet  WHERE userwallet.userId = _userId;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished_check = 1;
			OPEN  cur_user_check;
				cur_user_check_loop: LOOP
					FETCH cur_user_check INTO cUserWalletId;
                    
                    IF finished_check = 1 THEN
						LEAVE cur_user_check_loop;
					END IF;
                    
                END LOOP cur_user_check_loop;
			CLOSE cur_user_check;
            IF cUserWalletId = 0 THEN
				UPDATE userscratchcards SET isScratched = 1, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _userScratchCardId;
                INSERT INTO userwallet(userId, coin, createdBy, modifiedBy) VALUES(_userId, _value, _userId, _userId);
                SET @userWalletId = LAST_INSERT_ID();
                INSERT INTO userwallethistory(userWalletId, userId, coin,rewardType ,createdBy, modifiedBy) VALUES(@userWalletId, _userId, _value,_rewardType, _userId, _userId);
			ELSE
				UPDATE userscratchcards SET isScratched = 1 WHERE id = _userScratchCardId;
                UPDATE userwallet SET coin = coin+_value, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = cUserWalletId;
                INSERT INTO userwallethistory(userWalletId, userId, coin,rewardType, createdBy, modifiedBy) VALUES(cUserWalletId, _userId, _value,_rewardType,_userId, _userId);
            END IF;
		END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `validateReferLink`(IN _linkKey TEXT)
BEGIN
	SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',"SELECT * FROM referlinks WHERE linkKey LIKE '%",_linkKey,"%'  AND isActive = 1 AND isDelete = 0");
    
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `webInsertReferCustomer`(IN _countryCode VARCHAR(6), IN _contactNo VARCHAR(15), IN _email VARCHAR(256), IN _temporaryCode VARCHAR(45), IN _fullName VARCHAR(200)
, IN _panCardNo VARCHAR(20), IN _addressTypeId INT, IN _label TEXT, IN _addressLine1 TEXT, IN _addressLine2 TEXT, IN _pincode VARCHAR(10), IN _cityId INT, IN _city VARCHAR(100)
, IN _district VARCHAR(100), IN _state VARCHAR(100), IN _referenceUserId INT, IN _referCoin DECIMAL(15,3), IN _registerCoin DECIMAL(15,3), IN _referLinkId INT,IN _referCoinRewardTypeId INT ,IN _registerCoinRewardTypeId INT)
BEGIN
	INSERT INTO users(countryCode, contactNo, isDisabled, email, fullName,currentRoleId) VALUES(_countryCode, _contactNo, 0, _email, _fullName,2);
    SET @userId = LAST_INSERT_ID();
	INSERT INTO userroles(userId,roleId,createdBy,modifiedBy) VALUES(@userId, 2, @userId, @userId);
    INSERT INTO customers(userId, temporaryCode, contactNo, fullName, panCardNo, createdBy, modifiedBy,currentRoleId) VALUES(@userId, _temporaryCode, _contactNo, _fullName, _panCardNo, @userId, @userId,2);
	SET @customerId = LAST_INSERT_ID();
    INSERT INTO customeraddresses(customerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId, city, district, state, createdBy, modifiedBy) 
    VALUES(@customerId, _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, _cityId, _city, _district, _state, @userId, @userId);
    INSERT INTO referusers(userId, referUserId, createdBy, modifiedBy) VALUES(_referenceUserId, @userId, @userId, @userId);
    
    INSERT INTO userscratchcards(userId, value,rewardType,createdBy, modifiedBy) VALUES(_referenceUserId, _referCoin,_referCoinRewardTypeId ,@userId, @userId);
    INSERT INTO userscratchcards(userId, value,rewardType, createdBy, modifiedBy) VALUES(@userId, _registerCoin,_registerCoinRewardTypeId, @userId, @userId);
    
    UPDATE referlinks SET referCount = referCount+1 WHERE id = _referLinkId;
    SELECT @userId as userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetBanks`()
BEGIN
	SELECT * FROM banks;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetCity`()
BEGIN
	SELECT cities.*,districts.name as districtName FROM cities INNER JOIN districts ON districts.id = cities.districtId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetCompanyType`()
BEGIN
	SELECT * FROM companytypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetCountry`()
BEGIN
	SELECT * FROM countries;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetCourses`(IN _degreeId INT)
BEGIN
	IF _degreeId>0 THEN
		SELECT * FROM courses WHERE deegreeId = _degreeId;
	ELSE 
		SELECT * FROM courses;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetDegree`()
BEGIN
	SELECT * FROM degrees;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetDocuments`()
BEGIN
	SELECT * FROM documentmasters;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetEmploymentTypes`()
BEGIN
	SELECT * FROM employmenttypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetLastCustomer`()
BEGIN
	SELECT temporaryCode FROM customers ORDER BY id DESC LIMIT 1;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetLastPartner`()
BEGIN
	SELECT temporaryCode,permanentCode FROM partners ORDER BY id DESC LIMIT 1;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetLeadsByContactNoAndServiceId`(IN _contactNo varchar(20), IN _serviceId INT)
BEGIN
	SELECT leads.* FROM leads INNER JOIN leadstatushistory ON leadstatushistory.leadId = leads.id WHERE contactNo = _contactNo AND serviceId = _serviceId AND leadstatushistory.leadStatusId = 1;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetPartnerRoles`()
BEGIN
	SELECT * FROM roles WHERE name NOT IN('ADMINISTRATOR','CUSTOMERS','SUBDSA');
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetProfessionType`()
BEGIN
	SELECT * FROM professiontypes;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetServices`()
BEGIN
	SELECT * FROM services WHERE isActive = 1 AND isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteGetTowns`()
BEGIN
	SELECT * FROM towns;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteInsertContact`(IN _name VARCHAR(100), IN _email VARCHAR(256), IN _contactNO VARCHAR(20), IN _subject VARCHAR(200), IN _message TEXT)
BEGIN
	INSERT INTO contacts(name,email,contactNo,subject,message) VALUES(_name,_email,_contactNo,_subject,_message);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteInsertLead`(IN userId INT,IN temporaryCode VARCHAR(45), IN addressTypeId INT, IN serviceId INT, IN contactNo varchar(20), IN loanAmount decimal(15,3)
, IN customerFullName varchar(200), IN _pincode VARCHAR(10), IN cityId INT, IN professionTypeId INT, IN email VARCHAR(256), IN panCardNo VARCHAR(20), IN aadhaarCardNo VARCHAR(20), IN primaryBankId INT, IN employmentTypeId INT
, IN loanPurpose TEXT, IN studiedCountryId INT, IN degreeId INT, IN courseId INT, IN monthlyIncome DECIMAL(15,2))
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cCutomerId INT DEFAULT 0;
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_customer CURSOR FOR SELECT id FROM customers WHERE userId = userId;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
            OPEN  cur_customer;
				cur_customer_loop: LOOP
					FETCH cur_customer INTO cCutomerId;
                    
                    IF finished = 1 THEN
						LEAVE cur_customer_loop;
					END IF;
                    
                END LOOP cur_customer_loop;
			CLOSE cur_customer;
            
            IF cCutomerId = 0 THEN
				-- Insert Customer and customer address lead
                INSERT INTO leads(customerFullName,contactNo,email,serviceId,loanAmount,pincode,cityId,professionTypeId,employmentTypeId,panCardNo,aadhaarCardNo,monthlyIncome,primaryBankId,loanPurpose,studiedCountryId,degreeId,courseId,createdBy,modifiedBy) 
                VALUE(customerFullName,contactNo,email,serviceId,loanAmount,_pincode,cityId,professionTypeId,employmentTypeId,panCardNo,aadhaarCardNo,monthlyIncome,primaryBankId,loanPurpose,studiedCountryId,degreeId,courseId,userId,userId);
                SET @leadId = LAST_INSERT_ID();
				-- SELECT @leadId as insertId;
                INSERT INTO leadstatushistory(leadId, leadStatusId, transactionDate) VALUES(@leadId, 1, CURRENT_TIMESTAMP());
                UPDATE users SET fullName = customerFullName, isDisabled = 0, modifiedDate = CURRENT_TIMESTAMP(), modifiedBy = userId WHERE id = userId;
                INSERT INTO customers(userId,temporaryCode,fullName,contactNo,createdBy,modifiedBy) VALUES(userId,temporaryCode,customerFullName,contactNo,userId,userId);
                SET @customerId = LAST_INSERT_ID();
				-- SELECT @customerId as insertId;
               INSERT INTO customeraddresses(customerId,addressTypeId,cityId,createdBy,modifiedBy) VALUES(@customerId,addressTypeId,cityId,userId,userId);
                SELECT * FROM leads WHERE id = @leadId;
            ELSE
				-- Insert Only lead
				INSERT INTO leads(customerFullName,contactNo,email,serviceId,loanAmount,pincode,cityId,professionTypeId,employmentTypeId,panCardNo,aadhaarCardNo,monthlyIncome,primaryBankId,loanPurpose,studiedCountryId,degreeId,courseId,createdBy,modifiedBy) 
                VALUE(customerFullName,contactNo,email,serviceId,loanAmount,_pincode,cityId,professionTypeId,employmentTypeId,panCardNo,aadhaarCardNo,monthlyIncome,primaryBankId,loanPurpose,studiedCountryId,degreeId,courseId,userId,userId);
                SET @leadId = LAST_INSERT_ID();
				-- SELECT @leadId as insertId;
                INSERT INTO leadstatushistory(leadId, leadStatusId, transactionDate) VALUES(@leadId, 1, CURRENT_TIMESTAMP());
                SELECT * FROM leads WHERE id = @leadId;
            END IF;
        END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteInsertPartnerAddress`(IN _partnerId INT, IN _addressTypeId INT, IN _label VARCHAR(45), IN _addressLine1 TEXT, IN _addressLine2 TEXT
, IN _pincode VARCHAR(10), IN _cityId INT)
BEGIN
	INSERT INTO partneraddress(partnerId, addressTypeId, label, addressLine1, addressLine2, pincode, cityId) VALUES(_partnerId, _addressTypeId, _label, _addressLine1, _addressLine2, _pincode, cityId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteInsertPartnerDocument`(IN _partnerId INT, IN _documentId INT, IN _url TEXT)
BEGIN
	INSERT INTO partnerdocuments(partnerId, documentId, url) VALUES(_partnerId, _documentId, _url);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteSignUpPartner`(IN _roleId INT, IN _temporaryCode VARCHAR(45), IN _fullName VARCHAR(200), IN _countryCode VARCHAR(6), IN _contactNo VARCHAR(45), IN _email VARCHAR(45)
, IN _cityId INT, IN _commitment DECIMAL(13,3), IN _professionTypeId INT, IN _workExperience DECIMAL(13,3), IN _haveOffice BOOLEAN, IN _gender VARCHAR(20)
, IN _companyTypeId INT, IN _gstNo VARCHAR(20), IN _udhyamAadharNo VARCHAR(45), IN _companyRegNo VARCHAR(45), IN _referralCode VARCHAR(45))
BEGIN
	INSERT INTO users(fullName, gender, email, countryCode, contactNo, isDisabled) VALUES(_fullName, _gender, _email, _countryCode, _contactNo, true);
    SET @userId = LAST_INSERT_ID();
    INSERT INTO userroles(userId, roleId) VALUES(@userId, _roleId);
    INSERT INTO 
    partners(userId, temporaryCode, fullName, gender, contactNo, cityId, companyTypeId, udhyamAadhaarNo, companyRegNo, professionTypeId, workExperience, haveOffice, gstNo, commitment, referralCode) 
    VALUES(@userId, _temporaryCode, _fullName, _gender, _contactNo, _cityId, _companyTypeId, _udhyamAadharNo, _companyRegNo, _professionTypeId, _workExperience, _haveOffice, _gstNo, _commitment, _referralCode);
    SET @insertId = LAST_INSERT_ID();
	SELECT @insertId as insertId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteUpdateLead`(IN _leadId INT, IN _userId INT, IN _serviceId INT, IN _contactNo varchar(20), IN _loanAmount decimal(15,3), IN _customerFullName varchar(200)
, IN _pincode VARCHAR(10), IN _cityId INT, IN _email VARCHAR(256), IN _panCardNo VARCHAR(20), IN _aadhaarCardNo VARCHAR(20), IN _primaryBankId INT, IN _employmentTypeId INT, IN _loanPurpose TEXT
, IN _studiedCountryId INT, IN _degreeId INT, IN _courseId INT, IN _experience DECIMAL(15,2), IN _annualIncome DECIMAL(15,3), IN _monthlyIncome DECIMAL(15,3))
BEGIN
	DECLARE UpdateQuery TEXT DEFAULT "";
    DECLARE SetStatement TEXT DEFAULT "";
    DECLARE WhereStatement TEXT DEFAULT "";
    
    IF _leadId>0 THEN
		SET @UpdateQuery = "";
        SET @SetStatement = "";
        SET @WhereStatement = "";
        
        SET @UpdateQuery =  'UPDATE leads SET serviceId = ';
		SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, _serviceId);
        IF _contactNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", contactNo = '",_contactNo,"'");
        END IF;
        IF _loanAmount > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", loanAmount = ",_loanAmount);
        END IF;
        IF _customerFullName != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", customerFullName = '",_customerFullName,"'");
        END IF;
        IF _email != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", email = '",_email,"'");
        END IF;
        IF _panCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", panCardNo = '",_panCardNo,"'");
        END IF;
        IF _aadhaarCardNo != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", aadhaarCardNo = '",_aadhaarCardNo,"'");
        END IF;
        IF _primaryBankId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", primaryBankId = ",_primaryBankId);
        END IF;
        IF _employmentTypeId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", employmentTypeId = ",_employmentTypeId);
        END IF;
        IF _loanPurpose != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", loanPurpose = '",_loanPurpose,"'");
        END IF;
        IF _studiedCountryId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", studiedCountryId = ",_studiedCountryId);
        END IF;
        IF _degreeId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", degreeId = ",_degreeId);
        END IF;
        IF _courseId > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", courseId = ",_courseId);
        END IF;
        IF _experience > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", experience = ",_experience);
        END IF;
        IF _annualIncome > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", annualIncome = ",_annualIncome);
        END IF;
        IF _monthlyIncome > 0 THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", monthlyIncome = ",_monthlyIncome);
        END IF;
        IF _cityId > 0 THEN
			 SET @SetStatement = CONCAT_WS('', @SetStatement, ", cityId = ",_cityId);
        END IF;
         IF _pincode != '' THEN
			SET @SetStatement = CONCAT_WS('', @SetStatement, ", pincode = '",_pincode,"'");
        END IF;
    
    SET @UpdateQuery = CONCAT_WS('', @UpdateQuery, @SetStatement," WHERE id = ",_leadId);
    PREPARE stmt FROM @UpdateQuery;
	EXECUTE stmt;
    DEALLOCATE PREPARE stmt; 
	SELECT * FROM leads WHERE id = _leadId;
    END IF;	
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `websiteVerifyContactNo`(IN countryCode varchar(6), IN contactNo varchar(20))
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
	DECLARE cRoleId INT DEFAULT 0;
    
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
	  ROLLBACK;
	END;
    START TRANSACTION;
		BEGIN
			DECLARE cur_user CURSOR FOR SELECT users.id as userId, userroles.roleId as roleId FROM users LEFT JOIN userroles ON userroles.userId = users.id WHERE users.contactNo = contactNo;
            DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
            OPEN  cur_user;
				cur_user_loop: LOOP
					FETCH cur_user INTO cUserId, cRoleId;
                    
                    IF finished = 1 THEN
						LEAVE cur_user_loop;
					END IF;
                    
                END LOOP cur_user_loop;
			CLOSE cur_user;
            
            IF cUserId = 0 THEN
				INSERT INTO users(fullName,countryCode,contactNo) VALUES('Customer',countryCode,contactNo);
                SET @userId = LAST_INSERT_ID();
				SELECT @userId as insertId;
				INSERT INTO userroles(userId,roleId,createdBy,modifiedBy) VALUES(@userId,2,@userId,@userId);
                SELECT * FROM users WHERE id = @userId;
			ELSE
				SELECT cUserId as insertId;
				SELECT * FROM users WHERE id = cUserId;
            END IF;            
		END;
    COMMIT;
END$$
DELIMITER ;














--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `services`
--



CREATE TABLE `services` (
  `id` int NOT NULL AUTO_INCREMENT,
  `serviceTypeId` int NOT NULL,
  `name` varchar(500) NOT NULL,
  `displayName` varchar(500) DEFAULT NULL,
  `description` TEXT,
  `iconUrl` TEXT,
  `colorCode` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_services_serviceTypes_idx` (`serviceTypeId`),
  CONSTRAINT `fk_services_serviceTypes` FOREIGN KEY (`serviceTypeId`) REFERENCES `servicetypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `servicesemploymenttypes`
--



CREATE TABLE `servicesemploymenttypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `serviceId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_servicesemploymenttypes_services_idx` (`serviceId`),
  KEY `fk_servicesemploymenttypes_employmenttypes_idx` (`employmentTypeId`),
  CONSTRAINT `fk_servicesemploymenttypes_employmenttypes` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`),
  CONSTRAINT `fk_servicesemploymenttypes_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `servicetypedocuments`
--



CREATE TABLE `servicetypedocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `serviceId` int DEFAULT NULL,
  `documentId` int DEFAULT NULL,
  `displayName` varchar(100) DEFAULT NULL,
  `documentCount` int DEFAULT NULL,
  `isRequired` tinyint DEFAULT '0',
  `isPdf` tinyint DEFAULT '1',
  `employmentTypeId` int DEFAULT NULL,
  `isRequiredForTransfer` tinyint DEFAULT NULL,
  `isRequiredForNew` tinyint DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_servicetypedecument_services_idx` (`serviceId`),
  KEY `fk_servicetypedecuments_decuments_idx` (`documentId`),
  KEY `fk_servicetypedocumnets_employmenttypes_idx` (`employmentTypeId`),
  CONSTRAINT `fk_servicetypedecuments_decuments` FOREIGN KEY (`documentId`) REFERENCES `documentmasters` (`id`),
  CONSTRAINT `fk_servicetypedecuments_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`),
  CONSTRAINT `fk_servicetypedocumnets_employmenttypes` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=88 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `servicetypes`
--



CREATE TABLE `servicetypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `displayName` varchar(50) DEFAULT NULL,
  `description` TEXT,
  `iconUrl` TEXT,
  `colorCode` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `smstemplates`
--



CREATE TABLE `smstemplates` (
  `id` int NOT NULL AUTO_INCREMENT,
  `type` varchar(50) DEFAULT NULL,
  `template` TEXT,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `spouserelations`
--



CREATE TABLE `spouserelations` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `states`
--



CREATE TABLE `states` (
  `id` int NOT NULL AUTO_INCREMENT,
  `countryId` int NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `code` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_states_countries_idx` (`countryId`),
  CONSTRAINT `fk_states_countries` FOREIGN KEY (`countryId`) REFERENCES `countries` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=82 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `systemflags`
--



CREATE TABLE `systemflags` (
  `id` int NOT NULL AUTO_INCREMENT,
  `flagGroupId` int DEFAULT NULL,
  `valueTypeId` int DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `displayName` varchar(50) DEFAULT NULL,
  `value` TEXT,
  `defaultValue` TEXT,
  `valueList` TEXT,
  `description` TEXT,
  `label` varchar(50) DEFAULT NULL,
  `autoRender` tinyint DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_systemflag_flaggroup_idx` (`flagGroupId`),
  KEY `fk_systemflag_valuetype_idx` (`valueTypeId`),
  CONSTRAINT `fk_systemflag_flaggroup` FOREIGN KEY (`flagGroupId`) REFERENCES `flaggroups` (`id`),
  CONSTRAINT `fk_systemflag_valuetype` FOREIGN KEY (`valueTypeId`) REFERENCES `valuetypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `tenure`
--



CREATE TABLE `tenure` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `towns`
--



CREATE TABLE `towns` (
  `id` int NOT NULL AUTO_INCREMENT,
  `districtId` int DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `latitude` varchar(30) DEFAULT NULL,
  `longitude` varchar(30) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_tows_districts_idx` (`districtId`),
  CONSTRAINT `fk_tows_districts` FOREIGN KEY (`districtId`) REFERENCES `districts` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=825 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `trainings`
--



CREATE TABLE `trainings` (
  `id` int NOT NULL AUTO_INCREMENT,
  `trainingCategoryId` int DEFAULT NULL,
  `title` varchar(45) DEFAULT NULL,
  `url` TEXT,
  `fileName` VARCHAR(255) DEFAULT NULL,
  `documentType` varchar(45) DEFAULT NULL,
  `trainingSubCategoryId` int DEFAULT NULL,
  `assignRole` varchar(200) DEFAULT NULL,
  `completionTime` int DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_training_trainingCategory_idx` (`trainingCategoryId`),
  CONSTRAINT `fk_training_trainingCategory` FOREIGN KEY (`trainingCategoryId`) REFERENCES `triningcategories` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `triningcategories`
--



CREATE TABLE `triningcategories` (
  `id` int NOT NULL AUTO_INCREMENT,
  `parentId` int DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userdevicedetail`
--



CREATE TABLE `userdevicedetail` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `appId` int DEFAULT NULL,
  `deviceId` varchar(300) DEFAULT NULL,
  `fcmToken` varchar(300) DEFAULT NULL,
  `deviceLocation` varchar(300) DEFAULT NULL,
  `deviceManufacturer` varchar(300) DEFAULT NULL,
  `deviceModel` varchar(100) DEFAULT NULL,
  `appVersion` varchar(100) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userdevicedetails`
--



CREATE TABLE `userdevicedetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `appId` int DEFAULT NULL,
  `deviceId` varchar(300) DEFAULT NULL,
  `fcmToken` varchar(300) DEFAULT NULL,
  `deviceLocation` varchar(300) DEFAULT NULL,
  `deviceManufacturer` varchar(300) DEFAULT NULL,
  `deviceModel` varchar(100) DEFAULT NULL,
  `appVersion` varchar(100) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_userdevicedetails_users_idx` (`userId`),
  KEY `fk_userdevicedetails_applications_idx` (`appId`),
  CONSTRAINT `fk_userdevicedetails_applications` FOREIGN KEY (`appId`) REFERENCES `applications` (`id`),
  CONSTRAINT `fk_userdevicedetails_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1120 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userpages`
--



CREATE TABLE `userpages` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `pageId` int DEFAULT NULL,
  `readPermission` tinyint DEFAULT '0',
  `writePermission` tinyint DEFAULT '0',
  `editPermission` tinyint DEFAULT '0',
  `deletePermission` tinyint DEFAULT '0',
  `isAdminVerificationRequired` tinyint DEFAULT '0',
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_userpages_user_idx` (`userId`),
  KEY `fk_userpages_pages_idx` (`pageId`),
  CONSTRAINT `fk_userpages_pages` FOREIGN KEY (`pageId`) REFERENCES `pages` (`id`),
  CONSTRAINT `fk_userpages_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userroles`
--



CREATE TABLE `userroles` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int NOT NULL,
  `roleId` int NOT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=519 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userroles_temp`
--



CREATE TABLE `userroles_temp` (
  `id` int NOT NULL AUTO_INCREMENT,
  `users_tempId` int NOT NULL,
  `roleId` int NOT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `users`
--



CREATE TABLE `users` (
  `id` int NOT NULL AUTO_INCREMENT,
  `fullName` TEXT,
  `gender` varchar(20) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `countryCode` varchar(6) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `password` TEXT,
  `profilePicUrl` TEXT,
  `isBlocked` tinyint DEFAULT '0',
  `isPasswordSet` tinyint DEFAULT NULL,
  `isEmailVerified` tinyint DEFAULT NULL,
  `isDisabled` tinyint DEFAULT NULL,
  `isReceiveMarketingCalls` tinyint DEFAULT '0',
  `designation` varchar(200) DEFAULT NULL,
  `currentRoleId` int DEFAULT NULL,
  `permissionGroupId` int DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint NOT NULL DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1800 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userscratchcards`
--



CREATE TABLE `userscratchcards` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `value` decimal(15,3) DEFAULT NULL,
  `isScratched` tinyint DEFAULT '0',
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  `rewardType` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_userscratchcards_users_idx` (`userId`),
  CONSTRAINT `fk_userscratchcards_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=182 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `usersessions`
--



CREATE TABLE `usersessions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `sessionToken` TEXT NOT NULL,
  `appId` int DEFAULT NULL,
  `userId` int NOT NULL,
  `expireAt` datetime DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `fk_usersessions_applications_idx` (`appId`),
  KEY `fk_usersessions_users_idx` (`userId`),
  CONSTRAINT `fk_usersessions_applications` FOREIGN KEY (`appId`) REFERENCES `applications` (`id`),
  CONSTRAINT `fk_usersessions_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2174 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `usersnotification`
--



CREATE TABLE `usersnotification` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `notificationType` int DEFAULT NULL,
  `title` varchar(200) DEFAULT NULL,
  `message` varchar(200) DEFAULT NULL,
  `bodyJson` json DEFAULT NULL,
  `imgUrl` varchar(300) DEFAULT NULL,
  `isRead` tinyint DEFAULT '0',
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_usernotification_user_idx` (`userId`),
  KEY `fk_usernotification_notificationtypes_idx` (`notificationType`),
  CONSTRAINT `fk_usernotification_notificationtypes` FOREIGN KEY (`notificationType`) REFERENCES `notificationtypes` (`id`),
  CONSTRAINT `fk_usernotification_user` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=250 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `users_temp`
--



CREATE TABLE `users_temp` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `fullName` TEXT,
  `gender` varchar(20) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `countryCode` varchar(6) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `password` TEXT,
  `profilePicUrl` TEXT,
  `isBlocked` tinyint DEFAULT '0',
  `isPasswordSet` tinyint DEFAULT NULL,
  `isEmailVerified` tinyint DEFAULT NULL,
  `isDisabled` tinyint DEFAULT NULL,
  `isReceiveMarketingCalls` tinyint DEFAULT '0',
  `designation` varchar(200) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint NOT NULL DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  `currentRoleId` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `usertokens`
--



CREATE TABLE `usertokens` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int NOT NULL,
  `token` TEXT,
  `expireAt` datetime DEFAULT NULL,
  `isUsed` tinyint DEFAULT '0',
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userwallet`
--



CREATE TABLE `userwallet` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `coin` decimal(15,3) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_userwallet_user_idx` (`userId`),
  CONSTRAINT `fk_userwallet_user` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `userwallethistory`
--



CREATE TABLE `userwallethistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userWalletId` int DEFAULT NULL,
  `userId` int DEFAULT NULL,
  `coin` decimal(15,3) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  `rewardType` int DEFAULT NULL,
  `isWithdrawal` tinyint DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `fk_userwallethistory_userwallet_idx` (`userWalletId`),
  KEY `fk_userwallethistory_user_idx` (`userId`),
  CONSTRAINT `fk_userwallethistory_user` FOREIGN KEY (`userId`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_userwallethistory_userwallet` FOREIGN KEY (`userWalletId`) REFERENCES `userwallet` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=176 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `valuetypes`
--



CREATE TABLE `valuetypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `valueTypeName` varchar(50) DEFAULT NULL,
  `description` TEXT,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











--
-- Host: 192.168.29.201    Database: rupiloans
-- ------------------------------------------------------












--
-- Table structure for table `visitingcards`
--



CREATE TABLE `visitingcards` (
  `id` int NOT NULL AUTO_INCREMENT,
  `template` TEXT,
  `dynamicFields` VARCHAR(255) DEFAULT NULL,
  `location` TEXT,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;










