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












--
-- Table structure for table `addresstypes`
--



CREATE TABLE `addresstypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(100) 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=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `admincommission`
--



CREATE TABLE `admincommission` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `commission` 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_admincommission_users_idx` (`userId`),
  CONSTRAINT `fk_admincommission_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `admincommissionhistory`
--



CREATE TABLE `admincommissionhistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `adminCommissionId` int DEFAULT NULL,
  `userId` int DEFAULT NULL,
  `loanDetailId` int DEFAULT NULL,
  `commission` decimal(15,3) DEFAULT NULL,
  `type` 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_admincommissionhistory_admincommission_idx` (`adminCommissionId`),
  KEY `fk_admincommissionhistory_user_idx` (`userId`),
  KEY `fk_admincommissionhistory_loanDetail_idx` (`loanDetailId`),
  CONSTRAINT `fk_admincommissionhistory_admincommission` FOREIGN KEY (`adminCommissionId`) REFERENCES `admincommission` (`id`),
  CONSTRAINT `fk_admincommissionhistory_loanDetail` FOREIGN KEY (`loanDetailId`) REFERENCES `customerloandetail` (`id`),
  CONSTRAINT `fk_admincommissionhistory_user` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=112 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `adminpanelactions`
--



CREATE TABLE `adminpanelactions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `action` 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=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `adminuseractions`
--



CREATE TABLE `adminuseractions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `adminPanelActionId` int DEFAULT NULL,
  `referenceId` int DEFAULT NULL,
  `jsonValue` 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 `applications`
--



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











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












--
-- Table structure for table `assignuserstraining`
--



CREATE TABLE `assignuserstraining` (
  `id` int NOT NULL AUTO_INCREMENT,
  `trainingId` int NOT NULL,
  `partnerId` int NOT NULL,
  `trainingStatus` varchar(45) NOT NULL,
  `stayTiming` 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_assignuserstraining_training_idx` (`trainingId`),
  KEY `fk_assignuserstraining_partners_idx` (`partnerId`),
  CONSTRAINT `fk_assignuserstraining_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `fk_assignuserstraining_training` FOREIGN KEY (`trainingId`) REFERENCES `trainings` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=2650 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `badges`
--



CREATE TABLE `badges` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankbranches`
--



CREATE TABLE `bankbranches` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `ifscCode` varchar(15) DEFAULT NULL,
  `description` TEXT,
  `cityId` 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_bankbranches_banks_idx` (`bankId`),
  CONSTRAINT `fk_bankbranches_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankcompanycategory`
--



CREATE TABLE `bankcompanycategory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int NOT NULL,
  `companyCategoryTypeId` int DEFAULT NULL,
  `companyCategoryId` 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 `bankcompanycategory_banks_idx` (`bankId`),
  KEY `bankcompanycategory_companycategorytype_idx` (`companyCategoryTypeId`),
  KEY `bankcompanycategory_companycategory_idx` (`companyCategoryId`),
  CONSTRAINT `bankcompanycategory_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `bankcompanycategory_companycategory` FOREIGN KEY (`companyCategoryId`) REFERENCES `companycategory` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `bankcompanycategory_companycategorytype` FOREIGN KEY (`companyCategoryTypeId`) REFERENCES `companycategorytype` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=293 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankcreditcard`
--



CREATE TABLE `bankcreditcard` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `creditCardName` TEXT,
  `benifitDescription` TEXT,
  `keyFeatures` TEXT,
  `joiningfee` decimal(10,2) DEFAULT NULL,
  `renualfee` decimal(10,2) DEFAULT NULL,
  `creditCardUrl` 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`),
  KEY `fk_bankcreditcard_bank_idx` (`bankId`),
  CONSTRAINT `fk_bankcreditcard_bank` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankcreditcardpolicies`
--



CREATE TABLE `bankcreditcardpolicies` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankCreditCardId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `minimumCibilScore` int DEFAULT NULL,
  `minAge` int DEFAULT NULL,
  `maxAge` int DEFAULT NULL,
  `minIncome` decimal(15,3) DEFAULT NULL,
  `companyCategoryTypeId` 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_bankcreditcardpolicies_bankcreditcard_idx` (`bankCreditCardId`),
  KEY `fk_bankcreditcardpolicies_employmenttype_idx` (`employmentTypeId`),
  KEY `fk_bankcreditcardpolicies_companycategorytype_idx` (`companyCategoryTypeId`),
  CONSTRAINT `fk_bankcreditcardpolicies_bankcreditcard` FOREIGN KEY (`bankCreditCardId`) REFERENCES `bankcreditcard` (`id`),
  CONSTRAINT `fk_bankcreditcardpolicies_companycategorytype` FOREIGN KEY (`companyCategoryTypeId`) REFERENCES `companycategorytype` (`id`),
  CONSTRAINT `fk_bankcreditcardpolicies_employmenttype` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankloancommissions`
--



CREATE TABLE `bankloancommissions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `commissionTypeId` int DEFAULT '1',
  `commission` decimal(5,2) 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_bankloancommissions_banks_idx` (`bankId`),
  KEY `fk_bankloancommissions_services_idx` (`serviceId`),
  KEY `fk_bankloancommissions_commissiontypes_idx` (`commissionTypeId`),
  CONSTRAINT `fk_bankloancommissions_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_bankloancommissions_commissiontypes` FOREIGN KEY (`commissionTypeId`) REFERENCES `commissiontypes` (`id`),
  CONSTRAINT `fk_bankloancommissions_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankloanpartnercommissions`
--



CREATE TABLE `bankloanpartnercommissions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `bankLoanCommissionId` int DEFAULT NULL,
  `commissionTypeId` int DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `commissionTemplateId` int DEFAULT NULL,
  `commission` decimal(5,2) 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_bankloanpartnercommission_bankloancommission_idx` (`bankLoanCommissionId`),
  KEY `fk_bankloanpartnercommission_commissiontypes_idx` (`commissionTypeId`),
  KEY `fk_bankloanpartnercommission_banks_idx` (`bankId`),
  KEY `fk_bankloanpartnercommission_services_idx` (`serviceId`),
  KEY `fk_bankloanpartnercommission_partner_idx` (`partnerId`),
  KEY `fk_bankloanpartnercommission_commissiontemplate_idx` (`commissionTemplateId`),
  CONSTRAINT `fk_bankloanpartnercommission_bankloancommission` FOREIGN KEY (`bankLoanCommissionId`) REFERENCES `bankloancommissions` (`id`),
  CONSTRAINT `fk_bankloanpartnercommission_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_bankloanpartnercommission_commissiontemplate` FOREIGN KEY (`commissionTemplateId`) REFERENCES `commissiontemplate` (`id`),
  CONSTRAINT `fk_bankloanpartnercommission_commissiontypes` FOREIGN KEY (`commissionTypeId`) REFERENCES `commissiontypes` (`id`),
  CONSTRAINT `fk_bankloanpartnercommission_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_bankloanpartnercommission_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=376 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankloanpolicies`
--



CREATE TABLE `bankloanpolicies` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `bankLoanId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `cibilScore` varchar(200) DEFAULT NULL,
  `minIncome` decimal(15,3) DEFAULT NULL,
  `vintage` int DEFAULT NULL,
  `minTurnOver` decimal(16,2) DEFAULT NULL,
  `maxTurnOver` decimal(16,2) DEFAULT NULL,
  `tenure` varchar(100) DEFAULT NULL,
  `minLoanAmount` decimal(16,2) DEFAULT NULL,
  `ROI` decimal(10,2) DEFAULT NULL,
  `itrRequired` int DEFAULT NULL,
  `companyCategoryTypeId` int DEFAULT NULL,
  `maxLoanAmount` decimal(16,2) 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_bankloanpolicies_banks_idx` (`bankId`),
  KEY `fk_bankloanpolicies_bankloans_idx` (`bankLoanId`),
  KEY `fk_bankloanpolicies_employmenttype_idx` (`employmentTypeId`),
  KEY `fk_bankloanpolicies_services_idx` (`serviceId`),
  CONSTRAINT `fk_bankloanpolicies_bankloans` FOREIGN KEY (`bankLoanId`) REFERENCES `bankloans` (`id`),
  CONSTRAINT `fk_bankloanpolicies_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_bankloanpolicies_employmenttype` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`),
  CONSTRAINT `fk_bankloanpolicies_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=51 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankloans`
--



CREATE TABLE `bankloans` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `loanName` varchar(200) 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_bankloan_bank_idx` (`bankId`),
  KEY `fk_bankloans_services_idx` (`serviceId`),
  CONSTRAINT `fk_bankloans_bank` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_bankloans_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `bankpayouts`
--



CREATE TABLE `bankpayouts` (
  `id` int NOT NULL AUTO_INCREMENT,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `payoutAmount` decimal(13,3) DEFAULT NULL,
  `month` varchar(45) DEFAULT NULL,
  `fromDate` datetime DEFAULT NULL,
  `toDate` datetime DEFAULT NULL,
  `releaseAt` datetime 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_bankpayout_banks_idx` (`bankId`),
  KEY `fk_bankpayout_services_idx` (`serviceId`),
  CONSTRAINT `fk_bankpayout_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_bankpayout_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `banks`
--



CREATE TABLE `banks` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` TEXT,
  `description` TEXT,
  `headquarters` TEXT,
  `bankCode` varchar(45) DEFAULT NULL,
  `minAge` int DEFAULT NULL,
  `maxAge` int DEFAULT NULL,
  `bankLogo` 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=26 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `banners`
--



CREATE TABLE `banners` (
  `id` int NOT NULL AUTO_INCREMENT,
  `roleId` int NOT NULL,
  `url` TEXT,
  `fromDate` datetime DEFAULT NULL,
  `toDate` datetime 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 `becomeapartnerrequest`
--



CREATE TABLE `becomeapartnerrequest` (
  `id` int NOT NULL AUTO_INCREMENT,
  `fullName` VARCHAR(255) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `customerId` int DEFAULT NULL,
  `gender` varchar(45) DEFAULT NULL,
  `aadharCardNo` varchar(45) DEFAULT NULL,
  `panCardNo` varchar(45) DEFAULT NULL,
  `businessCommitement` varchar(45) DEFAULT NULL,
  `jobType` varchar(45) DEFAULT NULL,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `district` varchar(200) DEFAULT NULL,
  `state` varchar(200) 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=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `businessaddressproofs`
--



CREATE TABLE `businessaddressproofs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `addressProofName` varchar(200) 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 `businessannualprofits`
--



CREATE TABLE `businessannualprofits` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` 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=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `businessannualsales`
--



CREATE TABLE `businessannualsales` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) 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=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `businessexperience`
--



CREATE TABLE `businessexperience` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` 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=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `businessnatures`
--



CREATE TABLE `businessnatures` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` 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=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `businessproofs`
--



CREATE TABLE `businessproofs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `businessProofName` varchar(200) 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 `cities`
--



CREATE TABLE `cities` (
  `id` int NOT NULL AUTO_INCREMENT,
  `districtId` int DEFAULT NULL,
  `name` varchar(200) DEFAULT NULL,
  `pincode` varchar(10) 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_cities_districts_idx` (`districtId`),
  CONSTRAINT `fk_cities_districts` FOREIGN KEY (`districtId`) REFERENCES `districts` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=153850 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `coapplicantrelations`
--



CREATE TABLE `coapplicantrelations` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `commissiontemplate`
--



CREATE TABLE `commissiontemplate` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) DEFAULT NULL,
  `commissionTypeId` int DEFAULT NULL,
  `commission` decimal(5,2) DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `bankLoanCommissionId` 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_commissiontemplate_commissiontype_idx` (`commissionTypeId`),
  KEY `fk_commissiontemplate_bankId_idx` (`bankId`),
  KEY `fk_commissionTemplate_services_idx` (`serviceId`),
  KEY `fk_commissionTemplate_bankLoanCommissionId_idx` (`bankLoanCommissionId`),
  CONSTRAINT `fk_commissiontemplate_bankId` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `fk_commissionTemplate_bankLoanCommissionId` FOREIGN KEY (`bankLoanCommissionId`) REFERENCES `bankloancommissions` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `fk_commissiontemplate_commissiontype` FOREIGN KEY (`commissionTypeId`) REFERENCES `commissiontypes` (`id`),
  CONSTRAINT `fk_commissionTemplate_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `commissiontypes`
--



CREATE TABLE `commissiontypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `parentId` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `companyaddresses`
--



CREATE TABLE `companyaddresses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `addressTypeId` int DEFAULT NULL,
  `label` TEXT,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `district` varchar(100) DEFAULT NULL,
  `state` 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`),
  KEY `fk_companyaddresses_addresstypes_idx` (`addressTypeId`),
  KEY `fk_companyaddresses_cities_idx` (`cityId`),
  CONSTRAINT `fk_companyaddresses_addresstypes` FOREIGN KEY (`addressTypeId`) REFERENCES `addresstypes` (`id`),
  CONSTRAINT `fk_companyaddresses_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=373 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `companycategory`
--



CREATE TABLE `companycategory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `companyCategoryTypeId` int DEFAULT NULL,
  `companyName` 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`),
  KEY `fk_companycategory_companycategorytype_idx` (`companyCategoryTypeId`),
  CONSTRAINT `fk_companycategory_companycategorytype` FOREIGN KEY (`companyCategoryTypeId`) REFERENCES `companycategorytype` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25363 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `companycategorytype`
--



CREATE TABLE `companycategorytype` (
  `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=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `companytypes`
--



CREATE TABLE `companytypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `contacts`
--



CREATE TABLE `contacts` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `contactNo` varchar(20) DEFAULT NULL,
  `subject` varchar(200) DEFAULT NULL,
  `message` TEXT,
  `contactDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `status` 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=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `countries`
--



CREATE TABLE `countries` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(60) DEFAULT NULL,
  `isoCode` varchar(25) DEFAULT NULL,
  `isoCode3` varchar(25) DEFAULT NULL,
  `dialCode` varchar(10) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `courses`
--



CREATE TABLE `courses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `deegreeId` int DEFAULT NULL,
  `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`),
  KEY `fk_courses_degree_idx` (`deegreeId`),
  CONSTRAINT `fk_courses_degree` FOREIGN KEY (`deegreeId`) REFERENCES `degrees` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `creditcardcompletescreenhistory`
--



CREATE TABLE `creditcardcompletescreenhistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerCreditCardId` int DEFAULT NULL,
  `isCompleted` tinyint DEFAULT NULL,
  `completeScreen` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `creditcardstatuses`
--



CREATE TABLE `creditcardstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status` varchar(45) DEFAULT NULL,
  `isDataEditable` tinyint DEFAULT '1',
  `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=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customeraddresses`
--



CREATE TABLE `customeraddresses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerId` int DEFAULT NULL,
  `addressTypeId` int DEFAULT NULL,
  `label` TEXT,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `district` varchar(100) DEFAULT NULL,
  `state` 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`),
  KEY `fk_customeraddress_customers_idx` (`customerId`),
  KEY `fk_customeraddress_addresstypes_idx` (`addressTypeId`),
  KEY `fk_customeraddress_cities_idx` (`cityId`),
  CONSTRAINT `fk_customeraddress_addresstypes` FOREIGN KEY (`addressTypeId`) REFERENCES `addresstypes` (`id`),
  CONSTRAINT `fk_customeraddress_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_customeraddress_customers` FOREIGN KEY (`customerId`) REFERENCES `customers` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=621 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customeraddresses_temp`
--



CREATE TABLE `customeraddresses_temp` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customers_tempId` int DEFAULT NULL,
  `addressTypeId` int DEFAULT NULL,
  `label` TEXT,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `district` varchar(100) DEFAULT NULL,
  `state` 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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customercreditcardemploymentdetail`
--



CREATE TABLE `customercreditcardemploymentdetail` (
  `id` int NOT NULL AUTO_INCREMENT,
  `creditCardId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `companyName` varchar(45) DEFAULT NULL,
  `professionName` varchar(45) DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `bankAccountNo` varchar(45) DEFAULT NULL,
  `lastItr` TEXT,
  `officeContactNo` varchar(45) DEFAULT NULL,
  `educationTypeId` 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`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  KEY `creditcardemploymentdetail_creditcard_idx` (`creditCardId`),
  KEY `creditcardemploymentdetail_employmenttypes_idx` (`employmentTypeId`),
  CONSTRAINT `creditcardemploymentdetail_creditcard` FOREIGN KEY (`creditCardId`) REFERENCES `customercreditcards` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `creditcardemploymentdetail_employmenttypes` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=87 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customercreditcardoffer`
--



CREATE TABLE `customercreditcardoffer` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerCreditCardId` int DEFAULT NULL,
  `bankCreditCardId` int DEFAULT NULL,
  `referenceNo` 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=69 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customercreditcardrejectionreason`
--



CREATE TABLE `customercreditcardrejectionreason` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerCreditCardId` int DEFAULT NULL,
  `reason` 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`),
  KEY `fk_customercreditcardrejectionreason_customercreditcard_idx` (`customerCreditCardId`),
  CONSTRAINT `fk_customercreditcardrejectionreason_customercreditcard` FOREIGN KEY (`customerCreditCardId`) REFERENCES `customercreditcards` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customercreditcards`
--



CREATE TABLE `customercreditcards` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerId` int DEFAULT NULL,
  `isAlreadyCreditCard` tinyint DEFAULT NULL,
  `otherCreditCardBankId` int DEFAULT NULL,
  `maxCreditLimit` varchar(45) DEFAULT NULL,
  `availableCreditLimit` varchar(45) DEFAULT NULL,
  `communicationAddressId` 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,
  `statusId` int DEFAULT NULL,
  `creditCardTransactionDate` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customercreditcardstatushistory`
--



CREATE TABLE `customercreditcardstatushistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerCreditCardId` int DEFAULT NULL,
  `creditCardStatusId` int DEFAULT NULL,
  `transactionDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `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=218 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerdocuments`
--



CREATE TABLE `customerdocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerId` int DEFAULT NULL,
  `panCardUrl` TEXT,
  `aadhaarCardUrl` 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`),
  KEY `fk_customerdocuments_customers_idx` (`customerId`),
  CONSTRAINT `fk_customerdocuments_customers` FOREIGN KEY (`customerId`) REFERENCES `customers` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanbusinessdetails`
--



CREATE TABLE `customerloanbusinessdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `companyTypeId` int DEFAULT NULL,
  `industryTypeId` int DEFAULT NULL,
  `businessAnnualSale` decimal(15,3) DEFAULT NULL,
  `businessExperienceId` int DEFAULT NULL,
  `businessNatureId` int DEFAULT NULL,
  `businessAnnualProfitId` int DEFAULT NULL,
  `primaryBankId` int DEFAULT NULL,
  `currentlyPayEmi` decimal(15,3) DEFAULT NULL,
  `businessGstNo` varchar(15) DEFAULT NULL,
  `businessName` varchar(100) DEFAULT NULL,
  `companyName` varchar(100) DEFAULT NULL,
  `address` TEXT,
  `countryId` int DEFAULT NULL,
  `stateId` int DEFAULT NULL,
  `cityId` 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_loanbusinessdetail_customerLoan_idx` (`customerLoanId`),
  KEY `fk_loanbusinessdetail_companytypes_idx` (`companyTypeId`),
  KEY `fk_loanbusinessdetail_industrytypes_idx` (`industryTypeId`),
  KEY `fk_loanbusinessdetail_countries_idx` (`countryId`),
  KEY `fk_loanbusinessdetail_states_idx` (`stateId`),
  KEY `fk_loanbusinessdetail_cities_idx` (`cityId`),
  KEY `fk_loanbusinessdetail_businessexperience_idx` (`businessExperienceId`),
  KEY `fk_loanbusinessdetail_businessnature_idx` (`businessNatureId`),
  KEY `fk_loanbusinessdetail_businessannualprofit_idx` (`businessAnnualProfitId`),
  KEY `fk_loanbusinessdetail_bank_idx` (`primaryBankId`),
  CONSTRAINT `fk_loanbusinessdetail_bank` FOREIGN KEY (`primaryBankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_businessannualprofit` FOREIGN KEY (`businessAnnualProfitId`) REFERENCES `businessannualprofits` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_businessexperience` FOREIGN KEY (`businessExperienceId`) REFERENCES `businessexperience` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_businessnature` FOREIGN KEY (`businessNatureId`) REFERENCES `businessnatures` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_companytypes` FOREIGN KEY (`companyTypeId`) REFERENCES `companytypes` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_countries` FOREIGN KEY (`countryId`) REFERENCES `countries` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_customerLoan` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_industrytypes` FOREIGN KEY (`industryTypeId`) REFERENCES `industrytypes` (`id`),
  CONSTRAINT `fk_loanbusinessdetail_states` FOREIGN KEY (`stateId`) REFERENCES `states` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=160 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanbusinesspartnerdetails`
--



CREATE TABLE `customerloanbusinesspartnerdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `customerLoanBusinessDetailId` int DEFAULT NULL,
  `fullName` varchar(200) DEFAULT NULL,
  `contractNo` varchar(15) DEFAULT NULL,
  `panCardNo` varchar(20) 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_businesspartnerdetail_businessdetail_idx` (`customerLoanBusinessDetailId`),
  KEY `fk_businesspartnerdetail_customerloans_idx` (`customerLoanId`),
  CONSTRAINT `fk_businesspartnerdetail_businessdetail` FOREIGN KEY (`customerLoanBusinessDetailId`) REFERENCES `customerloanbusinessdetails` (`id`),
  CONSTRAINT `fk_businesspartnerdetail_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloancoapplicantemploymentdetails`
--



CREATE TABLE `customerloancoapplicantemploymentdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanCoApplicantId` int DEFAULT NULL,
  `customerLoanId` int DEFAULT NULL,
  `monthlyIncome` decimal(15,3) DEFAULT NULL,
  `otherIncome` decimal(15,3) DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `companyAddressId` int DEFAULT NULL,
  `officePincode` varchar(8) DEFAULT NULL,
  `companyName` TEXT,
  `companyAddress` TEXT,
  `cityId` int DEFAULT NULL,
  `designationId` int DEFAULT NULL,
  `employmentNatureId` int DEFAULT NULL,
  `employmentServiceTypeId` int DEFAULT NULL,
  `currentCompanyExperience` decimal(5,2) DEFAULT NULL,
  `experienceInProfession` decimal(5,2) 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,
  `industryTypeId` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_coapplicantemployment_coapplicant_idx` (`customerLoanCoApplicantId`),
  KEY `fk_coapplicantemployment_customerloan_idx` (`customerLoanId`),
  KEY `fk_coapplicantemployment_cities_idx` (`cityId`),
  KEY `fk_coapplicantemployment_designations_idx` (`designationId`),
  KEY `fk_coapplicantemployment_employmentnatures_idx` (`employmentNatureId`),
  KEY `fk_coapplicantemployment_employmentservicetypes_idx` (`employmentServiceTypeId`),
  KEY `fk_coapplicantemployment_employmenttype_idx` (`employmentTypeId`),
  KEY `fk_coapplicantemployment_companyaddress_idx` (`companyAddressId`),
  CONSTRAINT `fk_coapplicantemployment_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_coapplicantemployment_coapplicant` FOREIGN KEY (`customerLoanCoApplicantId`) REFERENCES `customerloancoapplicants` (`id`),
  CONSTRAINT `fk_coapplicantemployment_companyaddress` FOREIGN KEY (`companyAddressId`) REFERENCES `companyaddresses` (`id`),
  CONSTRAINT `fk_coapplicantemployment_customerloan` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_coapplicantemployment_designations` FOREIGN KEY (`designationId`) REFERENCES `designations` (`id`),
  CONSTRAINT `fk_coapplicantemployment_employmentnatures` FOREIGN KEY (`employmentNatureId`) REFERENCES `employmentnatures` (`id`),
  CONSTRAINT `fk_coapplicantemployment_employmentservicetypes` FOREIGN KEY (`employmentServiceTypeId`) REFERENCES `employmentservicetypes` (`id`),
  CONSTRAINT `fk_coapplicantemployment_employmenttype` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloancoapplicants`
--



CREATE TABLE `customerloancoapplicants` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `fullName` varchar(200) DEFAULT NULL,
  `birthdate` datetime DEFAULT NULL,
  `maritalStatusId` int DEFAULT NULL,
  `coApplicantRelationId` 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_customerloancoapplicant_customerloan_idx` (`customerLoanId`),
  KEY `fk_customerloancoapplicant_maritalstatus_idx` (`maritalStatusId`),
  KEY `fk_customerloancoapplicant_coapplicantrelations_idx` (`coApplicantRelationId`),
  CONSTRAINT `fk_customerloancoapplicant_coapplicantrelations` FOREIGN KEY (`coApplicantRelationId`) REFERENCES `coapplicantrelations` (`id`),
  CONSTRAINT `fk_customerloancoapplicant_customerloan` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloancoapplicant_maritalstatus` FOREIGN KEY (`maritalStatusId`) REFERENCES `maritalstatuses` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=123 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloancurrentresidentdetails`
--



CREATE TABLE `customerloancurrentresidentdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `residentTypeId` int DEFAULT NULL,
  `rentAmount` decimal(10,3) DEFAULT NULL,
  `valueOfProperty` decimal(15,2) DEFAULT NULL,
  `monthlyHouseHold` 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_currentresident_customerloans_idx` (`customerLoanId`),
  KEY `fk_currentresident_residenttypes_idx` (`residentTypeId`),
  CONSTRAINT `fk_currentresident_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_currentresident_residenttypes` FOREIGN KEY (`residentTypeId`) REFERENCES `residenttypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=545 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloandetail`
--



CREATE TABLE `customerloandetail` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int NOT NULL,
  `refrenceNo` varchar(45) NOT NULL,
  `email` varchar(100) DEFAULT NULL,
  `amountDisbursed` decimal(16,2) NOT NULL,
  `ROI` decimal(6,2) NOT NULL,
  `bankId` int NOT NULL,
  `emi` decimal(16,2) NOT NULL,
  `termsCondition` varchar(200) DEFAULT NULL,
  `tenure` int DEFAULT NULL,
  `totalInterestPayable` decimal(12,2) DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  `isAccept` tinyint(1) DEFAULT NULL,
  `isShared` 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_customerloandetail_customerloanId_idx` (`customerLoanId`),
  CONSTRAINT `fk_customerloandetail_customerloanId` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=230 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloandocuments`
--



CREATE TABLE `customerloandocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `serviceTypeDocumentId` int DEFAULT NULL,
  `documentId` int DEFAULT NULL,
  `documentUrl` TEXT,
  `documentStatus` 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_customerloandocuments_customerloans_idx` (`customerLoanId`),
  KEY `fk_customerloandocuments_servicetypedocuments_idx` (`serviceTypeDocumentId`),
  KEY `fk_customerloandocuments_documents_idx` (`documentId`),
  CONSTRAINT `fk_customerloandocuments_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloandocuments_documents` FOREIGN KEY (`documentId`) REFERENCES `documentmasters` (`id`),
  CONSTRAINT `fk_customerloandocuments_servicetypedocuments` FOREIGN KEY (`serviceTypeDocumentId`) REFERENCES `servicetypedocuments` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2280 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanemploymentdetails`
--



CREATE TABLE `customerloanemploymentdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerloanId` int DEFAULT NULL,
  `monthlyIncome` decimal(15,2) DEFAULT NULL,
  `otherIncome` decimal(15,2) DEFAULT NULL,
  `companyTypeId` int DEFAULT NULL,
  `companyName` varchar(100) DEFAULT NULL,
  `companyAddressId` int DEFAULT NULL,
  `officePincode` varchar(8) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `designationId` int DEFAULT NULL,
  `designation` varchar(100) DEFAULT NULL,
  `employmentNatureId` int DEFAULT NULL,
  `employmentServiceTypeId` int DEFAULT NULL,
  `currentCompanyExperience` decimal(10,2) DEFAULT NULL,
  `experienceInProfession` decimal(5,2) 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,
  `industryTypeId` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_customerloanemploymentdetails_customerloans_idx` (`customerloanId`),
  KEY `fk_customerloanemploymentdetails_cities_idx` (`cityId`),
  KEY `fk_customerloanemploymentdetails_designations_idx` (`designationId`),
  KEY `fk_customerloanemploymentdetails_employmentServiceType_idx` (`employmentServiceTypeId`),
  KEY `fk_customerloanemploymentdetails_employnatures_idx` (`employmentNatureId`),
  KEY `fk_customerloanemploymentdetails_companyaddress_idx` (`companyAddressId`),
  CONSTRAINT `fk_customerloanemploymentdetails_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_customerloanemploymentdetails_companyaddress` FOREIGN KEY (`companyAddressId`) REFERENCES `companyaddresses` (`id`),
  CONSTRAINT `fk_customerloanemploymentdetails_customerloans` FOREIGN KEY (`customerloanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloanemploymentdetails_designations` FOREIGN KEY (`designationId`) REFERENCES `designations` (`id`),
  CONSTRAINT `fk_customerloanemploymentdetails_employmentServiceType` FOREIGN KEY (`employmentServiceTypeId`) REFERENCES `employmentservicetypes` (`id`),
  CONSTRAINT `fk_customerloanemploymentdetails_employnatures` FOREIGN KEY (`employmentNatureId`) REFERENCES `employmentnatures` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=310 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloannominees`
--



CREATE TABLE `customerloannominees` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `nomineeFullName` varchar(200) DEFAULT NULL,
  `nomineeRelationId` 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_customerloannominee_nomineerealations_idx` (`nomineeRelationId`),
  KEY `fk_customerloannominee_customerloans_idx` (`customerLoanId`),
  CONSTRAINT `fk_customerloannominee_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloannominee_nomineerealations` FOREIGN KEY (`nomineeRelationId`) REFERENCES `nomineerelations` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanoffers`
--



CREATE TABLE `customerloanoffers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `status` varchar(45) DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `cibilScore` int DEFAULT NULL,
  `minAge` int DEFAULT NULL,
  `maxAge` int DEFAULT NULL,
  `minIncome` decimal(15,3) DEFAULT NULL,
  `vintage` int DEFAULT NULL,
  `minTurnOver` decimal(16,2) DEFAULT NULL,
  `maxTurnOver` decimal(16,2) DEFAULT NULL,
  `tenure` varchar(100) DEFAULT NULL,
  `ROI` decimal(4,2) DEFAULT NULL,
  `minLoanAmount` decimal(16,2) DEFAULT NULL,
  `maxLoanAmount` decimal(16,2) DEFAULT NULL,
  `companyCategoryTypeId` int DEFAULT NULL,
  `otherDetail` TEXT,
  `fileStatus` 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 `customerloanoffers_customerloanId_idx` (`customerLoanId`),
  CONSTRAINT `customerloanoffers_customerloanId` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=118 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanpropertydetails`
--



CREATE TABLE `customerloanpropertydetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `propertyTypeId` int DEFAULT NULL,
  `propertyPurchaseValue` decimal(15,2) DEFAULT NULL,
  `propertyCityId` int DEFAULT NULL,
  `propertyCity` varchar(100) DEFAULT NULL,
  `propertyDistrict` varchar(100) DEFAULT NULL,
  `propertyState` 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,
  `pincode` varchar(10) DEFAULT NULL,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `loanType` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_loanproperty_customerloan_idx` (`customerLoanId`),
  KEY `fk_loanproperty_propertytypes_idx` (`propertyTypeId`),
  CONSTRAINT `fk_loanproperty_customerloan` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_loanproperty_propertytypes` FOREIGN KEY (`propertyTypeId`) REFERENCES `propertytypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=120 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanreferences`
--



CREATE TABLE `customerloanreferences` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `fullName` varchar(100) DEFAULT NULL,
  `contactNo` varchar(15) 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_loanreferences_customerloans_idx` (`customerLoanId`),
  CONSTRAINT `fk_loanreferences_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=296 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanrejectionreason`
--



CREATE TABLE `customerloanrejectionreason` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int NOT NULL,
  `reason` TEXT 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`,`customerLoanId`),
  KEY `fk_customerloanrejectionreason_customerloanId_idx` (`customerLoanId`),
  CONSTRAINT `fk_customerloanrejectionreason_customerloanId` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloans`
--



CREATE TABLE `customerloans` (
  `id` int NOT NULL AUTO_INCREMENT,
  `leadId` int DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `loanAmount` decimal(15,2) DEFAULT NULL,
  `customerId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `motherName` varchar(100) DEFAULT NULL,
  `fatherContactNo` varchar(15) DEFAULT NULL,
  `loanAgainstCollateralId` int DEFAULT NULL,
  `assignRMId` int DEFAULT NULL,
  `statusId` int DEFAULT NULL,
  `tenureId` int DEFAULT NULL,
  `fatherName` varchar(100) DEFAULT NULL,
  `loanTransactionDate` datetime 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,
  `loanType` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_customerloans_leads_idx` (`leadId`),
  KEY `fk_customerloans_servies_idx` (`serviceId`),
  KEY `fk_customerloans_customer_idx` (`customerId`),
  KEY `fk_customerloans_employmenttypes_idx` (`employmentTypeId`),
  KEY `fk_customerloans_loanagainstcollteral_idx` (`loanAgainstCollateralId`),
  KEY `fk_customerloans_statusId_idx` (`statusId`),
  KEY `fk_customerloans_tenureId_idx` (`tenureId`),
  CONSTRAINT `fk_customerloans_customer` FOREIGN KEY (`customerId`) REFERENCES `customers` (`id`),
  CONSTRAINT `fk_customerloans_employmenttypes` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`),
  CONSTRAINT `fk_customerloans_leads` FOREIGN KEY (`leadId`) REFERENCES `leads` (`id`),
  CONSTRAINT `fk_customerloans_loanagainstcollteral` FOREIGN KEY (`loanAgainstCollateralId`) REFERENCES `loanagainstcollteral` (`id`),
  CONSTRAINT `fk_customerloans_servies` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`),
  CONSTRAINT `fk_customerloans_statusId` FOREIGN KEY (`statusId`) REFERENCES `loanstatuses` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `fk_customerloans_tenureId` FOREIGN KEY (`tenureId`) REFERENCES `tenure` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=407 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanspouses`
--



CREATE TABLE `customerloanspouses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `name` varchar(100) DEFAULT NULL,
  `contactNo` varchar(45) DEFAULT NULL,
  `spouseRelationId` 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_customerloanspouses_customerloans_idx` (`customerLoanId`),
  KEY `fk_customerloanspouses_spouserelations_idx` (`spouseRelationId`),
  CONSTRAINT `fk_customerloanspouses_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloanspouses_spouserelations` FOREIGN KEY (`spouseRelationId`) REFERENCES `spouserelations` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=215 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloanstatushistory`
--



CREATE TABLE `customerloanstatushistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerloanId` int DEFAULT NULL,
  `loanStatusId` int DEFAULT NULL,
  `transactionDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `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_customerloanstatushistory_loanstatus_idx` (`loanStatusId`),
  KEY `fk_customerloanstatushistory_customerloan_idx` (`customerloanId`),
  CONSTRAINT `fk_customerloanstatushistory_customerloan` FOREIGN KEY (`customerloanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_customerloanstatushistory_loanstatus` FOREIGN KEY (`loanStatusId`) REFERENCES `loanstatuses` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1398 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerloantransferpropertydetails`
--



CREATE TABLE `customerloantransferpropertydetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `loanAmountTakenExisting` decimal(15,2) DEFAULT NULL,
  `approxDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `topupAmount` decimal(15,2) DEFAULT NULL,
  `approxCurrentEMI` decimal(15,2) DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=198 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerotherloans`
--



CREATE TABLE `customerotherloans` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `fullName` varchar(256) DEFAULT NULL,
  `birthdate` datetime DEFAULT NULL,
  `panCardNo` varchar(20) DEFAULT NULL,
  `aadhaarCardNo` varchar(20) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `monthlyincome` decimal(15,2) DEFAULT NULL,
  `label` TEXT,
  `addressline1` TEXT,
  `addressline2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `distict` varchar(100) DEFAULT NULL,
  `state` 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,
  `serviceId` int DEFAULT NULL,
  `serviceTypeId` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `userId_idx` (`userId`),
  KEY `employmentTypeId_idx` (`employmentTypeId`),
  KEY `serviceTypeId_idx` (`serviceTypeId`),
  CONSTRAINT `employmentTypeId` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`),
  CONSTRAINT `serviceTypeId` FOREIGN KEY (`serviceTypeId`) REFERENCES `servicetypes` (`id`),
  CONSTRAINT `userId` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customerreferenceaddresses`
--



CREATE TABLE `customerreferenceaddresses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanReferenceId` int DEFAULT NULL,
  `label` TEXT,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `district` varchar(100) DEFAULT NULL,
  `state` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `addressTypeId` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=136 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customers`
--



CREATE TABLE `customers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `temporaryCode` varchar(45) DEFAULT NULL,
  `permanentCode` varchar(45) DEFAULT NULL,
  `fullName` varchar(200) DEFAULT NULL,
  `birthdate` datetime DEFAULT NULL,
  `gender` varchar(15) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `alternativeContactNo` varchar(15) DEFAULT NULL,
  `groupId` int DEFAULT NULL,
  `partnerId` int DEFAULT NULL,
  `panCardNo` varchar(20) DEFAULT NULL,
  `aadhaarCardNo` varchar(20) DEFAULT NULL,
  `maritalStatusId` 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,
  `currentRoleId` int DEFAULT NULL,
  `cibilScore` decimal(15,2) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_customers_users_idx` (`userId`),
  KEY `fk_customers_groups_idx` (`groupId`),
  KEY `fk_customers_partners_idx` (`partnerId`),
  KEY `fk_customers_maritalstatus_idx` (`maritalStatusId`),
  CONSTRAINT `fk_customers_maritalstatus` FOREIGN KEY (`maritalStatusId`) REFERENCES `maritalstatuses` (`id`),
  CONSTRAINT `fk_customers_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_customers_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`),
  CONSTRAINT `fk_customers_usersfk_customers_groups` FOREIGN KEY (`groupId`) REFERENCES `groups` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=288 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `customers_temp`
--



CREATE TABLE `customers_temp` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerId` int DEFAULT NULL,
  `user_tempId` int DEFAULT NULL,
  `fullName` varchar(200) DEFAULT NULL,
  `birthdate` datetime DEFAULT NULL,
  `gender` varchar(15) DEFAULT NULL,
  `contactNo` varchar(15) DEFAULT NULL,
  `alternativeContactNo` varchar(15) DEFAULT NULL,
  `groupId` int DEFAULT NULL,
  `partnerId` int DEFAULT NULL,
  `panCardNo` varchar(20) DEFAULT NULL,
  `aadhaarCardNo` varchar(20) DEFAULT NULL,
  `maritalStatusId` 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,
  `currentRoleId` int DEFAULT NULL,
  `cibilScore` decimal(15,2) 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 `degrees`
--



CREATE TABLE `degrees` (
  `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=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `designations`
--



CREATE TABLE `designations` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `districts`
--



CREATE TABLE `districts` (
  `id` int NOT NULL AUTO_INCREMENT,
  `stateId` int NOT NULL,
  `name` varchar(200) 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_districts_states_idx` (`stateId`),
  CONSTRAINT `fk_districts_states` FOREIGN KEY (`stateId`) REFERENCES `states` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=633 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `documentmasters`
--



CREATE TABLE `documentmasters` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) DEFAULT NULL,
  `maxSize` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `educationtypes`
--



CREATE TABLE `educationtypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `emailtemplates`
--



CREATE TABLE `emailtemplates` (
  `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 `employmentnatures`
--



CREATE TABLE `employmentnatures` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `employmentservicetypes`
--



CREATE TABLE `employmentservicetypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `employmenttypes`
--



CREATE TABLE `employmenttypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) DEFAULT NULL,
  `parentId` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `faqcategories`
--



CREATE TABLE `faqcategories` (
  `id` int NOT NULL AUTO_INCREMENT,
  `categoryName` varchar(200) NOT NULL,
  `displayOrder` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `faqs`
--



CREATE TABLE `faqs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `question` varchar(250) DEFAULT NULL,
  `answer` varchar(250) DEFAULT NULL,
  `isActive` tinyint DEFAULT '1',
  `isDelete` tinyint DEFAULT '0',
  `createdDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `modifiedDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `faqType` int DEFAULT NULL,
  `faqCategoryId` int NOT NULL,
  `createdBy` int DEFAULT NULL,
  `modifiedBy` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `faqType_idx` (`faqType`),
  CONSTRAINT `faqType` FOREIGN KEY (`faqType`) REFERENCES `faqtypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `faqtypes`
--



CREATE TABLE `faqtypes` (
  `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=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `flaggroups`
--



CREATE TABLE `flaggroups` (
  `id` int NOT NULL AUTO_INCREMENT,
  `flagGroupName` varchar(50) DEFAULT NULL,
  `detail` TEXT,
  `parentFlagGroupId` int DEFAULT NULL,
  `displayOrder` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `followupstatuses`
--



CREATE TABLE `followupstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `groups`
--



CREATE TABLE `groups` (
  `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 `industrytypes`
--



CREATE TABLE `industrytypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `parentId` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `itryear`
--



CREATE TABLE `itryear` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leadaddresses`
--



CREATE TABLE `leadaddresses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `leadId` int DEFAULT NULL,
  `addressTypeId` int DEFAULT NULL,
  `label` varchar(45) DEFAULT NULL,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `district` varchar(45) DEFAULT NULL,
  `state` 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_lead_leadaddress_idx` (`addressTypeId`),
  CONSTRAINT `fk_lead_leadaddress` FOREIGN KEY (`addressTypeId`) REFERENCES `addresstypes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=99 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leaddocuments`
--



CREATE TABLE `leaddocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `leadId` int DEFAULT NULL,
  `panCardUrl` TEXT,
  `aadhaarCardUrl` 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`),
  KEY `fk_leaddocuments_leads_idx` (`leadId`),
  CONSTRAINT `fk_leaddocuments_leads` FOREIGN KEY (`leadId`) REFERENCES `leads` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leadfollowupstatuses`
--



CREATE TABLE `leadfollowupstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `leadId` int DEFAULT NULL,
  `followupStatusId` 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_leaddocuments_lead_idx` (`leadId`),
  KEY `fk_leaddocuments_followupstatuses_idx` (`followupStatusId`),
  CONSTRAINT `fk_leaddocuments_followupstatuses` FOREIGN KEY (`followupStatusId`) REFERENCES `followupstatuses` (`id`),
  CONSTRAINT `fk_leaddocuments_lead` FOREIGN KEY (`leadId`) REFERENCES `leads` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leads`
--



CREATE TABLE `leads` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerFullName` varchar(200) DEFAULT NULL,
  `contactNo` varchar(20) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `serviceId` int DEFAULT NULL,
  `loanAmount` decimal(15,3) DEFAULT NULL,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `employmentTypeId` int DEFAULT NULL,
  `panCardNo` varchar(20) DEFAULT NULL,
  `aadhaarCardNo` varchar(20) DEFAULT NULL,
  `monthlyIncome` decimal(15,2) DEFAULT NULL,
  `annualIncome` decimal(15,2) DEFAULT NULL,
  `experience` decimal(15,2) DEFAULT NULL,
  `professionTypeId` int DEFAULT NULL,
  `primaryBankId` int DEFAULT NULL,
  `loanPurpose` TEXT,
  `studiedCountryId` int DEFAULT NULL,
  `degreeId` int DEFAULT NULL,
  `courseId` int DEFAULT NULL,
  `assignedById` int DEFAULT NULL,
  `assignToPartnerId` int DEFAULT NULL,
  `assignOn` datetime 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,
  `leadStatusId` int DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_leads_services_idx` (`serviceId`),
  KEY `fk_leads_employmenttypes_idx` (`employmentTypeId`),
  KEY `fk_leads_banks_idx` (`primaryBankId`),
  KEY `fk_leads_countries_idx` (`studiedCountryId`),
  KEY `fk_leads_users_idx` (`assignedById`),
  KEY `fk_leads_partnerusers_idx` (`assignToPartnerId`),
  KEY `fk_leads_degree_idx` (`degreeId`),
  KEY `fk_leads_courses_idx` (`courseId`),
  KEY `fk_leads_cities_idx` (`cityId`),
  KEY `fk_leads_professiontypes_idx` (`professionTypeId`),
  CONSTRAINT `fk_leads_banks` FOREIGN KEY (`primaryBankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_leads_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_leads_countries` FOREIGN KEY (`studiedCountryId`) REFERENCES `countries` (`id`),
  CONSTRAINT `fk_leads_courses` FOREIGN KEY (`courseId`) REFERENCES `courses` (`id`),
  CONSTRAINT `fk_leads_degree` FOREIGN KEY (`degreeId`) REFERENCES `degrees` (`id`),
  CONSTRAINT `fk_leads_employmenttypes` FOREIGN KEY (`employmentTypeId`) REFERENCES `employmenttypes` (`id`),
  CONSTRAINT `fk_leads_partnerusers` FOREIGN KEY (`assignToPartnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_leads_professiontypes` FOREIGN KEY (`professionTypeId`) REFERENCES `professiontypes` (`id`),
  CONSTRAINT `fk_leads_services` FOREIGN KEY (`serviceId`) REFERENCES `services` (`id`),
  CONSTRAINT `fk_leads_users` FOREIGN KEY (`assignedById`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=211 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leadstatuses`
--



CREATE TABLE `leadstatuses` (
  `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=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `leadstatushistory`
--



CREATE TABLE `leadstatushistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `leadId` int DEFAULT NULL,
  `leadStatusId` int DEFAULT NULL,
  `transactionDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `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_leadstatushistory_leadstatus_idx` (`leadStatusId`),
  KEY `fk_leadstatushistory_leads_idx` (`leadId`),
  CONSTRAINT `fk_leadstatushistory_leads` FOREIGN KEY (`leadId`) REFERENCES `leads` (`id`),
  CONSTRAINT `fk_leadstatushistory_leadstatus` FOREIGN KEY (`leadStatusId`) REFERENCES `leadstatuses` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=251 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `loanagainstcollteral`
--



CREATE TABLE `loanagainstcollteral` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) 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=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `loancompletescreenhistory`
--



CREATE TABLE `loancompletescreenhistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `isCompleted` tinyint DEFAULT NULL,
  `completeScreen` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=369 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `loanstatuses`
--



CREATE TABLE `loanstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status` varchar(45) DEFAULT NULL,
  `isDataEditable` tinyint DEFAULT '1',
  `displayOrder` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `maritalstatuses`
--



CREATE TABLE `maritalstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status` 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=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `newslettersubscription`
--



CREATE TABLE `newslettersubscription` (
  `id` int NOT NULL AUTO_INCREMENT,
  `email` varchar(256) 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=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `nomineerelations`
--



CREATE TABLE `nomineerelations` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `notificationtypes`
--



CREATE TABLE `notificationtypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `isActive` tinyint DEFAULT NULL,
  `isDelete` tinyint DEFAULT NULL,
  `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=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `offers`
--



CREATE TABLE `offers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int NOT NULL,
  `bankId` int DEFAULT NULL,
  `loanAmount` decimal(15,2) DEFAULT NULL,
  `ROI` decimal(20,2) DEFAULT NULL,
  `tenure` int DEFAULT NULL,
  `isShared` tinyint DEFAULT NULL,
  `otherDetail` 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`),
  KEY `offers_bankId_idx` (`bankId`),
  KEY `offers_customerloanId_idx` (`customerLoanId`),
  CONSTRAINT `offers_bankId` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `offers_customerloanId` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=79 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `orderaddresses`
--



CREATE TABLE `orderaddresses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `orderId` int DEFAULT NULL,
  `addressTypeId` int DEFAULT NULL,
  `label` TEXT,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `city` varchar(100) DEFAULT NULL,
  `district` varchar(100) DEFAULT NULL,
  `state` 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`),
  KEY `fk_orderaddresses_orders_idx` (`orderId`),
  KEY `fk_orderaddresses_addresstypes_idx` (`addressTypeId`),
  KEY `fk_orderaddresses_city_idx` (`cityId`),
  CONSTRAINT `fk_orderaddresses_addresstypes` FOREIGN KEY (`addressTypeId`) REFERENCES `addresstypes` (`id`),
  CONSTRAINT `fk_orderaddresses_city` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_orderaddresses_orders` FOREIGN KEY (`orderId`) REFERENCES `orders` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `orders`
--



CREATE TABLE `orders` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `productId` int DEFAULT NULL,
  `quantity` int DEFAULT NULL,
  `unitCoin` decimal(15,3) DEFAULT NULL,
  `totalCoin` decimal(15,3) DEFAULT NULL,
  `transactionDate` datetime DEFAULT NULL,
  `orderStatusId` int DEFAULT NULL,
  `remark` TEXT,
  `isActive` tinyint NOT NULL 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`,`isActive`),
  KEY `fk_orders_products_idx` (`productId`),
  KEY `fk_orders_users_idx` (`userId`),
  KEY `fk_orders_orderstatuses_idx` (`orderStatusId`),
  CONSTRAINT `fk_orders_orderstatuses` FOREIGN KEY (`orderStatusId`) REFERENCES `orderstatuses` (`id`),
  CONSTRAINT `fk_orders_products` FOREIGN KEY (`productId`) REFERENCES `products` (`id`),
  CONSTRAINT `fk_orders_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `orderstatuses`
--



CREATE TABLE `orderstatuses` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status` 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=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `orderstatushistory`
--



CREATE TABLE `orderstatushistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `orderId` int DEFAULT NULL,
  `orderStatusId` int DEFAULT NULL,
  `transactionDate` datetime 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_orderstatushistory_order_idx` (`orderId`),
  KEY `fk_orderstatushistory_orderstatus_idx` (`orderStatusId`),
  CONSTRAINT `fk_orderstatushistory_order` FOREIGN KEY (`orderId`) REFERENCES `orders` (`id`),
  CONSTRAINT `fk_orderstatushistory_orderstatus` FOREIGN KEY (`orderStatusId`) REFERENCES `orderstatuses` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `pages`
--



CREATE TABLE `pages` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `displayName` varchar(100) DEFAULT NULL,
  `url` varchar(100) DEFAULT NULL,
  `parentId` int DEFAULT NULL,
  `icon` varchar(45) DEFAULT NULL,
  `type` varchar(20) DEFAULT NULL,
  `isActive` tinyint DEFAULT NULL,
  `isDelete` tinyint DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=135 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partneraddress`
--



CREATE TABLE `partneraddress` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `addressTypeId` int DEFAULT NULL,
  `label` varchar(45) DEFAULT NULL,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `cityId` 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 `fl_partneraddress_partners_idx` (`partnerId`),
  KEY `fl_partneraddress_addresstypes_idx` (`addressTypeId`),
  KEY `fl_partneraddress_cities_idx` (`cityId`),
  CONSTRAINT `fl_partneraddress_addresstypes` FOREIGN KEY (`addressTypeId`) REFERENCES `addresstypes` (`id`),
  CONSTRAINT `fl_partneraddress_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fl_partneraddress_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=272 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerbadges`
--



CREATE TABLE `partnerbadges` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `badgeId` 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_partnerbadges_partners_idx` (`partnerId`),
  KEY `fk_partnerbadges_badges_idx` (`badgeId`),
  CONSTRAINT `fk_partnerbadges_badges` FOREIGN KEY (`badgeId`) REFERENCES `badges` (`id`),
  CONSTRAINT `fk_partnerbadges_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=264 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerbankdetails`
--



CREATE TABLE `partnerbankdetails` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `bankId` int DEFAULT NULL,
  `accountHolderName` TEXT,
  `accountNo` varchar(50) DEFAULT NULL,
  `ifscCode` 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_partnerbankdetails_banks_idx` (`bankId`),
  KEY `fk_partnerbankdetails_partners_idx` (`partnerId`),
  CONSTRAINT `fk_partnerbankdetails_banks` FOREIGN KEY (`bankId`) REFERENCES `banks` (`id`),
  CONSTRAINT `fk_partnerbankdetails_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnercommission`
--



CREATE TABLE `partnercommission` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `commission` 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_partnercommission_partner_idx` (`partnerId`),
  CONSTRAINT `fk_partnercommission_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnercommissionhistory`
--



CREATE TABLE `partnercommissionhistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerCommissionId` int DEFAULT NULL,
  `partnerId` int DEFAULT NULL,
  `loanDetailId` int DEFAULT NULL,
  `commission` decimal(15,3) DEFAULT NULL,
  `type` 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,
  `isReleased` tinyint DEFAULT '0',
  `releaseDate` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_partnercommissionhistory_partnercommission_idx` (`partnerCommissionId`),
  KEY `fk_partnercommissionhistory_user_idx` (`partnerId`),
  KEY `fk_partnercommissionhistory_loanDetail_idx` (`loanDetailId`),
  CONSTRAINT `fk_partnercommissionhistory_loanDetail` FOREIGN KEY (`loanDetailId`) REFERENCES `customerloandetail` (`id`),
  CONSTRAINT `fk_partnercommissionhistory_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_partnercommissionhistory_partnercommission` FOREIGN KEY (`partnerCommissionId`) REFERENCES `partnercommission` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=155 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnercustomercreditcards`
--



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











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












--
-- Table structure for table `partnercustomers`
--



CREATE TABLE `partnercustomers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `customerId` 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_partnercustomers_partner_idx` (`partnerId`),
  KEY `fk_partnercustomers_customer_idx` (`customerId`),
  CONSTRAINT `fk_partnercustomers_customer` FOREIGN KEY (`customerId`) REFERENCES `customers` (`id`),
  CONSTRAINT `fk_partnercustomers_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=70 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerdocuments`
--



CREATE TABLE `partnerdocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `documentId` int DEFAULT NULL,
  `url` 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`),
  KEY `fk_partnerdocument_partner_idx` (`partnerId`),
  KEY `fk_partnerdocument_document_idx` (`documentId`),
  CONSTRAINT `fk_partnerdocument_document` FOREIGN KEY (`documentId`) REFERENCES `documentmasters` (`id`),
  CONSTRAINT `fk_partnerdocument_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnereducations`
--



CREATE TABLE `partnereducations` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `educationTypeId` int DEFAULT NULL,
  `resume` TEXT,
  `instituteName` TEXT,
  `passingYear` int DEFAULT NULL,
  `otherDetail` 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`),
  KEY `fk_partnereducations_partners_idx` (`partnerId`),
  KEY `fk_partnereducations_educationtypes_idx` (`educationTypeId`),
  CONSTRAINT `fk_partnereducations_educationtypes` FOREIGN KEY (`educationTypeId`) REFERENCES `educationtypes` (`id`),
  CONSTRAINT `fk_partnereducations_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=271 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerinvoice`
--



CREATE TABLE `partnerinvoice` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `url` TEXT NOT NULL,
  `loanDetailId` int NOT NULL,
  `partnerCommissionHistoryId` int DEFAULT NULL,
  `invoiceNumber` 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 `partnerinvoice.partnerId_idx` (`partnerId`),
  KEY `partnerInvocie_loandetailId_idx` (`loanDetailId`),
  KEY `partnerinvocie_partnercommissionhistory_idx` (`partnerCommissionHistoryId`),
  CONSTRAINT `partnerInvocie_loandetailId` FOREIGN KEY (`loanDetailId`) REFERENCES `customerloandetail` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `partnerinvocie_partnercommissionhistory` FOREIGN KEY (`partnerCommissionHistoryId`) REFERENCES `partnercommissionhistory` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
  CONSTRAINT `partnerinvoice.partnerId` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnernetworks`
--



CREATE TABLE `partnernetworks` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `networkPartnerId` 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_partnernetworks_partners_idx` (`partnerId`),
  KEY `fk_partnernetworks_networkpartners_idx` (`networkPartnerId`),
  CONSTRAINT `fk_partnernetworks_networkpartners` FOREIGN KEY (`networkPartnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_partnernetworks_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=128 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerpayouts`
--



CREATE TABLE `partnerpayouts` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `payoutAmount` decimal(13,3) DEFAULT NULL,
  `month` varchar(45) DEFAULT NULL,
  `fromDate` datetime DEFAULT NULL,
  `toDate` datetime DEFAULT NULL,
  `releasedAt` datetime 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_partnerpayouts_partners_idx` (`partnerId`),
  CONSTRAINT `fk_partnerpayouts_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partners`
--



CREATE TABLE `partners` (
  `id` int NOT NULL AUTO_INCREMENT,
  `parentPartnerId` int DEFAULT NULL,
  `userId` int DEFAULT NULL,
  `temporaryCode` varchar(45) DEFAULT NULL,
  `permanentCode` varchar(45) DEFAULT NULL,
  `fullName` varchar(200) DEFAULT NULL,
  `gender` varchar(20) DEFAULT NULL,
  `contactNo` varchar(45) DEFAULT NULL,
  `aadhaarCardNo` varchar(20) DEFAULT NULL,
  `panCardNo` varchar(20) DEFAULT NULL,
  `cityId` int DEFAULT NULL,
  `companyName` varchar(100) DEFAULT NULL,
  `companyTypeId` int DEFAULT NULL,
  `udhyamAadhaarNo` varchar(45) DEFAULT NULL,
  `companyRegNo` varchar(45) DEFAULT NULL,
  `professionTypeId` int DEFAULT NULL,
  `workExperience` decimal(5,2) DEFAULT NULL,
  `haveOffice` tinyint DEFAULT '0',
  `businessName` varchar(100) DEFAULT NULL,
  `gstNo` varchar(20) DEFAULT NULL,
  `commitment` decimal(13,3) DEFAULT NULL,
  `designationId` int DEFAULT NULL,
  `referralCode` varchar(45) DEFAULT NULL,
  `currentBadgeId` int DEFAULT NULL,
  `businessAddress` varchar(45) DEFAULT NULL,
  `addressLine1` TEXT,
  `addressLine2` TEXT,
  `pincode` varchar(10) DEFAULT NULL,
  `workAddressCityId` int DEFAULT NULL,
  `jobType` 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_partners_users_idx` (`userId`),
  KEY `fk_partners_cities_idx` (`cityId`),
  KEY `fk_partners_professiontypes_idx` (`professionTypeId`),
  KEY `fk_partners_designation_idx` (`designationId`),
  CONSTRAINT `fk_partners_cities` FOREIGN KEY (`cityId`) REFERENCES `cities` (`id`),
  CONSTRAINT `fk_partners_designation` FOREIGN KEY (`designationId`) REFERENCES `designations` (`id`),
  CONSTRAINT `fk_partners_professiontypes` FOREIGN KEY (`professionTypeId`) REFERENCES `professiontypes` (`id`),
  CONSTRAINT `fk_partners_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=278 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerscustomerloans`
--



CREATE TABLE `partnerscustomerloans` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int DEFAULT NULL,
  `partnerId` int DEFAULT NULL,
  `transactionDate` datetime DEFAULT CURRENT_TIMESTAMP,
  `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_partnerscustomerloans_customerloans_idx` (`customerLoanId`),
  KEY `fk_partnerscustomerloans_partners_idx` (`partnerId`),
  CONSTRAINT `fk_partnerscustomerloans_customerloans` FOREIGN KEY (`customerLoanId`) REFERENCES `customerloans` (`id`),
  CONSTRAINT `fk_partnerscustomerloans_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=174 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnerteams`
--



CREATE TABLE `partnerteams` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `teamPartnerId` 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_partnerteams_partner_idx` (`partnerId`),
  KEY `fk_partnerteams_teampartner_idx` (`teamPartnerId`),
  CONSTRAINT `fk_partnerteams_partner` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_partnerteams_teampartner` FOREIGN KEY (`teamPartnerId`) REFERENCES `partners` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnertrainings`
--



CREATE TABLE `partnertrainings` (
  `id` int NOT NULL AUTO_INCREMENT,
  `trainingId` int DEFAULT NULL,
  `partnerId` int DEFAULT NULL,
  `isCompleted` tinyint DEFAULT '0',
  `completedDate` datetime DEFAULT NULL,
  `assignedBy` 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_partnertrainings_trainings_idx` (`trainingId`),
  KEY `fk_partnertrainings_partners_idx` (`partnerId`),
  CONSTRAINT `fk_partnertrainings_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_partnertrainings_trainings` FOREIGN KEY (`trainingId`) REFERENCES `trainings` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `partnervisitingcards`
--



CREATE TABLE `partnervisitingcards` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `visitingCardId` int DEFAULT NULL,
  `template` TEXT,
  `location` varchar(100) DEFAULT NULL,
  `dynamicFields` 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`),
  KEY `fk_partnervisitingcards_partners_idx` (`partnerId`),
  KEY `fk_partnervisitingcards_visitingcards_idx` (`visitingCardId`),
  CONSTRAINT `fk_partnervisitingcards_partners` FOREIGN KEY (`partnerId`) REFERENCES `partners` (`id`),
  CONSTRAINT `fk_partnervisitingcards_visitingcards` FOREIGN KEY (`visitingCardId`) REFERENCES `visitingcards` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `permissiongroup`
--



CREATE TABLE `permissiongroup` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` 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=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `permissiongrouppages`
--



CREATE TABLE `permissiongrouppages` (
  `id` int NOT NULL AUTO_INCREMENT,
  `permissionGroupId` 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_permissiongrouppages_permissiongroup_idx` (`permissionGroupId`),
  KEY `fk_permissiongrouppages_page_idx` (`pageId`),
  CONSTRAINT `fk_permissiongrouppages_page` FOREIGN KEY (`pageId`) REFERENCES `pages` (`id`),
  CONSTRAINT `fk_permissiongrouppages_permissiongroup` FOREIGN KEY (`permissionGroupId`) REFERENCES `permissiongroup` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=28 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `products`
--



CREATE TABLE `products` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(200) DEFAULT NULL,
  `description` TEXT,
  `imageUrl` TEXT,
  `coin` decimal(15,3) DEFAULT NULL,
  `duration` 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=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `professiontypes`
--



CREATE TABLE `professiontypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `propertydocuments`
--



CREATE TABLE `propertydocuments` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  `isRequired` 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`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `propertytypes`
--



CREATE TABLE `propertytypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=10 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `reasons`
--



CREATE TABLE `reasons` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerloanId` int DEFAULT NULL,
  `customerCreditCardId` int DEFAULT NULL,
  `reason` varchar(200) 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=34 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `referlinks`
--



CREATE TABLE `referlinks` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `roleId` int DEFAULT NULL,
  `linkKey` TEXT,
  `referCount` 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_referlinks_users_idx` (`userId`),
  KEY `fk_referlinks_roles_idx` (`roleId`),
  CONSTRAINT `fk_referlinks_roles` FOREIGN KEY (`roleId`) REFERENCES `roles` (`id`),
  CONSTRAINT `fk_referlinks_users` FOREIGN KEY (`userId`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `referpartner`
--



CREATE TABLE `referpartner` (
  `id` int NOT NULL AUTO_INCREMENT,
  `partnerId` int DEFAULT NULL,
  `referPartnerId` int DEFAULT NULL,
  `isRewarded` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `referusers`
--



CREATE TABLE `referusers` (
  `id` int NOT NULL AUTO_INCREMENT,
  `userId` int DEFAULT NULL,
  `referUserId` 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`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `residenttypes`
--



CREATE TABLE `residenttypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `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=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `rewardcoin`
--



CREATE TABLE `rewardcoin` (
  `id` int NOT NULL AUTO_INCREMENT,
  `rewardTypeId` int DEFAULT NULL,
  `rewardCoin` decimal(15,3) DEFAULT NULL,
  `minLoanFile` int DEFAULT NULL,
  `maxLoanFile` int DEFAULT NULL,
  `roleIds` varchar(100) DEFAULT NULL,
  `isScratchCard` 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 `rewardcoin_roleId_idx` (`roleIds`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `rewardtypes`
--



CREATE TABLE `rewardtypes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` 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=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Table structure for table `rmassignhistory`
--



CREATE TABLE `rmassignhistory` (
  `id` int NOT NULL AUTO_INCREMENT,
  `customerLoanId` int NOT NULL,
  `assignRMId` int NOT NULL,
  `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 `roles`
--



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











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












--
-- Table structure for table `rolesvisitingcards`
--



CREATE TABLE `rolesvisitingcards` (
  `id` int NOT NULL AUTO_INCREMENT,
  `visitingCardId` 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=354 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;











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












--
-- Dumping routines for database 'rupiloans'
--









DELIMITER $$
CREATE  PROCEDURE `adminAcceptOffer`(IN _id INT,IN _isAccept BOOLEAN,IN _userId INT,IN _status VARCHAR(200),IN _customerLoanId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	IF _isAccept THEN
		UPDATE customerloandetail SET isAccept = true,status = _status ,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	IF _status = 'SANCTIONED' THEN
		 BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerLoanId = _customerLoanId AND loanStatusId = 7;
			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,7,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE customerloans SET statusId = 7 WHERE id = _customerLoanId;
		END IF;	
    END IF;
        
    ELSE
		UPDATE customerloandetail SET isAccept = false,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _id;
	END If;
    
END$$
DELIMITER ;













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













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













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













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













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













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













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













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













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













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













DELIMITER $$
CREATE  PROCEDURE `adminActiveInactiveDocumentMaster`(IN _id INT, IN _isActive Boolean, IN _userId INT)
BEGIN
	UPDATE documentmasters SET isActive = _isActive, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
END$$
DELIMITER ;













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













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













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













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













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













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













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













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













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













DELIMITER $$
CREATE  PROCEDURE `adminActiveInactiveService`(IN _serviceId INT, IN _userId INT, IN _isActive BOOLEAN)
BEGIN
	UPDATE services SET isActive = _isActive, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminActiveInactiveServiceEmploymentType`(IN _id INT,IN _serviceId INT,IN _userId INT)
BEGIN
	IF _serviceId > 0 THEN
		UPDATE servicesemploymenttypes SET isActive = !isActive,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE serviceId = _serviceId;
	ELSE 
		UPDATE servicesemploymenttypes SET isActive = !isActive,modifiedBy = _userId,modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
   END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminActiveInactiveServiceTypeDocuments`(IN _id INT, IN _IsActive BOOLEAN, IN _userId INT)
BEGIN
	UPDATE servicetypedocuments SET isActive = _isActive, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminActiveInactiveServiceTypes`(IN _serviceTypeId INT, IN _userId INT, IN _isActive BOOLEAN)
BEGIN
	UPDATE servicetypes SET isActive = _isActive, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _serviceTypeId;
END$$
DELIMITER ;













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













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













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













DELIMITER $$
CREATE  PROCEDURE `adminAssignRoleToCustomer`(IN _customerId INT,IN _userId INT,IN _roleId INT,IN _partnerCode VARCHAR(200),IN _currentUserId INT,IN _temporaryCode VARCHAR(200),IN _permanentCode VARCHAR(100),IN _fullName TEXT,IN _gender VARCHAR(100),IN _contactNo VARCHAR(15),IN _aadharCardNo VARCHAR(20),IN _panCardNo VARCHAR(20),IN _cityId INT,IN _commitment DECIMAL(13,3),IN _addressLine1 TEXT,IN _addressLine2 TEXT,IN _pincode TEXT,IN _jobType VARCHAR(45))
BEGIN

    DECLARE _parentPartnerId INT DEFAULT 0;
	DECLARE _parentUserId INT DEFAULT 0;
	DECLARE _partnerId INT DEFAULT 0;
    DECLARE finished INT DEFAULT 0;
    
	INSERT INTO userroles (userId,roleId,createdBy,modifiedBy) VALUES (_userId,_roleId,_currentUserId,_currentUserId);
	UPDATE users SET currentRoleId = _roleId WHERE id = _userId;
    
    IF(_partnerCode != '') THEN
    	BEGIN
			DECLARE cur_checkexist cursor for select id,userId FROM partners WHERE permanentCode = _partnerCode;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
         
				getParentPartner: LOOP
					FETCH cur_checkexist INTO _parentPartnerId,_parentUserId;
					IF finished = 1 THEN 
						LEAVE getParentPartner;
					END IF;
				END LOOP;
		    CLOSE cur_checkexist;
		END;
		INSERT INTO partners (parentPartnerId,userId,temporaryCode,permanentCode,fullName,gender,contactNo,aadhaarCardNo,panCardNo,cityId,commitment,currentBadgeId,jobType,createdBy,modifiedBy) VALUES (_parentPartnerId,_userId,_temporaryCode,_permanentCode,_fullName,_gender,_contactNo,_aadharCardNo,_panCardNo,_cityId,_commitment,1,_jobType,_currentUserId,_currentUserId);
		SET @partnerId = LAST_INSERT_ID();
	
        IF _roleId = 5 THEN
			INSERT INTO partnerteams (partnerId,teamPartnerId) VALUES (_parentPartnerId,@partnerId);
		END IF;
		IF (_roleId = 4 || _roleId = 6) THEN
			INSERT INTO partnernetworks (partnerId,networkPartnerId) VALUES (_parentPartnerId,@partnerId);
        END IF;
    ELSE 
		INSERT INTO partners (userId,temporaryCode,permanentCode,fullName,gender,contactNo,aadhaarCardNo,panCardNo,cityId,commitment,currentBadgeId,jobType,createdBy,modifiedBy) VALUES (_userId,_temporaryCode,_permanentCode,_fullName,_gender,_contactNo,_aadharCardNo,_panCardNo,_cityId,_commitment,1,_jobType,_currentUserId,_currentUserId);
		SET @partnerId = LAST_INSERT_ID();
   END IF;
		UPDATE users SET isDisabled = false,contactNo = _contactNo,fullName = _fullName,gender = _gender  WHERE id = _userId;
        UPDATE customers SET contactNo = _contactNo,fullName = _fullName,gender = _gender,panCardNo = _panCardNo,aadhaarCardNo = _aadharCardNo,currentRoleId = _roleId WHERE id = _customerId;
    	INSERT INTO partnerbadges (partnerId,badgeId,createdBy,modifiedBy) VALUES (@partnerId,1,_currentUserId,_currentUserId);
        INSERT INTO partneraddress (partnerId,addressTypeId,addressLine1,addressLine2,pincode,cityId,createdBy,modifiedBy) VALUES (@partnerId,1,_addressLine1,_addressLine2,_pincode,_cityId,_currentUserId,_currentUserId);
		INSERT INTO partnerscustomerloans (customerLoanId,partnerId,transactionDate,createdBy,modifiedBy) SELECT id,@partnerId,createdDate,createdBy,modifiedBy FROM customerloans WHERE customerId = _customerId;
		DELETE FROM becomeapartnerrequest WHERE customerId = _customerId;
        
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminAssignToRm`(IN _userId INT,IN _customerLoanId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	UPDATE customerloans SET assignRMId = _userId WHERE id = _customerLoanId;
	BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 2;
			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,2,CURRENT_TIMESTAMP(),_userId,_userId);
            UPDATE customerloans SET statusId = 2 WHERE id = _customerLoanId;
		ELSE 
			UPDATE customerloanstatushistory SET loanStatusId = 2,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE customerloanId = _customerLoanId AND loanStatusId = 2;
        END IF;
        
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminBlockUnBlockUser`(IN _id INT,IN _userId INT)
BEGIN
	UPDATE users SET isBlocked = !isBlocked,modifiedDate = current_timestamp(),modifiedBy = _userId WHERE id = _id; 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminChangeCustomerLoanDocumentStatus`(IN _id VARCHAR(200),IN _status VARCHAR(200),IN _userId INT,IN _allApproved BOOLEAN,IN _customerLoanId INT)
BEGIN
	DECLARE front TEXT;
    DECLARE documentStatus TEXT DEFAULT NULL;
    DECLARE frontlen INT;
    DECLARE TempValue TEXT;
	DECLARE StatusValue TEXT DEFAULT NULL;
    DECLARE statuslen TEXT DEFAULT NULL;
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
  	iterator:
	LOOP  
    IF LENGTH(TRIM(_id)) = 0 OR _id IS NULL THEN
    LEAVE iterator;
    END IF;
    SET front = SUBSTRING_INDEX(_id,',',1);
    SET documentStatus = SUBSTRING_INDEX(_status,',',1);
    SET frontlen = LENGTH(front);
    SET statuslen = LENGTH(documentStatus);
	SET TempValue = TRIM(front);
    SET StatusValue = TRIM(documentStatus);
    UPDATE customerloandocuments SET documentStatus = StatusValue,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = TempValue;
	SET _id = INSERT(_id,1,frontlen + 1,'');
    SET _status = INSERT(_status,1,statuslen + 1,'');
    END LOOP;
    IF (_allApproved) THEN
		 BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 11;
			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,11,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE customerloans SET statusId = 11 WHERE id = _customerLoanId;
		ELSE 
			UPDATE customerloanstatushistory SET loanStatusId = 11,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE customerloanId = _customerLoanId AND loanStatusId = 11;
        END IF;	
    ELSE 
		 BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 23;
			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,23,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE customerloans SET statusId = 23 WHERE id = _customerLoanId;
		ELSE 
			UPDATE customerloanstatushistory SET loanStatusId = 23,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE customerloanId = _customerLoanId AND loanStatusId = 23;
			UPDATE customerloans SET statusId = 23 WHERE id = _customerLoanId;
       END IF;
	END IF;
    SELECT customerloans.statusId,loanstatuses.status FROM customerloans INNER JOIN loanstatuses ON customerloans.statusId = loanstatuses.id WHERE customerloans.id = _customerLoanId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminChangeLeadStatus`(IN _leadId INT,IN _statusId INT,IN _userId 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 = _statusId;
			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,_statusId,CURRENT_TIMESTAMP(),_userId,_userId);
		END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminChangeLoanStatus`(IN _customerLoanId INT,IN _loanStatusId INT,IN  _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = _loanStatusId;
			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,_loanStatusId,CURRENT_TIMESTAMP(),_userId,_userId);
			UPDATE customerloans SET statusId = _loanStatusId WHERE id = _customerLoanId;
		
        ELSE 
			UPDATE customerloans SET statusId = _loanStatusId WHERE id = _customerLoanId;
		END IF;
        SELECT customerloans.*,loanstatuses.status FROM customerloans INNER JOIN loanstatuses ON customerloans.statusId = loanstatuses.id WHERE customerloans.id = _customerLoanId;
	END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminChangeOrderStatus`(IN _orderId INT,IN _statusId INT,IN _userId INT,IN _remark TEXT)
BEGIN
	DECLARE updateQuery TEXT DEFAULT '';
    SET @updateQuery = '';
    
	SET @updateQuery = CONCAT_WS(''," UPDATE orders SET orderStatusId = ",_statusId,",modifiedBy = ",_userId,",modifiedDate = '",CURRENT_TIMESTAMP(),"'");
    IF _remark != '' THEN
		SET @updateQuery = CONCAT_WS('',@updateQuery," ,remark = '",_remark,"'");
	END IF;
    SET @updateQuery = CONCAT_WS('',@updateQuery," WHERE id = ",_orderId);
    PREPARE stmt FROM @updateQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    INSERT INTO orderstatushistory (orderId,orderStatusId,transactionDate,createdBy,modifiedBy) VALUES (_orderId,_statusId,CURRENT_TIMESTAMP(),_userId,_userId); 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminCheckContactNoExist`(IN _contactNo VARCHAR(20),IN _roleId INT,IN _userId INT)
BEGIN
	IF(_userId) THEN
	SELECT users.id 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 IN(_roleId) AND users.id != _userId ;
    ELSE
	SELECT users.id 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 IN(_roleId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminCheckServiceImage`(IN _serviceId INT)
BEGIN
	SELECT * FROM services WHERE id = _serviceId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminCheckServiceTypeImage`(IN _serviceTypeId INT)
BEGIN
	SELECT * FROM servicetypes WHERE id = _serviceTypeId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminConvertLeadIntoLoan`(IN _leadId INT, IN _customerId INT,IN _serviceId INT, IN _loanAmount decimal(15,3),IN _employmentTypeId INT, IN _userId INT,IN _assignPartnerId INT,IN _contactNo VARCHAR(20),IN _customerFullName VARCHAR(200),IN _countryCode VARCHAR(20),IN _temporaryCode VARCHAR(50),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 _aadharCardNo VARCHAR(20),IN _panCardNo VARCHAR(20))
BEGIN
	DECLARE finished INT DEFAULT 0;
	DECLARE cUserId INT DEFAULT 0;
	DECLARE cRoleId INT DEFAULT 0;
    DECLARE customerLoanId INT DEFAULT 0;
	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, isDisabled, createdBy, modifiedBy,currentRoleId) VALUES(_customerFullName, _countryCode, _contactNo, 0, _userId, _userId,2);
			SET @userId = LAST_INSERT_ID();
			INSERT INTO userroles (userId,roleId,createdBy,modifiedBy) VALUES (@userId,2,_userId,_userId);
			INSERT INTO customers(userId, temporaryCode, fullName, contactNo,aadhaarCardNo,panCardNo, createdBy, modifiedBy,currentRoleId) VALUES(@userId, _temporaryCode, _customerFullName, _contactNo,_aadharCardNo,_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); SET @customerAddressId = LAST_INSERT_ID();
       		END IF;
        END;
			INSERT INTO customerloans(leadId,serviceId,loanAmount,customerId,employmentTypeId,statusId,createdBy,modifiedBy) VALUES (_leadId,_serviceId,_loanAmount,_customerId,_employmentTypeId,1,_userId,_userId);
			SET @customerLoanId =  LAST_INSERT_ID();
            UPDATE leads SET leadStatusId = 5,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE id = _leadId;
            INSERT INTO leadstatushistory(leadId,leadStatusId,transactionDate,createdBy,modifiedBy) VALUES (_leadId,5,CURRENT_TIMESTAMP(),_userId,_userId);
            INSERT INTO customerloanstatushistory(customerLoanId,loanStatusId,transactionDate,createdBy,modifiedBy) VALUES (@customerLoanId,1,CURRENT_TIMESTAMP(),_userId,_userId);
            INSERT INTO partnerscustomerloans (customerLoanId,partnerId,createdBy,modifiedBy) VALUES (@customerLoanId,_assignPartnerId,_userId,_userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminDisabledPartner`(IN _id INT,IN _userId INT,IN _permanentCode VARCHAR(20))
BEGIN
	IF _permanentCode !='' THEN
		UPDATE partners SET permanentCode = _permanentCode,isActive = !isActive WHERE id = _id;
    ELSE 
		UPDATE partners SET isActive = !isActive WHERE id = _id;
    END IF;
	UPDATE users SET isDisabled = !isDisabled WHERE id = _userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGenerateOfferForCustomerLoan`(IN _employmentTypeId INT,IN _serviceId INT,IN _userId INT,IN _age INT,IN _loanAmount INT,IN _companyCategoryTypeId VARCHAR(200),IN _cibilScore DECIMAL(15,2),IN _turnOver DECIMAL(15,2),IN _minIncome INT,IN _vintage INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	DECLARE sqlQuery TEXT DEFAULT "";
	DECLARE finalSqlQuery TEXT DEFAULT "";
    DECLARE parentTypeId INT DEFAULT 0;
    DECLARE parentEmploymentTypeId INT DEFAULT 0;
	SET @sqlQuery = "";
	BEGIN
			DECLARE cur_checkexist CURSOR FOR SELECT parentId FROM employmenttypes WHERE id = _employmentTypeId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @parentTypeId =0;
				getParentId: LOOP
					FETCH cur_checkexist INTO parentEmploymentTypeId;
					IF finished = 1 THEN 
						LEAVE getParentId;
					END IF;
					IF parentEmploymentTypeId > 0 THEN
						SET @parentTypeId = parentEmploymentTypeId;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
    SET @sqlQuery = CONCAT_WS(''," SELECT blp.*,banks.name as bankName,services.displayName as serviceName,banks.minAge,banks.maxAge FROM bankloanpolicies blp LEFT JOIN banks ON blp.bankId = banks.id LEFT JOIN services ON services.id = blp.serviceId  WHERE blp.isActive = 1 AND blp.isDelete = 0 AND blp.serviceId = ",_serviceId, "");
   IF _employmentTypeId > 0 THEN 
		SET @sqlQuery = CONCAT_WS('',@sqlQuery," AND (blp.employmentTypeId = ",_employmentTypeId," OR blp.employmentTypeId = ",@parentTypeId,")");
   END IF;
   IF _age > 0 THEN
		SET @sqlQuery = CONCAT_WS('',@sqlQuery," AND banks.minAge <=", _age," AND banks.maxAge >= ",_age,"");
	END IF;
	IF _loanAmount > 0 THEN
		SET @sqlQuery = CONCAT_WS('',@sqlQuery," AND blp.minLoanAmount <= ",_loanAmount," AND blp.maxLoanAmount >= ",_loanAmount,"");
	END IF;
   
  /* IF _cibilScore > 0 THEN
		SET @sqlQuery = CONCAT_WS('',@sqlQuery," AND blp.cibilScore >=", _cibilScore,"");
	END IF;*/
  	IF _turnOver > 0 THEN
			SET @sqlQuery = CONCAT_WS('',@sqlQuery," AND blp.minTurnOver <= ",_turnOver," AND blp.maxTurnOver >= ",_turnOver,"");
	END IF;
	
     IF _vintage > 0  THEN 
		SET @sqlQuery = CONCAT_WS('',@sqlQuery,"  AND blp.vintage = ",_vintage);
	END IF;
     SET @finalSqlQuery = "";
    SET @finalSqlQuery = CONCAT_WS('',@sqlQuery);
    
    PREPARE stmt FROM @finalSqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
   
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetAddressTypes`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(addresstypes.id) as totalCount FROM addresstypes 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 addresstypes WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetAdminRoles`()
BEGIN
	SELECT * FROM roles WHERE name IN('ADMINISTRATOR','RELATION MANAGER'); 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBadges`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(badges.id) as totalCount FROM badges 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 badges WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBankCreditCardPolicy`(IN _startIndex INT, IN _fetchRecords INT,IN _bankId INT,IN _companyCategoryTypeId INT,IN _minAge INT,IN _maxAge INT,IN _minCibilScore INT,IN _employmentTypeId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE SqlWhereQuery TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SET @SqlWhereQuery = '';
	IF _bankId > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS(''," AND bankcreditcard.bankId = ",_bankId,"");
    END IF;
    IF _companyCategoryTypeId > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',@SqlWhereQuery," AND bankcreditcardpolicies.companyCategoryTypeId = ",_companyCategoryTypeId,"");
    END IF;
    IF _minAge > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',@SqlWhereQuery," AND bankcreditcardpolicies.minAge >= ",_minAge,"");
    END IF;
    IF _maxAge > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',@SqlWhereQuery," AND bankcreditcardpolicies.maxAge <= ",_maxAge,"");
    END IF;
    IF _minCibilScore > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',@SqlWhereQuery," AND bankcreditcardpolicies.minimumCibilScore = ",_minCibilScore,"");
    END IF;
	IF _employmentTypeId > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',@SqlWhereQuery," AND bankcreditcardpolicies.employmentTypeId = ",_employmentTypeId,"");
    END IF;
    
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(bankcreditcardpolicies.id) as totalCount FROM bankcreditcardpolicies
    INNER JOIN bankcreditcard ON bankcreditcardpolicies.bankCreditCardId = bankcreditcard.id 
    LEFT JOIN companycategorytype ON companycategorytype.id = bankcreditcardpolicies.companyCategoryTypeId
    LEFT JOIN banks ON bankcreditcard.bankId = banks.id
    LEFT JOIN employmenttypes ON employmenttypes.id = bankcreditcardpolicies.employmentTypeId
    WHERE bankcreditcardpolicies.isDelete = 0",@SqlWhereQuery);
    IF _startIndex >= 0 AND _fetchRecords>0 THEN
            SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @SqlQuery = "";
    SET @SqlQuery = CONCAT_WS('', "SELECT bankcreditcardpolicies.*,employmenttypes.name as employmentType,companycategorytype.name as companyCategoryType,bankcreditcard.bankId,banks.name as bankName,bankcreditcard.creditcardName
    FROM bankcreditcardpolicies INNER JOIN bankcreditcard ON bankcreditcardpolicies.bankCreditCardId = bankcreditcard.id 
    LEFT JOIN companycategorytype ON companycategorytype.id = bankcreditcardpolicies.companyCategoryTypeId
    LEFT JOIN banks ON bankcreditcard.bankId = banks.id
    LEFT JOIN employmenttypes ON employmenttypes.id = bankcreditcardpolicies.employmentTypeId
    WHERE bankcreditcardpolicies.isDelete = 0",@SqlWhereQuery," ORDER BY bankcreditcardpolicies.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 `adminGetBankLoan`(IN _startIndex INT,IN _fetchRecords INT,IN _bankIds VARCHAR(100), IN _serviceIds VARCHAR(100))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE FilterBankQuery TEXT DEFAULT "";
    DECLARE FilterServiceQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE StartIndexQuery TEXT DEFAULT "";
    SET @FilterBankQuery = "";
	IF _bankIds !="" THEN 
		SET @FilterBankQuery = CONCAT_WS(''," AND bankloans.bankId IN (",_bankIds,")");        
	END IF;
	SET @FilterServiceQuery = "";
	IF _serviceIds !="" THEN 
		SET @FilterServiceQuery = CONCAT_WS(''," AND bankloans.serviceId IN (",_serviceIds,")");        
	END IF;
    SET @SqlQueryCount = "";
	SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(bankloans.id) as totalCount FROM bankloans INNER JOIN banks ON bankloans.bankId = banks.id INNER JOIN services ON bankloans.serviceId = services.id WHERE bankloans.isDelete = 0",@FilterBankQuery,@FilterServiceQuery);
    SET @StartIndexQuery = "";
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    IF _startIndex >= 0 AND _fetchRecords >0 THEN 
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS(''," SELECT bankloans.*,banks.name as bankName,services.displayName as serviceName FROM bankloans INNER JOIN banks ON bankloans.bankId = banks.id INNER JOIN services ON bankloans.serviceId = services.id WHERE bankloans.isDelete = 0",@FilterBankQuery,@FilterServiceQuery," ORDER BY bankloans.id DESC",@StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBankLoanCommission`(IN _bankId TEXT, IN _serviceId TEXT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SET @sql = "";
    SET @sqlCountQuery = "";
    SET @filterquery = "";
    SET @bankFilterQuery = "";
    IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
	SET @sql = "SELECT bankloancommissions.*, banks.name as bankName, services.name as serviceName FROM bankloancommissions
				INNER JOIN banks ON banks.id = bankloancommissions.bankId
				INNER JOIN services ON services.id = bankloancommissions.serviceId
				WHERE bankloancommissions.id";
	SET @bankFilterQuery = "";
    IF _bankId != "" THEN
		SET @bankFilterQuery = CONCAT_WS(' '," AND bankloancommissions.bankId IN(",_bankId,")");
    END IF;
    
    IF _serviceId != "" THEN
		SET @filterquery = CONCAT_WS(' '," AND bankloancommissions.serviceId IN(",_serviceId,")");
    END IF;
    SET @sqlCountQuery = "";
    SET @sqlCountQuery = CONCAT_WS(''," SELECT COUNT(bankloancommissions.id) as totalCount FROM bankloancommissions 
				INNER JOIN banks ON banks.id = bankloancommissions.bankId
				INNER JOIN services ON services.id = bankloancommissions.serviceId
				WHERE bankloancommissions.id",@bankFilterQuery,@filterQuery);
  
    /*IF _commissionTypeId != "" THEN
		SET @sql = CONCAT_WS(' ',@sql," AND bankloancommissions.commissionTypeId IN(",_commissionTypeId,")");
    END IF;*/
	PREPARE countStmt FROM @sqlCountQuery;
	EXECUTE countStmt;
	DEALLOCATE PREPARE countStmt;
    SET @sql = CONCAT_WS(' ',@sql,@bankFilterQuery, @filterQuery,@StartIndexQuery);
    
    
    PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBankLoanPartnerCommission`(IN _role VARCHAR(40),IN _bankId INT,IN _serviceId INT,IN _commissionTypeId INT,IN _partnerId INT,IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	DECLARE filterRoleQuery TEXT DEFAULT "";
    DECLARE filterCommissionTypeQuery TEXT DEFAULT "";
	DECLARE filterBankQuery TEXT DEFAULT "";
	DECLARE filterServiceQuery TEXT DEFAULT "";
    DECLARE filterPartnerQuery TEXT DEFAULT "";
    SET @filterRoleQuery = "";
    IF(_role != "") THEN
    SET @filterRoleQuery = CONCAT_WS(''," AND r.name = '",_role,"'");
    END IF;
    SET @filterCommissionTypeQuery = "";
	IF _commissionTypeId > 0 THEN
    SET @filterCommissionTypeQuery = CONCAT_WS(''," AND bpc.commissionTypeId = ",_commissionTypeId);
    END IF;
	SET @filterBankQuery = "";
    IF(_bankId > 0) THEN
    SET @filterBankQuery = CONCAT_WS(''," AND bpc.bankId = '",_bankId,"'");
    END IF;
	SET @filterServiceQuery = "";
    IF(_serviceId > 0) THEN
    SET @filterServiceQuery = CONCAT_WS(''," AND bpc.serviceId = '",_serviceId,"'");
    END IF;
    SET @filterPartnerQuery = "";
    IF(_partnerId > 0) THEN
    SET @filterPartnerQuery = CONCAT_WS(''," AND bpc.partnerId = '",_partnerId,"'");
    END IF;
	SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(bpc.id) as totalCount FROM bankloanpartnercommissions  as bpc 
    LEFT JOIN partners p ON p.id = bpc.partnerId 
    LEFT JOIN users ON users.id = p.userId 
    LEFT JOIN userroles ON userroles.userId = users.id 
    LEFT JOIN roles r ON r.id = userroles.roleId
    LEFT JOIN banks b ON b.id = bpc.bankId
    LEFT JOIN commissiontypes c ON c.id = bpc.commissionTypeId WHERE bpc.isDelete = 0 ",@filterCommissionTypeQuery,@filterRoleQuery,@filterServiceQuery,@filterBankQuery,@filterPartnerQuery);
  	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;	
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT bpc.*,b.name as bankName,p.fullName,p.contactNo,p.temporaryCode,p.permanentCode,c.name as commissionType,r.name as roleName FROM bankloanpartnercommissions as bpc 
    LEFT JOIN partners p ON p.id = bpc.partnerId 
    LEFT JOIN users ON users.id = p.userId 
    LEFT JOIN userroles ON userroles.userId = users.id 
    LEFT JOIN roles r ON r.id = userroles.roleId
    LEFT JOIN banks b ON b.id = bpc.bankId
    LEFT JOIN commissiontypes c ON c.id = bpc.commissionTypeId
    WHERE bpc.isDelete = 0 " ,@filterCommissionTypeQuery ,@filterRoleQuery,@filterServiceQuery,@filterBankQuery,@filterPartnerQuery," ORDER BY bpc.id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;	
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBankLoanPolicyWithFilter`(IN _bankLoanPolicyId INT,IN _bankId INT, IN _serviceId INT, IN _employmentTypeId INt, IN _cibilScore INT, IN _age INT, IN _income DECIMAL(15,3), IN _exp INT
, IN _vintage INT, IN _turnOver DECIMAL(16,2),IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE FilterQuery TEXT DEFAULT "";
    DECLARE StartIndexQuery TEXT DEFAULT "";
    SET @FilterQuery = "";
     IF _bankId > 0 THEN
		SET @FilterQuery = CONCAT_WS('', " AND bankId = ", _bankId);
	END IF;
    IF _serviceId > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND serviceId = ", _serviceId);
	END IF;
    IF _employmentTypeId > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND employmentTypeId = ", _employmentTypeId);
	END IF;    
    IF _cibilScore > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND minimumCibilScore > ", _cibilScore);
	END IF;
    IF _age > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND minAge <= ", _age, " AND maxAge >= ", _age);
	END IF;
    IF _income > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND minIncome <= ", _income);
	END IF;
    IF _exp > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND minWorkExperience <= ", _exp, " AND maxWorkExperience >= ", _exp);
	END IF;
    IF _vintage > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND vintage <= ", _vintage);
	END IF;
    IF _turnOver > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND minTurnOver <= ", _turnOver, " AND maxTurnOver >= ", _turnOver);
	END IF;
	IF _bankLoanPolicyId > 0 THEN
		SET @FilterQuery = CONCAT_WS('',@FilterQuery, " AND blp.id =",_bankLoanPolicyId);
	END IF;
    SET @StartIndexQuery = "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @SqlQuery = "";
	SET SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(blp.id) as totalCount FROM  bankloanpolicies blp 
    LEFT JOIN banks ON blp.bankId = banks.id 
    LEFT JOIN employmenttypes emp ON emp.id = blp.employmentTypeId
    LEFT JOIN services ON services.id = blp.serviceId WHERE blp.isDelete = 0",@FilterQuery);
    SET @SqlQuery = CONCAT_WS('',"SELECT blp.*,banks.name as bankName,emp.name as employmentType,emp.parentId,services.name as serviceName  FROM  bankloanpolicies blp 
    LEFT JOIN banks ON blp.bankId = banks.id 
    LEFT JOIN employmenttypes emp ON emp.id = blp.employmentTypeId
    LEFT JOIN services ON services.id = blp.serviceId WHERE blp.isDelete = 0",@FilterQuery,@StartIndexQuery);
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBanks`(IN _startIndex INT,IN _fetchRecords INT,IN _searchString VARCHAR(200))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	DECLARE WhereSearchStringQuery TEXT DEFAULT "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @WhereSearchStringQuery = "";
    IF _searchString !="" THEN 
		SET @WhereSearchStringQuery =CONCAT_WS(''," AND (name LIKE '%",_searchString,"%' OR headquarters LIKE '%",_searchString,"%' OR bankCode LIKE '%",_searchString,"%')" );            
	END IF; 
	SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS('', "SELECT COUNT(id) as totalCount FROM banks  WHERE isDelete = 0 ",@WhereSearchStringQuery);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM banks WHERE isDelete = 0 ",@WhereSearchStringQuery," ORDER BY 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 `adminGetBanners`(IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200),IN _isActive BOOLEAN,IN _roleIds VARCHAR(40),IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    DECLARE sqlQueryCount TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE startIndexQuery TEXT DEFAULT '';
    SET @sqlQuery = '';
	SET @filterQuery = "";
    IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(fromDate) <= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(toDate) >= ",_toDate,"'");
	END IF;
    IF(_isActive) THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND isActive = ",_isActive);
	END IF;
     IF(_roleIds != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND roleId IN(",_roleIds,")");
	END IF;
    SET @startIndexQuery = "";
     IF _startIndex >= 0 AND _fetchRecords >0 THEN 
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @sqlQueryCount = '';
    SET @sqlQueryCount = CONCAT_WS(''," SELECT COUNT(id) as totalCount FROM banners WHERE isDelete = 0",@filterQuery);
	

   
    SET @sqlQuery = CONCAT_WS(''," SELECT * FROM banners WHERE isDelete = 0",@filterQuery," ORDER BY 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 `adminGetBecomePartnerRequest`(IN _searchString VARCHAR(200),IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT '';
	DECLARE SqlQueryCount TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE StartIndexQuery TEXT DEFAULT '';
    SET @filterQuery = '';
	IF(_searchString != '') THEN
			SET @filterQuery =CONCAT_WS('',@filterQuery," AND (becomeapartnerrequest.fullName LIKE '%",_searchString,"%' OR becomeapartnerrequest.contactNo LIKE '%",_searchString,"%')" );
    END IF;
    SET @SqlQueryCount = '';
	SET @SqlQueryCount = CONCAT_WS('',' SELECT COUNT(becomeapartnerrequest.id) as totalCount FROM becomeapartnerrequest  LEFT JOIN cities ON cities.id = becomeapartnerrequest.cityId',@filterQuery);
  
    PREPARE countStmt FROM @SqlQueryCount;
     EXECUTE  countStmt;
    DEALLOCATE PREPARE countStmt;
   
   SET @StartIndexQuery = '';
    IF (_startIndex >= 0 AND _fetchRecords > 0) THEN
		SET @StartIndexQuery = CONCAT_WS('',' LIMIT ',_fetchRecords,' OFFSET ',_startIndex);
	END IF;
    SET @SqlQuery = CONCAT_WS('',' SELECT becomeapartnerrequest.*,cities.name as city FROM becomeapartnerrequest LEFT JOIN cities ON cities.id = becomeapartnerrequest.cityId WHERE becomeapartnerrequest.id',@filterQuery,' ORDER BY becomeapartnerrequest.id',@StartIndexQuery);
  
   PREPARE stmt FROM @SqlQuery;
    EXECUTE  stmt;
    DEALLOCATE PREPARE stmt;
   
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBusinessAnnualProfits`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(businessannualprofits.id) as totalCount FROM businessannualprofits 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 businessannualprofits WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBusinessAnnualSales`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(businessannualsales.id) as totalCount FROM businessannualsales 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 businessannualsales WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBusinessExperience`(IN _startIndex INT,IN _fetchRecords 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 `adminGetBusinessLoanById`(IN _customerLoanId INT)
BEGIN
SET @sql = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
			, maritalstatuses.status as maritalStatus ,customeraddresses.id as customerAddressId, customeraddresses.label,customeraddresses.addressLine1,customeraddresses.addressLine2,customeraddresses.cityId,customeraddresses.city,customeraddresses.district,customeraddresses.state,customeraddresses.pincode
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
            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(', _customerLoanId, ') ) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)');
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
    SELECT customerloans.*, employmenttypes.name as employmentType, services.displayName as displayName, services.name as serviceName,loanagainstcollteral.name as  loanagainstcollteralName,designations.name as designation,loanstatuses.status FROM customerloans 
	LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
	LEFT JOIN services ON  services.id = customerloans.serviceId
    LEFT JOIN customerloanemploymentdetails ON customerloanemploymentdetails.customerLoanId = customerloans.id
    LEFT JOIN designations ON customerloanemploymentdetails.designationId = designations.id
    LEFT JOIN loanagainstcollteral ON  loanagainstcollteral.id = customerloans.loanAgainstCollateralId
     LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
    
	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 as 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 customerloanoffers.*,banks.name as bankName FROM customerloanoffers INNER JOIN banks ON customerloanoffers.bankId = banks.id WHERE customerloanoffers.isDelete = 0 AND customerloanoffers.customerLoanId AND customerloanoffers.customerLoanId = _customerLoanId;
   
   SELECT customerloandetail.*,banks.name as bankName FROM customerloandetail INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloandetail.isDelete = 0 AND customerloandetail.customerLoanId AND customerloandetail.customerLoanId = _customerLoanId;
   
   SELECT customerLoanId,reason FROM customerloanrejectionreason WHERE isDelete = 0 AND customerLoanId = _customerLoanId;
		
   SELECT reason,customerLoanId,description FROM reasons WHERE isDelete = 0 AND customerLoanId = _customerLoanId;
   
   select partners.permanentCode,partners.id,partners.fullName,partners.contactNo,partners.gender,roles.name as roleName, partnerscustomerloans.customerLoanId,partners.parentPartnerId from partnerscustomerloans
			INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
			INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
             INNER JOIN userroles ON userroles.userId = partners.userId
            INNER JOIN roles ON userroles.roleId = roles.id
			WHERE partnerscustomerloans.customerLoanId = _customerLoanId;
           
	SELECT customerloantransferpropertydetails.*, banks.name as bankName FROM customerloantransferpropertydetails INNER JOIN banks ON customerloantransferpropertydetails.bankId = banks.id WHERE customerLoanId = _customerLoanId;
	
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBusinessLoans`(IN _customerLoanId TEXT)
BEGIN
	SET @sql = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
			, maritalstatuses.status as maritalStatus
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
            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(', _customerLoanId, ') ) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)');
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
    
    SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName, users.fullName as rmFullName,loanstatuses.status FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN users ON users.id = customerloans.assignRMId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
            WHERE customerloans.id IN(", _customerLoanId,") ORDER BY customerloans.id DESC");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
                   
			SET @getQuery ="";
            SET @getQuery = CONCAT_WS('',"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(", _customerLoanId,")");
			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(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
                
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(", _customerLoanId ,")");
			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(", _customerLoanId,")  ORDER BY loanstatuses.displayOrder");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
         
            SET @getQuery = "";
            SET @getQuery = CONCAT_WS('',"SELECT customerloancurrentresidentdetails.*, residenttypes.name residentType FROM customerloancurrentresidentdetails
			LEFT JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId WHERE customerloancurrentresidentdetails.customerLoanId IN(", _customerLoanId,")");
        	PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloanoffers.*,banks.name as bankName FROM customerloanoffers INNER JOIN banks ON customerloanoffers.bankId = banks.id WHERE customerloanoffers.isDelete = 0 AND customerloanoffers.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloandetail.*,banks.name as bankName FROM customerloandetail INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloandetail.isDelete = 0 AND customerloandetail.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerLoanId,reason FROM customerloanrejectionreason WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
              SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT reason,customerLoanId,description FROM reasons WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
              
            SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "select partners.id,partners.permanentCode,partners.fullName,partners.contactNo, partnerscustomerloans.customerLoanId from partnerscustomerloans
			INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
			INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
			WHERE partnerscustomerloans.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
             SET @getQuery ="";
            SET @getQuery = CONCAT('SELECT customerloantransferpropertydetails.* FROM customerloantransferpropertydetails WHERE customerLoanId IN(',_customerLoanId,')');
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetBusinessNatures`(IN _startIndex INT,In _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(businessnatures.id) as totalCount FROM businessnatures 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 businessnatures WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetcoapplicantrelations`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(coapplicantrelations.id) as totalCount FROM coapplicantrelations 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 coapplicantrelations WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCommission`(IN _startIndex INT,IN _fetchRecords INT,IN _bankId INT, IN _serviceId INT)
BEGIN
	DECLARE sqlCountQuery TEXT DEFAULT '';
    DECLARE sqlQuery TEXT DEFAULT '';
	DECLARE filterQuery TEXT DEFAULT '';
    DECLARE filterServiceQuery TEXT DEFAULT '';
	DECLARE StartIndexQuery TEXT DEFAULT '';
    SET @filterQuery = '';
    IF _bankId > 0 THEN
    SET @filterQuery = CONCAT_WS(@filterQuery,' AND  customerloandetail.bankId = ',_bankId,'');
	END IF;
    SET @filterServiceQuery = '';
    IF _serviceId > 0 THEN
		SET @filterServiceQuery = CONCAT_WS('',' AND customerloans.serviceId = ',_serviceId,'');
    END IF;
    SET @StartIndexQuery = '';
    IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
	SET @sqlCountQuery = '';
    SET @sqlCountQuery = CONCAT_WS('',' SELECT COUNT(admincommissionhistory.id) as totalCount FROM admincommissionhistory
	INNER JOIN admincommission ON admincommission.id  = admincommissionhistory.adminCommissionId
    LEFT JOIN customerloandetail ON customerloandetail.id =admincommissionhistory.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
    LEFT JOIN banks ON customerloandetail.bankId = banks.id
    WHERE admincommissionhistory.userId =1', @filterQuery,@filterServiceQuery);
    
	SET @sqlQuery = '';
    SET @sqlQuery = CONCAT_WS('',' SELECT admincommissionhistory.*,customerloandetail.amountDisbursed,customerloandetail.customerLoanId,customers.fullName,customers.contactNo,services.name as serviceName,banks.name as bankName,admincommission.commission as totalCommission FROM admincommissionhistory
	INNER JOIN admincommission ON admincommission.id  = admincommissionhistory.adminCommissionId
    LEFT JOIN customerloandetail ON customerloandetail.id =admincommissionhistory.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
    LEFT JOIN banks ON customerloandetail.bankId = banks.id
    WHERE admincommissionhistory.userId =1 ',@filterQuery,@filterServiceQuery,' ORDER BY admincommissionhistory.id DESC',@StartIndexQuery);
    PREPARE countStmt FROM @sqlCountQuery;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
	PREPARE stmt FROM @sqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCommissionTemplates`(IN _startIndex INT, IN _fetchRecords INT,IN _bankIds VARCHAR(200),IN _serviceIds VARCHAR(200))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE filterQuery TEXT DEFAULT "";
	IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @filterQuery = "";
    IF _bankIds != '' THEN 
		SET @filterQuery = CONCAT_WS(''," AND commissiontemplate.bankId IN (",_bankIds,")");
    END IF;
        IF _serviceIds != '' THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND commissiontemplate.serviceId IN (",_serviceIds,")");
    END IF;
	SET @SqlQueryCount = "";
	SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(commissiontemplate.id) as totalCount FROM commissiontemplate INNER JOIN commissiontypes ON commissiontemplate.commissionTypeId = commissiontypes.id LEFT JOIN banks ON commissiontemplate.bankId = banks.id LEFT JOIN services ON commissiontemplate.serviceId = services.id WHERE commissiontemplate.isDelete = 0",@filterQuery);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT commissiontemplate.*,commissiontypes.name as commissionType,banks.name as bankName,services.name as service FROM commissiontemplate INNER JOIN commissiontypes ON commissiontemplate.commissionTypeId = commissiontypes.id LEFT JOIN banks ON commissiontemplate.bankId = banks.id LEFT JOIN services ON commissiontemplate.serviceId = services.id WHERE commissiontemplate.isDelete = 0',@filterQuery,@StartIndexQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













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













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













DELIMITER $$
CREATE  PROCEDURE `adminGetCompanyType`()
BEGIN
	SELECT * FROM companytypes WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetContactRequest`(IN _startIndex INT,IN _fetchRecords INT,IN _status VARCHAR(200),IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200))
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 _status != '' THEN
		SET @filterQuery = CONCAT_WS('', ' AND status = ',_status);
	END IF;
	IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(contactDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(contactDate) <= '",_toDate,"'");
	END IF;
    SET @SqlQueryCount = '';
    SET @SqlQueryCount = CONCAT_WS('',' SELECT COUNT(id) as totalCount FROM contacts ',@filterQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
    SET @SqlQuery = '';
    SET @SqlQuery = CONCAT_WS('',' SELECT * FROM contacts ' ,@filterQuery,' ORDER BY id DESC', @StartIndexQuery);
    
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCreditCards`(IN _bankId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE SqlWhereQuery TEXT DEFAULT "";
	DECLARE StartIndexQuery TEXT DEFAULT "";
	SET @StartIndexQuery = "";
    IF _startIndex >= 0 AND _fetchRecords>0 THEN
            SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @SqlWhereQuery = "";
    IF _bankId > 0 THEN
		SET @SqlWhereQuery = CONCAT_WS('',' AND bankcreditcard.bankId = ',_bankId);
    END IF;
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(bankcreditcard.id) as totalCount FROM bankcreditcard INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE bankcreditcard.isDelete = 0",@SqlWhereQuery); 
    SET @SqlQuery = "";
    SET @SqlQuery = CONCAT_WS('', "SELECT bankcreditcard.*,banks.name as bankName FROM bankcreditcard INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE bankcreditcard.isDelete = 0",@SqlWhereQuery," ORDER BY bankcreditcard.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 `adminGetCreditCardStatuses`()
BEGIN
	SELECT * FROM creditcardstatuses WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCustomer`(IN _startIndex INT,IN _fetchRecords INT,IN _customerId INT,IN _searchString VARCHAR(200),IN _roleIds VARCHAR(100),IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200),IN _isDelete BOOLEAN,IN _cityIds VARCHAR(100),IN _stateIds VARCHAR(100),IN _serviceIds VARCHAR(100),IN _statusIds VARCHAR(100))
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 _customerId > 0 THEN
		SET @filterQuery = CONCAT_WS(''," AND customers.id = ",_customerId);
	END IF;
	IF _searchString != '' THEN
		SET @filterQuery =CONCAT_WS('',@filterQuery," AND (customers.fullName LIKE '%",_searchString,"%' OR customers.contactNo LIKE '%",_searchString,"%' OR customers.temporaryCode LIKE '%",_searchString,"%' OR customers.permanentCode LIKE '%",_searchString,"%')" );
    END IF;
    IF _roleIds != '' THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND ur.roleId IN ('",_roleIds,"')");
	END IF;
      IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(customers.createdDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(customers.createdDate) <= '",_toDate,"'");
	END IF;
    IF _isDelete = true  THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND customers.isDelete = true " );
	END IF;
     IF _isDelete = false  THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND customers.isDelete = false " );
	END IF;
    IF _cityIds != '' THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND customeraddresses.cityId IN ('",_cityIds,"')");
	END IF;
    IF _stateIds != '' THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND states.id IN ('",_stateIds,"')");
	END IF;
    IF _serviceIds != '' THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND customerloans.serviceId IN ('",_serviceIds,"')");
    END IF;
    IF _statusIds != '' THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND customerloans.statusId IN ('",_statusIds,"')");
	END IF;
    	SET @SqlQueryCount = "";
	SET @SqlQueryCount =  CONCAT_WS('',"SELECT DISTINCT COUNT(DISTINCT(customers.id)) as totalCount FROM customers LEFT JOIN users u ON u.id = customers.createdBy 
    INNER JOIN userroles ur ON u.id = ur.userId 
    INNER JOIN roles r ON r.id = ur.roleId 
    LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
    LEFT JOIN partners p ON u.id = p.userId 
    LEFT JOIN cities ON cities.id = customeraddresses.cityId 
    LEFT JOIN districts ON districts.id = cities.districtId 
    LEFT JOIN states ON states.id = districts.stateId 
    LEFT JOIN customerloans ON customerloans.customerId = customers.id
    WHERE customeraddresses.addressTypeId = 1 AND customers.currentRoleId = 2",@filterQuery,"");
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT DISTINCT  customers.*,customeraddresses.addressLine1,customeraddresses.addressLine2,customeraddresses.pincode,customeraddresses.label,customeraddresses.id as customerAddressId,customeraddresses.cityId,customeraddresses.city,customeraddresses.district,customeraddresses.state,p.id as partnerId,p.fullName as partnerName,p.contactNo as partnerContactNo,ur.roleId,r.name as customerGroup FROM customers LEFT JOIN users u ON u.id = customers.createdBy INNER JOIN userroles ur ON u.id = ur.userId INNER JOIN roles r ON r.id = ur.roleId LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id LEFT JOIN partners p ON u.id = p.userId LEFT JOIN cities ON cities.id = customeraddresses.cityId LEFT JOIN districts ON districts.id = cities.districtId LEFT JOIN states ON states.id = districts.stateId LEFT JOIN customerloans ON customerloans.customerId = customers.id  WHERE customeraddresses.addressTypeId = 1 AND customers.currentRoleId = 2 ",@filterQuery,"   ORDER BY customers.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 `adminGetCustomerById`(IN _customerId INT)
BEGIN
	SELECT customers.*,users.email,users.profilePicUrl,customeraddresses.id as customerAddressId,customeraddresses.label,customeraddresses.addressLine1,customeraddresses.addressLine2,customeraddresses.pincode,customeraddresses.cityId,customeraddresses.city,customeraddresses.district,customeraddresses.state,maritalstatuses.status as maritalStatus FROM customers INNER JOIN users ON customers.userId = users.id 
    LEFT JOIN customeraddresses  ON customeraddresses.customerId = customers.id
    LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
    WHERE customers.isDelete = 0 AND customers.id = _customerId ;
	
	SELECT customerloans.*, services.name as serviceName,employmenttypes.name as employmentType,loanstatuses.status as loanStatus,customerloandetail.amountDisbursed,customerloandetail.ROI,customerloandetail.tenure,customerloandetail.emi,customerloandetail.totalInterestpayable FROM customerloans
    LEFT JOIN services ON customerloans.serviceId = services.id 
    LEFT JOIN employmenttypes ON employmenttypes.id = customerloans.employmentTypeId
    LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
    LEFT JOIN customerloandetail ON customerloandetail.customerLoanId = customerloans.id
    WHERE customerId = _customerId;
    
	SELECT leads.*,services.name as serviceName,employmenttypes.name as employmentType,partners.fullName as assignPartnerName,partners.contactNo as assignPartnerContactNo,leadstatuses.name as leadStatus FROM leads
	LEFT JOIN leadstatuses ON leadstatuses.id = leads.leadStatusId
    LEFT JOIN services ON leads.serviceId = services.id 
    LEFT JOIN employmenttypes ON employmenttypes.id = leads.employmentTypeId
    LEFT JOIN partners ON partners.id = leads.assignToPartnerId
    WHERE leads.contactNo = (SELECT contactNo FROM customers WHERE id  = _customerId);
    
    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 customers ON customers.userId = users.id
    LEFT JOIN userwallet ON userwallethistory.userWalletId = userwallet.id
	WHERE customers.id = _customerId;
    
    SELECT partners.parentPartnerId,partners.fullName,partners.contactNo,partners.temporaryCode,partners.permanentCode,partners.gender,partners.panCardNo,roles.name as partnerRoleName,partners.userId FROM partners
    LEFT JOIN users ON users.id = partners.userId
    LEFT JOIN userroles ON partners.userId = userroles.id
    LEFT JOIN roles ON roles.id = userroles.roleId
    LEFT JOIN customers ON customers.createdBy = users.id
    WHERE customers.id = _customerId AND customers.createdBy != _customerId;
    
      SELECT orders.*,products.name as productName,orderstatuses.status FROM orders INNER JOIN products ON orders.productId = products.id INNER JOIN orderstatuses ON  orderstatuses.id = orders.orderStatusId WHERE userId IN (SELECT userId FROM customers WHERE id = _customerId);
    
    SELECT customerotherloans.* ,employmenttypes.name as employmentType,servicetypes.name as serviceType,services.name as serviceName FROM customerotherloans
	INNER JOIN servicetypes ON servicetypes.id = customerotherloans.serviceTypeId
	INNER JOIN services ON services.id = customerotherloans.serviceId
	INNER JOIN customers ON customers.userId = customerotherloans.userId
	INNER JOIN employmenttypes ON employmenttypes.id = customerotherloans.employmentTypeId
	WHERE customerotherloans.userId = (SELECT customers.userId FROM customers WHERE customers.id = _customerId);

END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCustomerCreditCard`(IN _startIndex INT,IN _fetchRecords INT,IN _customerId INT,IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200))
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    DECLARE sqlQueryCount TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE startIndexQuery TEXT DEFAULT '';
    SET @StartIndexQuery = "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @filterQuery = "";
    IF _customerId > 0 THEN
		SET @filterQuery = CONCAT_WS(''," AND customercreditcards.customerId = ",_customerId,"");
	END IF;
    IF _fromDate != '' THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND customercreditcards.creditCardTransactionDate <= ",fromDate,"");
    END IF;
        IF _toDate != '' THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND customercreditcards.creditCardTransactionDate >= ",_toDate,"");
    END IF;
    SET @sqlQueryCount = "";
    SET @sqlQueryCount = CONCAT_WS(''," SELECT COUNT(customercreditcards.id) as totalCount FROM customercreditcards 
		LEFT JOIN customercreditcardoffer ON customercreditcards.id = customercreditcardoffer.customerCreditCardId 
		LEFT JOIN customers ON customers.id = customercreditcards.customerId
		LEFT JOIN bankcreditcard  ON customercreditcardoffer.bankCreditCardId = bankcreditcard.id 
		LEFT JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcards.statusId
		LEFT JOIN banks ON banks.id = bankcreditcard.bankId WHERE customercreditcards.isDelete = 0",@filterQuery);
        
	SET @sqlQuery = "";
	SET @sqlQuery = CONCAT_WS('',"SELECT customercreditcards.*,bankcreditcard.creditCardName,bankcreditcard.creditCardUrl,bankcreditcard.joiningfee,bankcreditcard.renualfee,banks.name as bankName,bankcreditcard.bankId,customers.fullName,customers.contactNo,customercreditcardoffer.referenceNo,creditcardstatuses.status,employmenttypes.name as employmentType FROM customercreditcards 
		LEFT JOIN customercreditcardoffer ON customercreditcards.id = customercreditcardoffer.customerCreditCardId 
		LEFT JOIN customers ON customers.id = customercreditcards.customerId
		LEFT JOIN bankcreditcard  ON customercreditcardoffer.bankCreditCardId = bankcreditcard.id 
		LEFT JOIN banks ON banks.id = bankcreditcard.bankId 
        LEFT JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcards.statusId
        LEFT JOIN customercreditcardemploymentdetail ON customercreditcardemploymentdetail.creditCardId = customercreditcards.id
        LEFT JOIN employmenttypes ON customercreditcardemploymentdetail.employmentTypeId = employmenttypes.id
        WHERE customercreditcards.isDelete = 0",@filterQuery," ORDER BY customercreditcards.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 `adminGetCustomerCreditCardById`(IN _customerId INT,IN _customerCreditCardId INT)
BEGIN
	SELECT customercreditcards.*,banks.name as bankName,creditcardstatuses.status FROM customercreditcards 
    LEFT JOIN banks ON customercreditcards.otherCreditCardBankId = banks.id
    LEFT JOIN creditcardstatuses ON creditcardstatuses.id = customercreditcards.statusId
    WHERE customercreditcards.id = _customerCreditCardId;
	
	 SELECT customercreditcardemploymentdetail.*,employmenttypes.name as employmentType,educationtypes.name as educationType,banks.name as bankName 
            FROM customercreditcardemploymentdetail LEFT JOIN employmenttypes ON customercreditcardemploymentdetail.employmentTypeId  = employmenttypes.id
            LEFT JOIN educationtypes ON customercreditcardemploymentdetail.educationTypeId = educationtypes.id
            LEFT JOIN banks ON customercreditcardemploymentdetail.bankId = banks.id
            WHERE customercreditcardemploymentdetail.creditCardId = _customerCreditCardId;
	
	
	
	 SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customeraddresses.city,customeraddresses.district,customeraddresses.state
            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,customeraddresses.city,customeraddresses.district,customeraddresses.state
            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,bankcreditcard.creditCardName,bankcreditcard.joiningfee,bankcreditcard.renualfee,bankcreditcard.creditCardUrl,bankcreditcard.keyFeatures,bankcreditcard.benifitDescription FROM customercreditcardoffer
            INNER JOIN bankcreditcard ON bankcreditcard.id =  customercreditcardoffer.bankCreditCardId
			INNER JOIN banks ON banks.id = bankcreditcard.bankId WHERE customerCreditCardId IN(_customerCreditCardId);
            
		SELECT users.id as userId, users.email,customers.birthDate, customers.fullName,customers.contactNo,customers.gender,customers.maritalStatusId,maritalstatuses.status as maritalStatus,customers.panCardNo
	, customeraddresses.id as customerAddressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,customeraddresses.city,customeraddresses.district,customeraddresses.state
	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 
    LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
	WHERE customers.id = _customerId AND users.isDelete = 0   AND customeraddresses.addressTypeId = 1 AND userroles.roleId IN(2);
    
    SELECT id,reason FROM customercreditcardrejectionreason WHERE isDelete = 0 AND customerCreditCardId = _customerCreditCardId;
    
    SELECT reason,description,id FROM reasons WHERE customerCreditCardId = _customerCreditCardId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetCustomerLoanId`(IN _serviceId INT,IN _startIndex INT,IN _fetchRecords INT,OUT _customerLoanId TEXT)
BEGIN
	DECLARE startIndexQuery  TEXT DEFAULT '';
    DECLARE sqlQuery TEXT DEFAULT '';
    SET @startIndexQuery = '';
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
 	SET @sqlQuery = CONCAT_WS('SELECT GROUP_CONCAT(id) FROM customerloans WHERE serviceId = _serviceId',@startIndexQuery,' into _customerloanId'); 
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetcustomerloanrejectionreason`(IN _customerLoanId INT)
BEGIN
	SELECT * FROM custoemerloanrejectionreason WHERE customerLoanId = _customerLoanId AND isDelete = 0;
    SELECT * FROM reasons WHERE customerLoanId = _customerLoanId AND isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetDashboard`()
BEGIN

SELECT COUNT(customerloans.id) as todayCount FROM customerloans  WHERE  customerloans.createdDate = CURRENT_DATE();

SELECT COUNT(customerloans.id) as weekCount FROM customerloans WHERE  WEEK(customerloans.createdDate) = WEEK(CURRENT_TIMESTAMP);

SELECT COUNT(customerloans.id) as monthCount FROM customerloans WHERE  MONTH(customerloans.createdDate) = MONTH(CURRENT_TIMESTAMP);

SELECT COUNT(customerloans.id) as previousMonthCount  FROM customerloans WHERE  MONTH(customerloans.createdDate) = MONTH((CURRENT_TIMESTAMP)) - 1 ;

SELECT COUNT(customerloans.id) as monthCount FROM customerloans WHERE  YEAR(customerloans.createdDate) = YEAR(CURRENT_TIMESTAMP);

SELECT COUNT(partners.id) as dsaCount FROM partners INNER JOIN userroles ON partners.userId = userroles.userId WHERE userroles.roleId = 3;

SELECT COUNT(partners.id) as subDsaCount FROM partners INNER JOIN userroles ON partners.userId = userroles.userId WHERE userroles.roleId = 4;

SELECT COUNT(partners.id) as connectorCount FROM partners INNER JOIN userroles ON partners.userId = userroles.userId WHERE userroles.roleId = 6;

SELECT COUNT(partners.id) as employeeCount FROM partners INNER JOIN userroles ON partners.userId = userroles.userId WHERE userroles.roleId = 5;

SELECT COUNT(customers.id) as totalCustomer FROM customers LEFT JOIN users u ON u.id = customers.createdBy INNER JOIN userroles ur ON u.id = ur.userId INNER JOIN roles r ON r.id = ur.roleId LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id LEFT JOIN partners p ON u.id = p.userId WHERE customeraddresses.addressTypeId = 1;

SELECT SUM(amountDisbursed) as totalAmountDisbursed FROM customerloandetail;

SELECT COUNT(customerloans.id) as totalCount FROM customerloans;

END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetDisbursedApplication`(IN _startIndex INT,IN _fetchrecords INT)
BEGIN
    DECLARE sqlQuery TEXT DEFAULT '';
	SELECT COUNT(customerloans.id) as totalDisbursedApplication FROM customerloans INNER JOIN services ON services.id = customerloans.serviceId INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN loanstatuses ON loanstatuses.id = customerloans.statusId INNER JOIN customerloandetail ON customerloans.id = customerloandetail.customerLoanId INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloans.statusId = 8;
    
    SET @sqlQuery = '';
    SET @sqlQuery = CONCAT_WS(''," SELECT customerloans.*,services.name as serviceName,customers.fullName,customers.contactNo,customerloandetail.refrenceNo,customerloandetail.amountDisbursed,customerloandetail.ROI,customerloandetail.tenure,customerloandetail.bankId,customerloandetail.emi,customerloandetail.totalInterestPayable,banks.name as bankName FROM  customerloans INNER JOIN services ON services.id = customerloans.serviceId INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN loanstatuses ON loanstatuses.id = customerloans.statusId INNER JOIN customerloandetail ON customerloans.id = customerloandetail.customerLoanId
    INNER JOIN banks ON customerloandetail.bankId = banks.id
    WHERE customerloans.statusId = 8"," ORDER BY id DESC");
    
    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 `adminGetDocumentMaster`(IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    SELECT COUNT(*) as totalCount FROM documentmasters;
    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 documentmasters "," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetDsa`(IN _startIndex INT,IN _fetchRecords INT,IN _role VARCHAR(20),IN _searchString VARCHAR(100),IN _status VARCHAR(50),IN _badgeId INT,IN _isDelete BOOLEAN,IN _fromDate VARCHAR(100),IN _toDate VARCHAR(100))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE DsaQuery TEXT DEFAULT "";
    DECLARE filterQuery TEXT DEFAULT "";
    SET @filterQuery = "";
     IF _searchString !="" THEN 
            SET @filterQuery =CONCAT_WS(''," AND (p.fullName LIKE '%",_searchString,"%' OR p.contactNo LIKE '%",_searchString,"%' OR c.name LIKE '%",_searchString,"%')" );            
	END IF;
	IF  _status = "Approved" THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND u.isDisabled = false " );
	ELSEIF  _status = "DisApproved" THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND u.isDisabled = true " );
    END IF;
    IF _badgeId > 0 THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND p.currentBadgeId = ",_badgeId);
	END IF;
    IF _isDelete = true  THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND p.isDelete = true " );
	END IF;
     IF _isDelete = false  THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND p.isDelete = false " );
	END IF;
    IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(p.createdDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(p.createdDate) <= '",_toDate,"'");
	END IF;
    
	SET @SqlQueryCount = "";
	SET @SqlQueryCount = CONCAT_WS('',"SELECT COUNT(p.id) as totalCount FROM partners as p INNER JOIN users u ON p.userId = u.id INNER JOIN userroles ur ON p.userId = ur.userId INNER JOIN roles r ON ur.roleId = r.id LEFT JOIN cities c ON p.cityId = c.id LEFT JOIN badges ON p.currentBadgeId = badges.id WHERE r.name = '", _role, "'",@filterQuery);
	SET @StartIndexQuery="";
    IF _startIndex >= 0 AND _fetchRecords>0 THEN
	SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @SqlQuery = "";
    SET @DsaQuery ="";
    SET @DsaQuery = CONCAT_WS('',"SELECT  p.*,u.isDisabled,u.id as userId,c.name as cityName, prt.permanentCode as networkCode, pnt.permanentCode as teamCode,prt.fullName as parentPartnerNetworkFullName,pnt.fullName as parentPartnerTeamFullName,badges.name as badgeName FROM partners as p INNER JOIN users u ON p.userId = u.id LEFT JOIN cities c ON p.cityId = c.id INNER JOIN userroles as ur ON p.userId = ur.userId LEFT JOIN roles r ON ur.roleId = r.id LEFT JOIN partnernetworks pn ON p.id = pn.networkPartnerId LEFT JOIN partners prt ON pn.partnerId = prt.id LEFT JOIN partnerteams pt ON p.id = pt.teamPartnerId LEFT JOIN partners pnt ON pt.partnerId = pnt.id LEFT JOIN badges ON p.currentBadgeId = badges.id  WHERE r.name = '",_role, "'");
	SET @SqlQuery = CONCAT_WS('', @DsaQuery,@filterQuery,' ORDER BY p.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 `adminGetDsaDetail`(IN _id int)
BEGIN
	SELECT SUM(cl.loanAmount) as thisMonthAmount FROM partnerscustomerloans as pcl INNER JOIN customerloans as cl ON pcl.customerLoanId = cl.id WHERE pcl.partnerId = _id AND pcl.isDelete = 0 AND MONTH(pcl.transactionDate) = MONTH(now()) AND YEAR(pcl.transactionDate) = YEAR(now()) GROUP BY pcl.partnerId;
	SELECT COUNT(pcl.id) as totalApplication,SUM(cl.loanAmount) as totalAmount FROM partnerscustomerloans as pcl INNER JOIN customerloans as cl ON pcl.customerLoanId = cl.id WHERE pcl.partnerId = _id AND pcl.isDelete = 0 GROUP BY pcl.partnerId;
	SELECT COUNT(cl.id) as totalPendingLoan FROM partnerscustomerloans as pcl INNER JOIN customerloans as cl ON pcl.customerLoanId = cl.id INNER JOIN customerloanstatushistory as clh ON cl.id = clh.customerLoanId WHERE pcl.partnerId = _id AND pcl.isDelete = 0 AND clh.loanStatusId = 1 GROUP BY pcl.partnerId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetEmploymentNatures`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(employmentnatures.id) as totalCount FROM employmentnatures 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 employmentnatures WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetEmploymentServcieTypes`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(employmentservicetypes.id) as totalCount FROM employmentservicetypes 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 employmentservicetypes WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetEmploymentTypes`()
BEGIN
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM employmenttypes "," ORDER BY id desc ");
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetFaqCategories`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(faqcategories.id) as totalCount FROM faqcategories 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 faqcategories WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetFaqs`(IN _faqCategoryId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(faqs.id) as totalCount FROM faqs WHERE isDelete = 0 AND faqCategoryId = _faqCategoryId;
	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 faqs WHERE isDelete = 0 AND faqCategoryId = ",_faqCategoryId," ORDER BY id DESC ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetFaqType`()
BEGIN
	SELECT * FROM faqtypes WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetHomeLoan`(IN _customerLoanIds TEXT)
BEGIN
	DECLARE customerLoanIds TEXT DEFAULT '';
    /*CALL adminGetCustomerLoanId(_serviceId,_startIndex,_fetchRecords,@a);
	SELECT @a INTO @customerLoanIds FROM dual;
    SELECT @customerLoanIds;*/

		SET @sql = CONCAT('SELECT DISTINCT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
			, maritalstatuses.status as maritalStatus
            FROM users 
            LEFT JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
            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 @sql;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
    
		SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', " SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName, users.fullName as rmFullName,loanstatuses.status FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN users ON users.id = customerloans.assignRMId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
            WHERE customerloans.id IN(", _customerLoanIds,") ORDER BY customerloans.id DESC");
			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 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 partners.id,partners.permanentCode,partners.fullName,partners.contactNo, partnerscustomerloans.customerLoanId from partnerscustomerloans
		INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
		INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
		WHERE partnerscustomerloans.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,")  ORDER BY loanstatuses.displayOrder");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetHomeLoanByCustomerLoanId`(IN _customerId INT,IN _customerLoanId INT)
BEGIN
	SET @sql = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
			, maritalstatuses.status as maritalStatus,customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId,cities.name as cityName
            FROM users 
            LEFT    JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
            LEFT JOIN customeraddresses ON customeraddresses.customerId = customers.id 
            LEFT JOIN cities ON cities.id = customeraddresses.cityId
            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 = ',_customerLoanId,' AND customeraddresses.addresstypeId = 1 AND users.isDelete = 0 AND users.isActive = 1)');
    PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
    
    SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', " SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName, users.fullName as rmFullName,loanstatuses.status FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN users ON users.id = customerloans.assignRMId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
            WHERE customerloans.id  = ",_customerLoanId," ORDER BY customerloans.id DESC");
			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,industrytypes.name as industryType
		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
        LEFT JOIN industrytypes ON  industrytypes.id = customerloanemploymentdetails.industryTypeId
		WHERE customerloanemploymentdetails.customerloanId = ", _customerLoanId);
        PREPARE stmt FROM @getQuery;
		EXECUTE stmt;
		DEALLOCATE PREPARE stmt;
        
	SET @getQuery = "";
		SET @getQuery = CONCAT_WS('',"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);
     PREPARE stmt FROM @getQuery;
	 EXECUTE stmt;
	 DEALLOCATE PREPARE stmt;
     
     SET @getQuery = "";
		SET @getQuery = CONCAT_WS('',"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);
    PREPARE stmt FROM @getQuery;
	 EXECUTE stmt;
	 DEALLOCATE PREPARE stmt;
     
     SET @getQuery = "";
     SET @getQuery = CONCAT_WS('',"SELECT customerloancurrentresidentdetails.*,residenttypes.name as residentType FROM customerloancurrentresidentdetails
	INNER JOIN residenttypes ON residenttypes.id = customerloancurrentresidentdetails.residentTypeId
	WHERE customerloancurrentresidentdetails.customerloanId = ",_customerLoanId);
    PREPARE stmt FROM @getQuery;
	 EXECUTE stmt;
	 DEALLOCATE PREPARE stmt;
     
     SET @getQuery = "";
     SET @getQuery = CONCAT_WS(''," SELECT  customeraddresses.id as addressId, customeraddresses.addressTypeId, customeraddresses.label, customeraddresses.addressLine1, customeraddresses.addressLine2, customeraddresses.pincode, customeraddresses.cityId
            FROM customeraddresses 
          WHERE customeraddresses.customerId = ",_customerId, " AND customeraddresses.addresstypeId = 3;");
	 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 =", _customerLoanId);
    PREPARE stmt FROM @getQuery;
	 EXECUTE stmt;
	 DEALLOCATE PREPARE stmt;
     
     SET @getQuery = "";
     SET @getQuery = CONCAT_WS('',"	SELECT * FROM loancompletescreenhistory WHERE customerloanId = ",_customerLoanId);
	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 = ",_customerLoanId,"  ORDER BY loanstatuses.displayOrder");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
      SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloanoffers.*,banks.name as bankName FROM customerloanoffers INNER JOIN banks ON customerloanoffers.bankId = banks.id WHERE customerloanoffers.isDelete = 0 AND customerloanoffers.customerLoanId = ",_customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloandetail.*,banks.name as bankName FROM customerloandetail INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloandetail.isDelete = 0 AND customerloandetail.customerLoanId =",_customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerLoanId,reason FROM customerloanrejectionreason WHERE isDelete = 0 AND customerLoanId =",_customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
              SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT reason,customerLoanId,description FROM reasons WHERE isDelete = 0 AND customerLoanId =",_customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
              
            SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "select partners.id, partners.permanentCode,partners.fullName,partners.contactNo,partners.gender,roles.name as roleName, partnerscustomerloans.customerLoanId from partnerscustomerloans
			INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
			INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
			INNER JOIN userroles ON userroles.userId = partners.userId
            INNER JOIN roles ON userroles.roleId = roles.id
			WHERE partnerscustomerloans.customerLoanId =",_customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanpropertydetails.*, propertytypes.name as propertyType FROM customerloanpropertydetails 
	INNER JOIN propertytypes ON propertytypes.id = customerloanpropertydetails.propertyTypeId 
	WHERE customerloanpropertydetails.customerloanId = ", _customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloantransferpropertydetails.*, banks.name as bankName FROM customerloantransferpropertydetails 
	INNER JOIN banks ON banks.id = customerloantransferpropertydetails.bankId 
	WHERE customerloantransferpropertydetails.customerloanId = ", _customerLoanId);
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetIndustryTypes`()
BEGIN
	SELECT * FROM industrytypes WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetLastInvoiceNumber`()
BEGIN
	SELECT invoiceNumber FROM partnerinvoice WHERE Date(createdDate) = CURRENT_DATE() ORDER BY id DESC limit 1;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetLeads`(IN _startIndex INT,IN _fetchRecords INT,IN _leadId INT,IN _serviceId TEXT,IN _partnerId TEXT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE FilterQuery TEXT DEFAULT "";
    DECLARE serviceFilterQuery TEXT DEFAULT "";
    SET @FilterQuery = "";
    SET @serviceFilterQuery ="";
    IF (_serviceId != '') THEN
		SET @serviceFilterQuery = CONCAT_WS(''," AND leads.serviceId IN (",_serviceId,")");
    END IF;
     IF (_partnerId != '') THEN
		SET @serviceFilterQuery = CONCAT_WS('',@serviceFilterQuery," AND leads.assignToPartnerId IN (",_partnerId,")");
    END IF;
   	IF(_leadId > 0) THEN
		SET @FilterQuery = CONCAT_WS(''," AND leads.id = ",_leadId);
	END IF;
       	SET @SqlQueryCount = "";
        SET @SqlQueryCount = CONCAT_WS('',"SELECT COUNT(leads.id) as totalCount FROM leads LEFT JOIN services ON leads.serviceId = services.id 
		LEFT JOIN employmenttypes ON employmenttypes.id = leads.employmentTypeId 
		LEFT JOIN professiontypes ON professiontypes.id = leads.professionTypeId 
		LEFT JOIN banks ON banks.id = leads.primaryBankId
		LEFT JOIN cities ON leads.cityId = cities.id
         LEFT JOIN users ON users.id = leads.createdBy
        LEFT JOIN customers ON customers.contactNo = leads.contactNo
		LEFT JOIN leadaddresses ON leadaddresses.leadId = leads.id
		LEFT JOIN partners ON partners.id = leads.assignToPartnerId WHERE leads.isDelete = 0 ",@FilterQuery,@serviceFilterQuery);
      
       PREPARE countStmt FROM @SqlQueryCount;
		EXECUTE countStmt;
		DEALLOCATE PREPARE countStmt;
		SET @StartIndexQuery = '';
		IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
		END IF;
        
		SET @SqlQuery = CONCAT_WS('',"SELECT leads.*,employmenttypes.name,professiontypes.name as professionType,banks.name as bankName,services.name as serviceName,cities.name as cityName,partners.fullName as partnerName,partners.contactNo as partnerContactNo,users.fullName as createdByUser,users.contactNo as createdByContactNo,customers.id as customerId,leadaddresses.id as customerAddressId,leadaddresses.label,leadaddresses.addressLine1,leadaddresses.addressLine2,leadaddresses.pincode,leadaddresses.cityId,leadaddresses.district,leadaddresses.state FROM leads 
        LEFT JOIN services ON leads.serviceId = services.id 
		LEFT JOIN employmenttypes ON employmenttypes.id = leads.employmentTypeId 
		LEFT JOIN professiontypes ON professiontypes.id = leads.professionTypeId 
		LEFT JOIN banks ON banks.id = leads.primaryBankId
        LEFT JOIN cities ON leads.cityId = cities.id
        LEFT JOIN users ON users.id = leads.createdBy
        LEFT JOIN customers ON customers.contactNo = leads.contactNo
		LEFT JOIN leadaddresses ON leadaddresses.leadId = leads.id
		LEFT JOIN partners ON partners.id = leads.assignToPartnerId WHERE leads.isDelete = 0 ",@FilterQuery,@serviceFilterQuery," ORDER BY leads.id DESC",@StartIndexQuery);

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













DELIMITER $$
CREATE  PROCEDURE `adminGetLeadStatus`()
BEGIN
	SELECT * FROM leadstatuses WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetLeadStatusHistory`(IN _leadIds TEXT)
BEGIN
	DECLARE SqlQuerty TEXT DEFAULT "";
    SET @SqlQuery = "";
    SET @SqlQuery = CONCAT_WS(''," SELECT leadstatushistory.*,leadstatuses.name FROM leadstatushistory INNER JOIN leadstatuses ON leadstatushistory.leadStatusId = leadstatuses.id WHERE leadId IN (",_leadIds,") ORDER BY id DESC" );
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetLoanAgainstCollteral`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(loanagainstcollteral.id) as totalCount FROM loanagainstcollteral 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 loanagainstcollteral WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetLoanStatuses`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(loanstatuses.id) as totalCount FROM loanstatuses 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 loanstatuses WHERE isDelete = 0"," ORDER BY displayOrder ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













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













DELIMITER $$
CREATE  PROCEDURE `adminGetOffer`(IN _customerLoanId INT)
BEGIN
	SELECT * FROM offers WHERE isDelete = 0 AND customerLoanId = _customerLoanId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetOrders`(IN _startIndex INT,IN _fetchRecords INT,IN _searchString TEXT,IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200),IN _statusIds VARCHAR(100))
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 _searchString != '' THEN
		SET @filterQuery =CONCAT_WS('',@filterQuery," AND (users.fullName LIKE '%",_searchString,"%' OR users.contactNo LIKE '%",_searchString,"%' OR products.name LIKE '%",_searchString,"%')");
    END IF;
   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 _statusIds != '' THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND orders.orderStatusId IN ('",_statusIds,"')");
	END IF;
    SET @SqlQueryCount = '';
    SET @SqlQueryCount = CONCAT_WS('',"SELECT COUNT(orders.id) as totalCount FROM orders LEFT JOIN users ON orders.userId = users.id
	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.id > 0",@filterQuery);
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @SqlQuery = '';
    SET @SqlQuery = CONCAT_WS('',"SELECT orders.*,users.fullName,users.contactNo,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 users ON orders.userId = users.id 
    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.id > 0",@filterQuery," ORDER BY orders.transactionDate DESC",@startIndexQuery);
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













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













DELIMITER $$
CREATE  PROCEDURE `adminGetOtherLoans`(IN _startIndex INT,IN _fetchRecords INT,IN _searchString VARCHAR(200),IN _serviceIds VARCHAR(200),IN _serviceTypeId INT,IN _userId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	DECLARE WhereSearchStringQuery TEXT DEFAULT "";
    DECLARE serviceQuery TEXT DEFAULT "";
    SET @startIndexQuery = "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
	SET @WhereSearchStringQuery = "";
    IF _searchString !="" THEN 
		SET @WhereSearchStringQuery =CONCAT_WS(''," AND (customerotherloans.fullName LIKE '%",_searchString,"%' OR customerotherloans.contactNo LIKE '%",_searchString,"%')" );            
	END IF; 
	SET @serviceQuery = "";
    IF _serviceIds !="" THEN 
		SET @serviceQuery = CONCAT_WS(''," AND customerotherloans.serviceId IN (",_serviceIds,")");        
	END IF; 
    IF _userId > 0 THEN
		SET @serviceQuery = CONCAT_WS('',@serviceQuery," AND customerotherloans.userId = ",_userId);
	END IF;
    SET @sqlQuery = "";
    SET @sqlQueryCount = "";
    SET @sqlQuery = CONCAT_WS(''," SELECT customerotherloans.*,employmenttypes.name as employmentType,servicetypes.name as serviceType,services.name as serviceName FROM customerotherloans LEFT JOIN employmenttypes ON customerotherloans.employmentTypeId = employmenttypes.id LEFT JOIN servicetypes ON customerotherloans.serviceTypeId = servicetypes.id LEFT JOIN services ON customerotherloans.serviceId = services.id WHERE customerotherloans.isDelete = 0 AND customerotherloans.serviceTypeId = ",_serviceTypeId,"",@WhereSearchStringQuery,@serviceQuery," ORDER BY customerotherloans.id DESC ",@StartIndexQuery);
	SET @sqlQueryCount = CONCAT_WS(''," SELECT COUNT(customerotherloans.id) as totalCount FROM customerotherloans LEFT JOIN employmenttypes ON customerotherloans.employmentTypeId = employmenttypes.id LEFT JOIN servicetypes ON customerotherloans.serviceTypeId = servicetypes.id LEFT JOIN services ON customerotherloans.serviceId = services.id WHERE customerotherloans.isDelete = 0 AND customerotherloans.serviceTypeId = ",_serviceTypeId,"",@WhereSearchStringQuery,@serviceQuery);
    PREPARE countStmt FROM @sqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
	PREPARE stmt FROM @sqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPageList`()
BEGIN
	SELECT * FROM pages;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPartnerById`(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 partnerAddressLine1
	, partneraddress.addressLine2 as partnerAddressLine2, partneraddress.pincode as partnerPincode, 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,designations.name as designation,professiontypes.name as professionType
    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
    LEFT JOIN designations ON partners.designationId = designations.id
    LEFT JOIN professiontypes ON professiontypes.id = partners.professionTypeId
    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 partnercustomers 
    INNER JOIN customers ON customers.id = partnercustomers.customerId
    INNER JOIN users ON users.id = customers.userId
	WHERE partnercustomers.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 partnerbankdetails.id as partnerBankDetailId,partnerbankdetails.bankId,partnerbankdetails.accountHolderName,partnerbankdetails.accountNo,partnerbankdetails.ifscCode,banks.name as bankName FROM partnerbankdetails LEFT JOIN banks ON partnerbankdetails.bankId = banks.id WHERE partnerId = _partnerId;

	SELECT partnercommission.commission as PendingCommission,partnercommissionhistory.* FROM partnercommissionhistory INNER JOIN partnercommission ON partnercommission.id = partnercommissionhistory.partnerCommissionId WHERE partnercommission.partnerId = _partnerId;

	SELECT roles.name as parentRole,p1.fullName as parentPartner,p1.contactNo as parentContactNo,p1.permanentCode as parentCode,p2.id as parentParentPartnerId,r1.name as parentParentRole,p2.fullName as parentParentPartnerName,
p2.contactNo as parentParentPartnerContactNo,p2.permanentCode as parentParentCode  FROM partners as p1 LEFT JOIN partners as p2 ON p1.parentPartnerId = p2.id 
LEFT JOIN userroles ON userroles.userId = p1.userId LEFT JOIN userroles u2 ON u2.userId = p2.userId
LEFT JOIN roles ON roles.id = userroles.roleId
LEFT JOIN roles r1 ON r1.id = u2.roleId
WHERE p1.id = (SELECT parentPartnerId FROM partners WHERE id = _partnerId);

 SELECT orders.*,products.name as productName,orderstatuses.status FROM orders INNER JOIN products ON orders.productId = products.id INNER JOIN orderstatuses ON  orderstatuses.id = orders.orderStatusId WHERE orders.userId IN (SELECT partners.userId FROM partners WHERE partners.id = _partnerId);

 SELECT leads.*,leads.id as leadId,services.name as serviceName, 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,partners.fullName as partnerName,partners.contactNo as partnerContactNo
					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
                    LEFT JOIN partners ON partners.id = leads.assignToPartnerId
					WHERE leads.createdBy IN  (SELECT userId FROM partners WHERE id = _partnerId) AND leads.isDelete = 0;
                    
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPartnerDetail`(IN _roleId INT, IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	SELECT partners.*, users.email, users.countryCode, users.profilePicUrl, users.isDisabled, roles.id as roleId, roles.name as roleName, companytypes.name as companyType
	, professiontypes.name as professionType, designations.name as designation, partneraddress.id as addressId, partneraddress.label, partneraddress.addressTypeId
	, partneraddress.label, partneraddress.addressLine1, partneraddress.addressLine2, partneraddress.pincode, partneraddress.cityId, addresstypes.name as addressType
	, cities.name as cityName
	, pp.id as networkParentPartnerId, pp.fullName as networkParentPartnerFullName, pp.permanentCode as networkParentPartnerPermanentCode
	, ptp.id as teamParentPartnerId, ptp.fullName as teamParentPartnerFullName, ptp.permanentCode as teamParentPartnerPermanentCode
	, partnereducations.id as partnerEducationId, partnereducations.educationTypeId as partnerEducationTypeId, partnereducations.resume
	, partnereducations.instituteName, partnereducations.passingYear, educationtypes.name as educationType
	, partnerdocuments.id as partnerDocumentId, partnerdocuments.documentId, partnerdocuments.url, documentmasters.name as documentName
	FROM partners
	INNER JOIN users ON users.id = partners.userId
	INNER JOIN userroles ON userroles.userId = partners.userId
	INNER JOIN roles ON roles.id = userroles.roleId
	LEFT JOIN professiontypes ON professiontypes.id = partners.professionTypeId
	LEFT JOIN companytypes ON companytypes.id = partners.companyTypeId
	LEFT JOIN designations ON designations.id = partners.designationId
	LEFT JOIN partneraddress ON partneraddress.partnerId = partners.id
	LEFT JOIN addresstypes ON addresstypes.id = partneraddress.addressTypeId
	LEFT JOIN cities ON cities.id = partneraddress.cityId
	LEFT JOIN partnernetworks ON partnernetworks.networkPartnerId = partners.id
	LEFT JOIN partners pp ON pp.id = partnernetworks.partnerId
	LEFT JOIN partnerteams ON partnerteams.teamPartnerId = partners.id
	LEFT JOIN partners ptp ON ptp.id = partnerteams.partnerId
	LEFT JOIN partnereducations ON partnereducations.partnerId = partners.id
	LEFT JOIN educationtypes ON educationtypes.id = partnereducations.educationTypeId
	LEFT JOIN partnerdocuments ON partnerdocuments.partnerId = partners.id
	LEFT JOIN documentmasters ON documentmasters.id = partnerdocuments.documentId
	WHERE roles.id = _roleId LIMIT _fetchRecords OFFSET _startIndex;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPartnerForAssignLead`()
BEGIN
	SELECT id,fullName,contactNo FROM partners WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPartnerList`(IN _startIndex INT,IN _fetchRecords INT,IN _roleIds VARCHAR(40))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE RoleQuery TEXT DEFAULT "";
    SET @RoleQuery = "";
    IF _startIndex >= 0 && _fetchRecords >0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
   
		
	IF _roleIds !="" THEN 
		SET @RoleQuery = CONCAT_WS(''," AND userroles.roleId IN (",_roleIds,")");        
	END IF; 
     SET @SqlQueryCount = "";
     SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(partners.id) as totalCount FROM partners INNER JOIN users ON partners.userId = users.id INNER JOIN userroles ON userroles.userId = users.id INNER JOIN roles ON roles.id = userroles.roleId WHERE users.isDelete = 0",@RoleQuery);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT partners.*, roles.id as roleId, roles.name as roleName FROM partners INNER JOIN users ON partners.userId = users.id INNER JOIN userroles ON userroles.userId = users.id INNER JOIN roles ON roles.id = userroles.roleId WHERE users.isDelete = 0',@RoleQuery," ORDER BY roles.id ",@StartIndexQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
   PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPartnerPayout`(IN _startIndex INT,IN _fetchRecords INT,IN _searchString TEXT)
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 _searchString != '' THEN
		SET @filterQuery =CONCAT_WS('',@filterQuery," AND (partners.fullName LIKE '%",_searchString,"%' OR partners.contactNo LIKE '%",_searchString,"%')");
    END IF;
    SET @SqlQueryCount = '';
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(partnercommission.id) as totalCount  FROM partnercommission INNER JOIN partners ON partnercommission.partnerId = partners.id WHERE partnercommission.id > 0 ",@filterQuery);
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @SqlQuery = '';
	SET @SqlQuery = CONCAT_WS(''," SELECT partnercommission.*,partners.fullName,partners.contactNo FROM partnercommission INNER JOIN partners ON partnercommission.partnerId = partners.id WHERE partnercommission.id > 0 ",@filterQuery,@startIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetpartnerPayoutHistory`(In _partnerIds VARCHAR(200),IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200),IN _serviceId INT)
BEGIN
	DECLARE filterQuery  TEXT DEFAULT '';
    SET @filterQuery = '';
	  IF(_fromDate != '') THEN 
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(partnercommissionhistory.releaseDate) >= '",_fromDate,"'");
	END IF;
    IF(_toDate != '') THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND DATE(partnercommissionhistory.releaseDate) <= '",_toDate,"'");
	END IF;
    IF(_serviceId > 0) THEN
		SET @filterQuery = CONCAT_WS('',@filterQuery," AND services.id = ",_serviceId,"");
    END IF;
	SET  @SqlQuery = CONCAT_WS('',"SELECT partnercommissionhistory.*,partnerinvoice.url,customerloandetail.amountDisbursed,customers.fullName,customers.contactNo,services.id as serviceId,services.name as serviceName,banks.id as bankId,banks.name as bankName 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
    LEFT JOIN banks ON customerloandetail.bankId = banks.id
    WHERE partnercommissionhistory.partnerId IN (",_partnerIds,")",@filterQuery," ORDER BY partnercommissionhistory.id DESC");
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPendingApplication`(IN _startIndex INT,IN _fetchrecords INT)
BEGIN
    DECLARE sqlQuery TEXT DEFAULT '';
	SELECT COUNT(customerloans.id) as totalPendingApplication FROM customerloans INNER JOIN services ON services.id = customerloans.serviceId INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN loanstatuses ON loanstatuses.id = customerloans.statusId WHERE customerloans.statusId = 1;
    
    SET @sqlQuery = '';
    SET @sqlQuery = CONCAT_WS(''," SELECT customerloans.*,services.name as serviceName,customers.fullName,customers.contactNo FROM  customerloans INNER JOIN services ON services.id = customerloans.serviceId INNER JOIN customers ON customers.id = customerloans.customerId
    INNER JOIN loanstatuses ON loanstatuses.id = customerloans.statusId WHERE customerloans.statusId = 1"," ORDER BY id DESC");
    
    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 `adminGetPersonalLoans`(IN _serviceId 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 loanQuery TEXT DEFAULT "";
    
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
	END;
	START TRANSACTION;
    BEGIN
		DECLARE cur_customerloan CURSOR FOR SELECT customerloans.id FROM customerloans 
											WHERE customerloans.serviceId = _serviceId
                                            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 @loanQuery = "";
            SET @loanQuery = CONCAT_WS(' ',"SELECT customerloans.customerId FROM customerloans 
									LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
									LEFT JOIN services ON  services.id = customerloans.serviceId
                                    LEFT JOIN customerloanstatushistory ON customerloanstatushistory.customerloanId = customerloans.id
                                    LEFT JOIN loancompletescreenhistory ON loancompletescreenhistory.customerloanId = customerloans.id
									WHERE customerloans.serviceId = _serviceId");
			IF _startDate IS NOT NULL THEN
				SET @loanQuery = CONCAT_WS('', @loanQuery, ", AND DATE(createdDate) <= DATE('",_startDate,"') AND DATE(createdDate) >= DATE('",_endDate,"')");
			END IF;
            
            IF _statusId <0 THEN
				SET @loanQuery = CONCAT_WS('', @loanQuery, ", AND loancompletescreenhistory.isCompleted=0");
            END IF;
			IF _statusId >0 THEN
				SET @loanQuery = CONCAT_WS('', @loanQuery, ", LIMIT ",_fetchRecords," OFFSET ",_startIndex);
            END IF;
            
            SET @loanQuery = CONCAT_WS('', @loanQuery, ", AND customerloanstatushistory.loanStatusId=",_statusId);*/
		
			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,loanstatuses.status FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            INNER JOIN loanstatuses ON loanstatuses.id = customerloans.statuseId
            WHERE customerloans.id IN(", @customerLoanIds,") ORDER BY customerloans.id DESC");
			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(", _customerLoanId ,")");
			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_WS(' ', "select partners.permanentCode,partners.fullName,partners.contactNo from partnerscustomerloans
			INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
			INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
			WHERE partnerscustomerloans.customerLoanId(", @customerLoanIds,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
              SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloanoffers.*,banks.name as bankName FROM customerloanoffers INNER JOIN banks ON customerloanoffers.bankId = banks.id WHERE customerloanoffers.isDelete = 0 AND customerloanoffers.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloandetail.*,banks.name as bankName FROM customerloandetail INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloandetail.isDelete = 0 AND customerloandetail.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerLoanId,reason FROM customerloanrejectionreason WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
              SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT reason,customerLoanId,description FROM reasons WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
        END IF;
    END;
    COMMIT;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPersonalLoansByFilter`(IN _customerLoanId TEXT)
BEGIN
	SET @sql = CONCAT('SELECT users.id as userId, users.email, users.countryCode, users.password, users.profilePicUrl, users.isDisabled, userroles.roleId as roleId, customers.*
			, maritalstatuses.status as maritalStatus
            FROM users 
            INNER JOIN userroles ON userroles.userId = users.id 
            INNER JOIN customers ON customers.userId = users.id 
            LEFT JOIN maritalstatuses ON maritalstatuses.id = customers.maritalStatusId
            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(', _customerLoanId, ')) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2)');
	PREPARE stmt FROM @sql;
	EXECUTE stmt;
	DEALLOCATE PREPARE stmt;
    
    SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloans.*, employmenttypes.name as employmentType,services.displayName as displayName, users.fullName as rmFullName,loanstatuses.status,tenure.name as tenure FROM customerloans 
            LEFT JOIN employmenttypes ON  employmenttypes.id = customerloans.employmentTypeId
            LEFT JOIN users ON users.id = customerloans.assignRMId
            LEFT JOIN services ON  services.id = customerloans.serviceId
            LEFT JOIN loanstatuses ON loanstatuses.id = customerloans.statusId
            LEFT JOIN tenure ON customerloans.tenureId = tenure.id
            WHERE customerloans.id IN(", _customerLoanId,") ORDER BY customerloans.id DESC");
			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(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM customerloanspouses WHERE customerloanId IN(", _customerLoanId,")");
			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(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT customerloanreferences.*,customerreferenceaddresses.id as customerreferenceaddressId,customerreferenceaddresses.label,customerreferenceaddresses.addressLine1,customerreferenceaddresses.addressLine2,customerreferenceaddresses.pincode,customerreferenceaddresses.cityId,customerreferenceaddresses.city,customerreferenceaddresses.district,customerreferenceaddresses.state FROM customerloanreferences LEFT JOIN customerreferenceaddresses ON  customerreferenceaddresses.customerLoanReferenceId = customerloanreferences.id WHERE customerloanId IN(", _customerLoanId ,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "SELECT * FROM loancompletescreenhistory WHERE customerloanId IN(", _customerLoanId ,")");
			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(", _customerLoanId,")  ORDER BY loanstatuses.displayOrder");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery = "";
            SET @getQuery = CONCAT_WS(' ', "select partners.id,partners.permanentCode,partners.fullName,partners.contactNo,partners.parentPartnerId, partnerscustomerloans.customerLoanId,partners.gender,roles.name as roleName from partnerscustomerloans
			INNER JOIN customerloans ON customerloans.id = partnerscustomerloans.customerLoanId
			INNER JOIN partners ON partners.id = partnerscustomerloans.partnerId
            INNER JOIN userroles ON userroles.userId = partners.userId
            INNER JOIN roles ON userroles.roleId = roles.id
			WHERE partnerscustomerloans.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;                 
            
               SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloanoffers.*,banks.name as bankName FROM customerloanoffers INNER JOIN banks ON customerloanoffers.bankId = banks.id WHERE customerloanoffers.isDelete = 0 AND customerloanoffers.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerloandetail.*,banks.name as bankName FROM customerloandetail INNER JOIN banks ON customerloandetail.bankId = banks.id WHERE customerloandetail.isDelete = 0 AND customerloandetail.customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
            SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customerLoanId,reason FROM customerloanrejectionreason WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
              SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT reason,customerLoanId,description FROM reasons WHERE isDelete = 0 AND customerLoanId IN(", _customerLoanId,")");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
			SET @getQuery ="";
            SET @getQuery = CONCAT_WS(''," SELECT customeraddresses.*  FROM users  INNER JOIN userroles ON userroles.userId = users.id  
            INNER JOIN customers ON customers.userId = users.id   
            INNER JOIN customeraddresses ON customeraddresses.customerId = customers.id
            WHERE customers.id IN (	SELECT customerloans.customerId FROM customerloans 
					WHERE customerloans.id IN(", _customerLoanId, ")) AND users.isDelete = 0 AND users.isActive = 1 AND userroles.roleId IN(2) AND customeraddresses.addressTypeId = 5");
			PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
           SET @getQuery ="";
            SET @getQuery = CONCAT_WS('','SELECT customerloantransferpropertydetails.*,banks.name as bankName FROM customerloantransferpropertydetails INNER JOIN banks ON customerloantransferpropertydetails.bankId = banks.id WHERE customerLoanId IN(',_customerLoanId,')');
            PREPARE stmt FROM @getQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            
		END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetProduct`(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",@filterQuery);
    PREPARE countStmt FROM @sqlQueryCount;
	EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @sqlQuery = '';
    SET @sqlQuery = CONCAT_WS(''," SELECT * FROM products WHERE isDelete = 0",@filterQuery," ORDER BY id DESC",@startIndexQuery);
    PREPARE stmt FROM @sqlQuery;
	EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetPropertyTypes`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(propertytypes.id) as totalCount FROM propertytypes 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 propertytypes WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetResidentTypes`(IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(residenttypes.id) as totalCount FROM residenttypes 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 residenttypes WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetRewardCoin`(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(rewardcoin.id) as totalCount FROM rewardcoin");
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT rewardcoin.*,rewardtypes.name as rewardType FROM rewardcoin INNER JOIN rewardtypes ON rewardcoin.rewardTypeId = rewardtypes.id',@StartIndexQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    
   PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetRewardType`()
BEGIN
	SELECT * FROM rewardTypes WHERE isDelete = 0;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetRM`(IN _startIndex INT, IN _fetchRecords INT,IN _searchString VARCHAR(200))
BEGIN
	DECLARE WhereSearchStringQuery TEXT DEFAULT "";
    DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    SET @WhereSearchStringQuery = "";
	IF _searchString != "" THEN
		SET @WhereSearchStringQuery =CONCAT_WS(''," AND (users.fullName LIKE '%",_searchString,"%' OR users.contactNo LIKE '%",_searchString,"%' OR users.email LIKE '%",_searchString,"%')" );
	END IF;
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(users.id) as totalCount FROM users INNER JOIN userroles ON userroles.userId = users.id INNER JOIN roles ON roles.id = userroles.roleId WHERE userroles.roleId IN(7)",@WhereSearchStringQuery);
    SET @SqlQuery = "";
    SET @SqlQuery = CONCAT_WS(''," SELECT users.*, 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 userroles.roleId IN(7)",@WhereSearchStringQuery,"ORDER BY users.id DESC");
	PREPARE countstmt FROM @SqlQueryCount;
    EXECUTE countstmt;
    DEALLOCATE PREPARE countstmt;
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetRoles`()
BEGIN
	SELECT * FROM roles;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetServiceEmploymentTypes`(IN startIndex INT,IN fetchRecords INT,IN _serviceId INT)
BEGIN
	IF _serviceId > 0 THEN
		SELECT servicesemploymenttypes.*,services.displayName as serviceName,employmenttypes.name as employmentType FROM servicesemploymenttypes 
		INNER JOIN services ON servicesemploymenttypes.serviceId = services.id
		INNER JOIN employmenttypes ON servicesemploymenttypes.employmentTypeId = employmenttypes.id
        WHERE servicesemploymenttypes.serviceId = _serviceId
		ORDER BY id DESC;
	ELSE
		SELECT servicesemploymenttypes.*,services.displayName as serviceName,employmenttypes.name as employmentType FROM servicesemploymenttypes 
		INNER JOIN services ON servicesemploymenttypes.serviceId = services.id
		INNER JOIN employmenttypes ON servicesemploymenttypes.employmentTypeId = employmenttypes.id
		ORDER BY id DESC;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetServices`(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(services.id) as totalCount FROM services INNER JOIN servicetypes ON services.serviceTypeId = servicetypes.id;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT services.*,servicetypes.name as serviceTypeName FROM services INNER JOIN servicetypes ON services.serviceTypeId = servicetypes.id"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetServiceTypeDocuments`(IN _startIndex INT, IN _fetchRecords INT,IN _serviceId INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SQlQueryCount TEXT DEFAULT "";
    DECLARE FilterQuery TEXT DEFAULT "";
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    SET @FilterQuery = "";
    IF _serviceId > 0 THEN 
		SET @FilterQuery = CONCAT_WS(''," AND servicetypedocuments.serviceId = ",_serviceId);
    END IF;
	SET @SqlQueryCount = CONCAT_WS('',"SELECT COUNT(servicetypedocuments.id) as totalCount
	FROM servicetypedocuments 
	INNER JOIN services ON services.id = servicetypedocuments.serviceId
	INNER JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId LEFT JOIN employmenttypes ON employmenttypes.id = servicetypedocuments.employmentTypeId WHERE servicetypedocuments.isDelete = 0 ",@FilterQuery);
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
	SET @SqlQuery = CONCAT_WS('', "SELECT servicetypedocuments.*, services.displayName as serviceDisplayName, services.name as servicesName, documentmasters.name as documentName,documentmasters.maxSize,employmenttypes.name as employmentType
	FROM servicetypedocuments 
	INNER JOIN services ON services.id = servicetypedocuments.serviceId
	INNER JOIN documentmasters ON documentmasters.id = servicetypedocuments.documentId 
    LEFT JOIN employmenttypes ON employmenttypes.id = servicetypedocuments.employmentTypeId WHERE servicetypedocuments.isDelete = 0 ",@FilterQuery," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetServiceTypes`(IN _startIndex INT, IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	SET @SqlQueryCount = "";
	SELECT COUNT(servicetypes.id) as totalCount FROM servicetypes 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 servicetypes WHERE isDelete = 0"," ORDER BY id desc ", @StartIndexQuery);
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetTenure`()
BEGIN
	SELECT * FROM tenure;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetTopPerformers`(IN _startIndex INT,IN _fetchRecords INT, IN _selectedGap VARCHAR(200))
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    DECLARE sqlQueryCount TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE startIndexQuery TEXT DEFAULT '';
    
    SET @filterQuery = '';
	IF (_selectedGap = 'month') THEN
    SET @filterQuery = CONCAT_WS(''," AND MONTH(customerloandetail.createdDate) = MONTH(CURRENT_TIMESTAMP()) ");
    END IF;
    IF (_selectedGap = 'previousMonth') THEN
    SET @filterQuery = CONCAT_WS(''," AND MONTH(customerloandetail.createdDate) = MONTH(CURRENT_TIMESTAMP()) - 1 ");
    END IF;
    IF (_selectedGap = 'previous6Month') THEN
    SET @filterQuery = CONCAT_WS(''," AND customerloandetail.createdDate > DATE_SUB(now(),INTERVAL 6 MONTH) ");
    END IF;
    IF (_selectedGap = 'year') THEN
    SET @filterQuery = CONCAT_WS(''," AND  YEAR(customerloandetail.createdDate) = YEAR(CURRENT_TIMESTAMP()) ");
    END IF;
    SET @startIndexQuery = '';
    IF _startIndex >=0 AND _fetchRecords > 0 THEN
		SET @startIndexQuery = CONCAT_WS(''," limit ",_fetchrecords," OFFSET ", _startIndex);
    END IF;
    SET @sqlQueryCount = '';
    SET @sqlQueryCount = CONCAT_WS('',"SELECT COUNT(DISTINCT(partnerscustomerloans.partnerId)) as totalCount
    FROM customerloans 
    INNER JOIN partnerscustomerloans ON partnerscustomerloans.customerLoanId = customerloans.id 
    INNER JOIN customerloandetail ON customerloandetail.customerLoanId = customerloans.id   
    INNER JOIN partners ON partnerscustomerloans.partnerId = partners.id
   	INNER JOIN users ON partners.userId = users.id
    INNER JOIN roles ON roles.id = users.currentRoleId
    WHERE (customerloans.statusId = 8 OR  customerloans.statusId = 15)",@filterQuery);
   
   SET @sqlQuery = '';
   SET @sqlQuery = CONCAT_WS(''," SELECT SUM(customerloandetail.amountDisbursed) as totalLoanAmount,partnerscustomerloans.partnerId,partners.fullName,partners.contactNo,roles.name as roleName
    FROM customerloans 
    INNER JOIN partnerscustomerloans ON partnerscustomerloans.customerLoanId = customerloans.id 
    INNER JOIN customerloandetail ON customerloandetail.customerLoanId = customerloans.id   
    INNER JOIN partners ON partnerscustomerloans.partnerId = partners.id 
	INNER JOIN users ON partners.userId = users.id
    INNER JOIN roles ON roles.id = users.currentRoleId
    WHERE (customerloans.statusId = 8 OR  customerloans.statusId = 15) ",@filterQuery," GROUP BY partnerscustomerloans.partnerId,roles.name ORDER BY SUM(customerloandetail.amountDisbursed) 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 `adminGetTrainingAssignUsers`(IN _startIndex INT,IN _fetchRecord INT,IN _trainingId INT,IN _roleIds VARCHAR(200))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
	DECLARE StartIndexQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT ''; 
	 SET @filterQuery = '';
    IF _roleIds != '' THEN
		SET @filterQuery = CONCAT_WS('',' AND r.id IN (',_roleIds,')');
	END IF;
    SET @SqlQueryCount = '';
    SET @SqlQueryCount = CONCAT_WS('','SELECT COUNT(assignuserstraining.id) as totalCount FROM assignuserstraining LEFT JOIN partners p ON assignuserstraining.partnerId = p.id LEFT JOIN users u ON p.userId = u.id LEFT JOIN userroles ur ON u.id = ur.userId LEFT JOIN roles r ON ur.roleId = r.id WHERE assignuserstraining.trainingId = ',_trainingId,@filterQuery);
    PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    SET @startIndexQuery = '';
    IF _startIndex >= 0 AND _fetchRecord > 0 THEN
		SET @StartIndexQuery = CONCAT_WS(''," LIMIT ",_fetchRecord, " OFFSET ", _startIndex);
    END IF;
   
    SET SqlQuery = "";
    SET @SqlQuery = CONCAT_WS(''," SELECT assignuserstraining.*,p.fullName,p.contactNo,r.id as roleId, r.name as roleName FROM assignuserstraining LEFT JOIN partners p ON assignuserstraining.partnerId = p.id LEFT JOIN users u ON p.userId = u.id LEFT JOIN userroles ur ON u.id = ur.userId LEFT JOIN roles r ON ur.roleId = r.id WHERE assignuserstraining.trainingId = ",_trainingId,@filterQuery, @StartIndexQuery);
	
    PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetTrainingCategories`()
BEGIN
	SET @SqlQuery = CONCAT_WS('', "SELECT * FROM triningcategories "," ORDER BY id desc ");
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetTrainings`(IN _startIndex INT, IN _fetchRecords INT,IN _searchString VARCHAR(200),IN _categoryIds VARCHAR(50))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
	DECLARE WhereSearchStringQuery TEXT DEFAULT "";
    DECLARE CategoryQuery TEXT DEFAULT "";
   
	IF _startIndex >= 0 AND _fetchRecords>0 THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
	SET @WhereSearchStringQuery = "";
    IF _searchString !="" THEN 
		SET @WhereSearchStringQuery =CONCAT_WS(''," AND (t.title LIKE '%",_searchString,"%' OR t.fileName LIKE '%",_searchString,"%')" );            
	END IF; 
	SET @CategoryQuery = "";
    IF _categoryIds !="" THEN 
		SET @CategoryQuery = CONCAT_WS(''," AND t.trainingCategoryId IN (",_categoryIds,")");        
	END IF; 
	/*SET @AssignRoleIdQuery = "";
     IF _assignRoleIds !="" THEN 
                SET @AssignRoleIdQuery = CONCAT_WS(''," AND t.assignRoleId IN (",_assignRoleIds,")");        
	END IF;*/ 
    SET @SqlQueryCount = "";
    SET @SqlQueryCount = CONCAT_WS('', "SELECT COUNT(t.id) as totalCount FROM trainings t LEFT JOIN triningcategories tc ON t.trainingCategoryId = tc.id  WHERE t.isDelete = 0 ",@WhereSearchStringQuery,@CategoryQuery);
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('', "SELECT t.*,tc.name as categoryName FROM trainings t LEFT JOIN triningcategories tc ON t.trainingCategoryId = tc.id WHERE t.isDelete = 0 ",@WhereSearchStringQuery,@CategoryQuery," ORDER BY t.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 `adminGetUserPagePermission`(IN _userId INT)
BEGIN
	SELECT userpages.*, pages.name FROM userpages INNER JOIN pages on pages.id = userpages.pageId WHERE userpages.userId = _userId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetUsers`(IN _startIndex INT, IN _fetchRecords INT,IN _roleIds VARCHAR(50),IN _searchString VARCHAR(200))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE RoleQuery TEXT DEFAULT "";
    SET @RoleQuery = "";
	IF _roleIds !="" THEN 
		SET @RoleQuery = CONCAT_WS(''," AND userroles.roleId IN (",_roleIds,")");        
	END IF; 
    IF _searchString != '' THEN
			SET @RoleQuery =CONCAT_WS('',@RoleQuery," AND (users.fullName LIKE '%",_searchString,"%' OR users.contactNo LIKE '%",_searchString,"%')" );
	END IF;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT users.*, 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.id != 0',@RoleQuery," ORDER BY users.id DESC");
	PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminGetUsersScratchCards`(IN _startIndex INT, IN _fetchRecords INT,IN _searchString VARCHAR(200),IN _roleId INT,IN _rewardTypeId INT,IN _isScratched BOOLEAN,IN _fromDate VARCHAR(200),IN _toDate VARCHAR(200))
BEGIN
	DECLARE SqlQuery TEXT DEFAULT '';
    DECLARE SqlQueryCount TEXT DEFAULT '';
    DECLARE filterQuery TEXT DEFAULT '';
    DECLARE StartIndexQuery TEXT DEFAULT '';
    SET @SqlQuery = '';
    SET @SqlQueryCount = '';
    SET @filterQuery = '';
    SET @SqlQuery = '';
    SET @StartIndexQuery = '';
    IF _startIndex >= 0 AND _fetchRecords > 0  THEN
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
	END IF;
    IF _searchString != '' THEN 
		SET @filterQuery =CONCAT_WS('',@filterQuery," AND (users.fullName LIKE '%",_searchString,"%' OR users.contactNo LIKE '%",_searchString,"%')");
    END IF;
    IF _roleId > 0 THEN 
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND userroles.roleId = ",_roleId);
    END IF;
    IF _rewardTypeId > 0 THEN
    	SET @filterQuery = CONCAT_Ws('',@filterQuery," AND userscratchcards.rewardType = ",_rewardTypeId);
    END IF;
    IF _isScratched THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND userscratchcards.isScratched = ",_isScratched);
    END IF;
    IF _fromDate THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND userscratchcards.createdDate >= '",_fromDate,"'");
    END IF;
    IF _toDate THEN
		SET @filterQuery = CONCAT_Ws('',@filterQuery," AND userscratchcards.createdDate <= '",_toDate,"'");
    END IF;
    SET @SqlQueryCount = CONCAT_WS(''," SELECT COUNT(userscratchcards.id) as totalCount FROM userscratchcards INNER JOIN users ON users.id = userscratchcards.userId INNER JOIN rewardtypes ON rewardtypes.id = userscratchcards.rewardType INNER JOIN userroles ON userroles.userId = userscratchcards.userId INNER JOIN roles ON roles.id  = userroles.roleId WHERE userscratchcards.isDelete = 0",@filterQuery);
    SET @SqlQuery = CONCAT_WS(''," SELECT userscratchcards.*,userroles.roleId,rewardtypes.name as rewardType,roles.name as roleName,users.fullName,users.contactNo FROM userscratchcards INNER JOIN users ON users.id = userscratchcards.userId INNER JOIN rewardtypes ON rewardtypes.id = userscratchcards.rewardType INNER JOIN userroles ON userroles.userId = userscratchcards.userId INNER JOIN roles ON roles.id  = userroles.roleId WHERE userscratchcards.isDelete = 0",@filterQuery," 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 `adminGetVisitingCards`(IN _roleIds VARCHAR(100),IN _startIndex INT,IN _fetchRecords INT)
BEGIN
	DECLARE SqlQuery TEXT DEFAULT "";
    DECLARE RoleQuery TEXT DEFAULT "";
    DECLARE SqlQueryCount TEXT DEFAULT "";
    DECLARE StartIndexQuery TEXT DEFAULT "";
    SET @RoleQuery = "";
	IF _roleIds !="" THEN 
		SET @RoleQuery = CONCAT_WS(''," AND r.roleId IN (",_roleIds,")");        
	END IF;
    SET @SqlQueryCount = "";
	SET @SqlQueryCount = CONCAT_WS(''," SELECT count(DISTINCT(v.id)) as totalCount FROM visitingcards v INNER JOIN rolesvisitingcards r ON v.id = r.visitingCardId WHERE v.isDelete = 0",@RoleQuery);
    SET @StartIndexQuery = "";
	PREPARE countStmt FROM @SqlQueryCount;
    EXECUTE countStmt;
    DEALLOCATE PREPARE countStmt;
    IF _startIndex >= 0 AND _fetchRecords >0 THEN 
		SET @StartIndexQuery = CONCAT_WS('', " LIMIT ",_fetchRecords, " OFFSET ", _startIndex);
    END IF;
    SET @SqlQuery = "";
	SET @SqlQuery = CONCAT_WS('',' SELECT v.*,GROUP_CONCAT(DISTINCT r.roleId SEPARATOR ",") AS roleIds FROM visitingcards v INNER JOIN rolesvisitingcards r ON v.id = r.visitingCardId WHERE v.isDelete = 0 ',@RoleQuery," GROUP BY v.id ORDER BY v.id",@StartIndexQuery);
  PREPARE stmt FROM @SqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertAddressType`(IN _name VARCHAR(100),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;
			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
			INSERT INTO addresstypes (name,description,createdBy,modifiedBy) VALUES (_name,_description,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO addresstypes (name,description,createdBy,modifiedBy) VALUES (_name,_description,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBadges`(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;
			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
			INSERT INTO badges (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO badges (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBankLoan`(IN _bankId INT,IN _serviceId INT,IN _loanName VARCHAR(100),IN _userId INT)
BEGIN
	INSERT INTO bankloans (bankId,serviceId,loanName,createdBy,modifiedBy) VALUES (_bankId,_serviceId,_loanName,_userId,_userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBanks`(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;
			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
			INSERT INTO banks (name,description,headquarters,bankCode,minAge,maxAge,bankLogo,createdBy,modifiedBy) VALUES (_name,_description,_headquarters,_bankCode,_minAge,_maxAge,_bankLogo,_userId,_userId);
			SELECT LAST_INSERT_ID() as bankId;
        END IF;
	ELSE
		INSERT INTO banks (name,description,headquarters,bankCode,minAge,maxAge,bankLogo,createdBy,modifiedBy) VALUES (_name,_description,_headquarters,_bankCode,_minAge,_maxAge,_bankLogo,_userId,_userId);
		SELECT LAST_INSERT_ID() as bankId;
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBusinessAnnualProfit`(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;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessAnnualProfit: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessAnnualProfit;
					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
			INSERT INTO businessannualprofits (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO businessannualprofits (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBusinessAnnualSale`(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;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBusinessAnnualSale: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBusinessAnnualSale;
					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
			INSERT INTO businessannualsales (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO businessannualsales (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBusinessExperience`(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 businessexperience) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM businessexperience WHERE isDelete =0;
			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
			INSERT INTO businessexperience (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO businessexperience (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertBusinessNature`(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;
			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
			INSERT INTO businessnatures (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO businessnatures (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertCoApplicantRelation`(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 coapplicantrelations) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM coapplicantrelations WHERE isDelete =0;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getCoApplicantRelation: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getCoApplicantRelation;
					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
			INSERT INTO coapplicantrelations (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO coapplicantrelations (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertCustomer`(IN _customerId INT,IN _customerUserId INT,IN _temporyCode VARCHAR(45),IN _permanentCode VARCHAR(45),IN _fullName VARCHAR(200),IN _birthDate datetime,IN _gender VARCHAR(15),IN _contactNo VARCHAR(15),IN _email VARCHAR(200),IN _alterNativeContactNo VARCHAR(15),IN _partnerId INT,IN _panCardNo VARCHAR(20),IN _aadharCardNo VARCHAR(20),IN _maritalStatusId INT,IN _userId INT,IN _customerAddressId INT,IN _label TEXT,IN _addressLine1 TEXT,IN _addressLine2 TEXT,IN _cityId INT,IN _city VARCHAR(100),IN _district VARCHAR(100),IN _state VARCHAR(100),IN _profilePicUrl TEXT,IN _pincode VARCHAR(20),IN _cibilScore decimal(15,2))
BEGIN
	DECLARE sqlQuery TEXT DEFAULT "";
    DECLARE userUpdateQuery TEXT DEFAULT "";
    DECLARE customerAddressQuery TEXT DEFAULT "";
    DECLARE finished INT DEFAULT 0;
    DECLARE _rewardCoin INT DEFAULT 0;
    DECLARE insertUserId INT DEFAULT 0;
    SET @sqlQuery = "";
    SET @userUpdateQuery = "";
     SET @customerAddressQuery = "";
	IF(_customerId > 0) THEN 
			SET @sqlQuery= CONCAT_WS(''," UPDATE customers SET temporaryCode = '",_temporyCode,"', fullName = '",_fullName,"',birthDate = '",_birthDate,"', gender = '",_gender,"', contactNo = '",_contactNo,"', panCardNo = '",_panCardNo,"', aadhaarCardNo = '",_aadharCardNo,"' ,maritalStatusId = ",_maritalStatusId,",modifiedBy = ",_userId," ,modifiedDate = '",CURRENT_TIMESTAMP(),"',currentRoleId = 2,cibilScore = ",_cibilScore,"");
			SET @userUpdateQuery = CONCAT_WS(''," UPDATE users SET fullName = '",_fullName,"', gender = '", _gender,"', contactNo = '",_contactNo,"',modifiedBy = ",_userId,",modifiedDate = '",CURRENT_TIMESTAMP(),"',currentRoleId = 2");
	ELSE 
		SET @sqlQuery = CONCAT_WS(''," INSERT INTO customers SET temporaryCode = '",_temporyCode,"', fullName = '",_fullName,"', birthDate = '",_birthDate,"', gender = '",_gender,"' ,contactNo = '",_contactNo,"', panCardNo = '",_panCardNo,"',aadhaarCardNo = '",_aadharCardNo,"', maritalStatusId = ",_maritalStatusId,",modifiedBy = ",_userId,",modifiedDate = '",CURRENT_TIMESTAMP() ,"',createdBy = ",_userId," ,createdDate = '",CURRENT_TIMESTAMP(),"',currentRoleId = 2,cibilScore = ",_cibilScore,"");
		SET @userUpdateQuery = CONCAT_WS(''," INSERT INTO users SET fullName = '",_fullName,"', gender = '", _gender,"', contactNo = '",_contactNo,"',modifiedBy = ",_userId,",modifiedDate = '",CURRENT_TIMESTAMP(), "', createdBy = ",_userId,",createdDate = '",CURRENT_TIMESTAMP(),"',countryCode = '+91',isDisabled = false,currentRoleId = 2");
	
    END IF;
		IF(_permanentCode != '') THEN
			SET @sqlQuery = CONCAT_WS('',@sqlQuery," , permanentCode = '",_permanentCode,"'");
		END IF;
		IF(_alterNativeContactNo != '') THEN
			SET @sqlQuery = CONCAT_WS('',@sqlQuery," , alterNativeContactNo = '",_alterNativeContactNo,"'");
		END IF;
		IF(_partnerId > 0) THEN
			SET @sqlQuery = CONCAT_WS('',@sqlQuery," ,partnerId = ",__partnerId);
		END IF;
		IF (_profilePicUrl != '') THEN
			SET @userUpdateQuery = CONCAT_WS('', @userUpdateQuery," , profilePicUrl = '",_profilePicUrl,"'");
		END IF;
		IF(_email != '') THEN
			SET @userUpdateQuery = CONCAT_WS('', @userUpdateQuery," , email = '",_email,"'");
		END IF;
        IF(_customerId > 0) THEN 
			SET @userUpdateQuery = CONCAT_WS('',@userUpdateQuery," WHERE id = ",_customerUserId);
        END IF;
        
		PREPARE userStmt FROM @userUpdateQuery;
        EXECUTE userStmt;
        DEALLOCATE PREPARE userStmt;
        IF(_customerUserId = 0) THEN
        SET _customerUserId = LAST_INSERT_ID();
        END IF;
		IF(_customerUserId > 0)THEN
			IF(_customerId = 0) THEN
				INSERT INTO userroles (userId,roleId,createdBy,modifiedBy) VALUES (_customerUserId,2,_userId,_userId);
				IF 	EXISTS(SELECT 1 FROM rewardcoin) THEN
				BEGIN
				DECLARE cur_checkexist cursor for select rewardCoin FROM rewardcoin WHERE isDelete =0 AND rewardTypeId = 2;
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
				OPEN cur_checkexist;
					SET @exist =0;
					getRewardCoin: LOOP
						FETCH cur_checkexist INTO _rewardCoin;
						IF finished = 1 THEN 
							LEAVE getRewardCoin;
						END IF;
						IF _rewardCoin THEN
							INSERT INTO userscratchcards(userId, value, createdBy, modifiedBy,rewardType) VALUES(_customerUserId, _rewardCoin,_userId, _userId,2);
						END IF;
                    END LOOP;
				CLOSE cur_checkexist;
				END;
			END IF;
			END IF;
			SET @sqlQuery = CONCAT_WS('',@sqlQuery," ,userId = ",_customerUserId);
			IF(_customerId > 0) THEN 
				SET @sqlQuery = CONCAT_WS('',@sqlQuery," WHERE id = ",_customerId);
			END IF;
			PREPARE stmt FROM @sqlQuery;
			EXECUTE stmt;
			DEALLOCATE PREPARE stmt;
            IF(_customerId = 0) THEN
			SET _customerId = LAST_INSERT_ID();
			END IF;
        END IF;
        IF (_customerId > 0) THEN
        IF(_cityId > 0 AND _pincode != '') THEN
			IF(_customerAddressId > 0)THEN 
				SET @customerAddressQuery = CONCAT_WS(''," UPDATE customeraddresses SET cityId = ",_cityId,", pincode = '",_pincode,"',modifiedDate = '",CURRENT_TIMESTAMP(),"',modifiedBy = ",_userId,",addressLine2 = '",_addressLine2,"'");
			ELSE
				SET @customerAddressQuery = CONCAT_WS(''," INSERT INTO customeraddresses SET customerId = ",_customerId,",cityId = ",_cityId,", pincode = '",_pincode,"',modifiedDate = '",CURRENT_TIMESTAMP(),"', modifiedBy = ",_userId,", createdBy = ",_userId," ,createdDate = '",CURRENT_TIMESTAMP(),"', addressTypeId = 1 ");
			END IF;
			IF(_addressLine1 != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , addressLine1 = '",_addressLine1,"'");
			END IF;
			/*IF(_addressLine2 != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , addressLine2 = '",_addressLine2,"'");
			END IF;*/
			IF(_label != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , label = '",_label,"'");
			END IF;
			IF(_city != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , city = '",_city,"'");
			END IF;
			IF(_district != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , district = '",_district,"'");
			END IF;
			IF(_state != '') THEN
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," , state = '",_state,"'");
			END IF;       
            IF(_customerAddressId > 0) THEN 
				SET @customerAddressQuery = CONCAT_WS('', @customerAddressQuery," WHERE id = ",_customerAddressId);
			END IF;
		END IF;
        PREPARE stmt FROM @customerAddressQuery;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
        END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertCustomerLoanOffers`(IN _customerLoanId INT,IN _status VARCHAR(200),IN _bankId INT,IN _employmentTypeId INT,IN _minimumCibilScore INT,IN _minAge INT,IN _maxAge INT,IN _minIncome DECIMAL(15,3),IN _workExpInCurrentCompany VARCHAR(200),IN _vintage INT,IN _minTurnOver DECIMAL(16,2),IN _maxTurnOver DECIMAL(16,2),IN _tenure VARCHAR(100),IN _minROI DECIMAL(4,2),IN _maxROI DECIMAL(4,2),IN _loanAmount DECIMAL(16,2),IN _loanValue DECIMAL(5,2),IN _userId INT)
BEGIN
    DECLARE exist INT DEFAULT 0;
    DECLARE fetchedId INT;
    DECLARE finished INT DEFAULT 0;
	INSERT INTO customerloanoffers (customerLoanId, status, bankId, employmentTypeId, minimumCibilScore, minAge, maxAge, minIncome, workExpInCurrentCompany, vintage, minTurnOver, maxTurnOver, tenure, minROI, maxROI, loanAmount, loanValue,createdBy, modifiedBy) VALUES (_customerLoanId, _status, _bankId, _employmentTypeId, _minimumCibilScore, _minAge, _maxAge, _minIncome, _workExpInCurrentCompany, _vintage, _minTurnOver, _maxTurnOver, _tenure, _minROI, _maxROI, _loanAmount, _loanValue, _userId, _userId);
		BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 12;
			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,12,CURRENT_TIMESTAMP(),_userId,_userId);
            UPDATE customerloans SET statusId = 12 Where id = _customerLoanId;
		END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertDocumentMasters`(IN _name VARCHAR(200),IN _maxSize VARCHAR(20), IN _userId INT)
BEGIN
	INSERT INTO documentmasters(name,maxSize,createdBy,modifiedBy) VALUES(_name,_maxSize, _userId, _userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertEmploymentNature`(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 employmentnatures) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM employmentnatures WHERE isDelete =0;
			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
			INSERT INTO employmentnatures (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO employmentnatures (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertEmploymentServiceType`(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 employmentservicetypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM employmentservicetypes WHERE isDelete =0;
			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
			INSERT INTO employmentservicetypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO employmentservicetypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertEmploymentType`(IN _name VARCHAR(100),IN _parentId INT,IN _userId INT)
BEGIN
	IF _parentId > 0 THEN
	INSERT INTO employmenttypes(name,parentId,createdBy,modifiedBy) VALUES (_name,_parentId,_userId,_userId);
    ELSE 
    INSERT INTO employmenttypes(name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
    END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertIndustryType`(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;
			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
				INSERT INTO industrytypes (name,parentId,createdBy,modifiedBy) VALUES (_name,_parentId,_userId,_userId);
            ELSE
				INSERT INTO industrytypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
			END IF;
		END IF;
	ELSE
		IF _parentId > 0 THEN
			INSERT INTO industrytypes (name,parentId,createdBy,modifiedBy) VALUES (_name,_parentId,_userId,_userId);
		ELSE
			INSERT INTO industrytypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertLoanAgainstCollteral`(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;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getLoanAginstCollteral: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getLoanAginstCollteral;
					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
			INSERT INTO loanagainstcollteral (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO loanagainstcollteral (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertLoanDetail`(IN _id INT,IN _customerLoanId INT,IN _refrenceNo VARCHAR(100),IN _email VARCHAR(200),IN _amountDisbursed DECIMAL(16,2),IN _ROI DECIMAL(6,2),IN _bankId INT,IN _emi DECIMAL(16,2),IN _termsCondition TEXT,IN _tenure INT,IN _totalInterestPayable DECIMAL(12,2),IN _userId INT,IN _isShared TINYINT)
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE fetchedId INT DEFAULT 0;
	IF _id > 0 THEN
		UPDATE customerloandetail SET refrenceNo = _refrenceNo,amountDisbursed = _amountDisbursed,ROI = _ROI,bankId = _bankId,emi = _emi,termsCondition = _termsCondition,tenure = _tenure,totalInterestPayable = _totalInterestPayable,isShared = _isShared WHERE id = _id;
   ELSE
	INSERT INTO customerloandetail(customerLoanId, refrenceNo, email, amountDisbursed, ROI, bankId, emi, termsCondition, tenure, totalInterestPayable,createdBy, modifiedBy,isShared) VALUES (_customerLoanId, _refrenceNo, _email, _amountDisbursed, _ROI, _bankId, _emi, _termsCondition, _tenure, _totalInterestPayable,_userId,_userId,_isShared);
	SET _id = LAST_INSERT_ID();
    END IF;
     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;
		ELSE 
			UPDATE customerloanstatushistory SET loanStatusId = 13,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE customerloanId = _customerLoanId AND loanStatusId = 13;
        END IF;
  
    SELECT _id as id,termsCondition FROM customerloandetail WHERE id = _id;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertLoanStatus`(IN _status VARCHAR(100),IN _isDataEditable BOOLEAN,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;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getLoanStatuses: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getLoanStatuses;
					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
			INSERT INTO loanstatuses (status,isDataEditable,createdBy,modifiedBy) VALUES (_status,_isDataEditable,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO loanstatuses (status,isDataEditable,createdBy,modifiedBy) VALUES (_status,_isDataEditable,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertMaritalStatus`(IN _status VARCHAR(40),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;
			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
			INSERT INTO maritalstatuses (status,createdBy,modifiedBy) VALUES (_status,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO maritalstatuses (status,createdBy,modifiedBy) VALUES (_status,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertOffer`(IN _id INT,IN _customerLoanId INT,IN _bankId INT,IN _loanAmount DECIMAL(15,2),IN _ROI DECIMAL(5,2),IN _tenure INT,IN _isShared BOOLEAN,IN _userId INT,IN _otherDetail TEXT)
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE fetchedId INT DEFAULT 0;
		IF (_id = 0) THEN
		INSERT INTO offers (customerLoanId,bankId,loanAmount,ROI,tenure,isShared,otherDetail,createdBy,modifiedBy) VALUES (_customerLoanId,_bankId,_loanAmount,_ROI,_tenure,_isShared,_otherDetail,_userId,_userId);
    ELSE 
		UPDATE offers SET bankId = _bankId,loanAmount = _loanAmount,ROI = _ROI,tenure = _tenure,isShared= _isShared,modifiedDate= CURRENT_TIMESTAMP(),modifiedBy = _userId,otherDetail = _otherDetail WHERE id = _id;
    END IF;
    
    BEGIN
			DECLARE cur_checkexist cursor for select id FROM customerloanstatushistory WHERE customerloanId = _customerLoanId AND loanStatusId = 12;
			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;
		ELSE 
			UPDATE customerloanstatushistory SET loanStatusId = 13,modifiedDate = CURRENT_TIMESTAMP(),modifiedBy = _userId WHERE customerloanId = _customerLoanId AND loanStatusId = 13;
        END IF;
		
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertPropertyTypes`(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 propertytypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM propertytypes WHERE isDelete =0;
			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
			INSERT INTO propertytypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO propertytypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertResidentType`(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;
			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
			INSERT INTO residenttypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
		END IF;
	ELSE
		INSERT INTO residenttypes (name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertService`(IN _serviceTypeId INT, IN _name VARCHAR(500), IN _displayName VARCHAR(500), IN _description TEXT, IN _iconUrl TEXT, IN _colorCode VARCHAR(45), IN _userId INT)
BEGIN
	INSERT INTO services(serviceTypeId, name, displayName, description, iconUrl, colorCode, createdBy, modifiedBy) VALUES(_serviceTypeId, _name, _displayName, _description, _iconUrl, _colorCode, _userId, _userId);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertServiceEmploymentType`(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 `adminInsertServiceTypeDocuments`(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
	INSERT INTO servicetypedocuments(serviceId, documentId, displayName, documentCount, isRequired,isPdf,employmentTypeId,createdBy, modifiedBy,usRequiredForTransfer,isRequiredForNew) VALUES(_serviceId, _documentId, _displayName, _documentCount, _isRequired,_isPdf,_employmentTypeId, _userId, _userId,_requiredForTransfer,_requiredForNew);
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertServiceTypes`(IN _name VARCHAR(50), IN _displayName VARCHAR(50), IN _description TEXT, IN _iconUrl TEXT, IN _colorCode VARCHAR(45), IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
	IF 	EXISTS(SELECT 1 FROM servicetypes) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select lower(name) FROM servicetypes WHERE isDelete =0;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getServiceType: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getServiceType;
					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
			INSERT INTO servicetypes(name, displayName, description, iconUrl, colorCode, createdBy, modifiedBy) VALUES(_name, _displayName, _description, _iconUrl, _colorCode, _userId, _userId);
		END IF;
	ELSE
		INSERT INTO servicetypes(name, displayName, description, iconUrl, colorCode, createdBy, modifiedBy) VALUES(_name, _displayName, _description, _iconUrl, _colorCode, _userId, _userId);
	END IF;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertTraining`(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(100),IN _roleIds VARCHAR(200),IN _completionTime INT)
BEGIN
	DECLARE front TEXT;
    DECLARE frontlen INT;
    DECLARE TempValue TEXT;
	DECLARE trainingId INT DEFAULT 0;
	IF _trainingSubCategoryId > 0 THEN
		INSERT INTO trainings (trainingCategoryId,title,url,fileName,documentType,trainingSubCategoryId,assignRole,completionTime,createdBy,modifiedBy) VALUES (_trainingCategoryId,_title,_url,_fileName,_documentType,_trainingSubCategoryId,_roleIds,_completionTime,_userId,_userId);
		SET trainingId= LAST_INSERT_ID();
    ELSE 
		INSERT INTO trainings (trainingCategoryId,title,url,fileName,documentType,assignRole,completionTime,createdBy,modifiedBy) VALUES (_trainingCategoryId,_title,_url,_fileName,_documentType,_roleIds,_completionTime,_userId,_userId);
		SET trainingId= LAST_INSERT_ID();
    END IF;
	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 (trainingId,TempValue,_trainingStatus,_userId,_userId);
    SET _trainingAssingUserId = INSERT(_trainingAssingUserId,1,frontlen + 1,'');
    END LOOP;
    SELECT trainingId as trainingId;
END$$
DELIMITER ;













DELIMITER $$
CREATE  PROCEDURE `adminInsertTrainingAssignUsers`(IN _trainingId INT,IN _trainingAssingUserId VARCHAR(600),IN _userId INT,IN _trainingStatus VARCHAR(70))
BEGIN
    DECLARE front TEXT;
    DECLARE frontlen INT;
   DECLARE TempValue TEXT;
   DELETE FROM assignuserstraining WHERE trainingId = _trainingId;
    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 (_trainingId,TempValue,_trainingStatus,_userId,_userId);
    SET _trainingAssingUserId = INSERT(_trainingAssingUserId,1,frontlen + 1,'');
    END LOOP;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertTrainingCategory`(IN _name VARCHAR(100),IN _parentId INT,IN _userId INT)
BEGIN
	IF _parentId > 0 THEN
	INSERT INTO triningcategories(name,parentId,createdBy,modifiedBy) VALUES (_name,_parentId,_userId,_userId);
    ELSE 
    INSERT INTO triningcategories(name,createdBy,modifiedBy) VALUES (_name,_userId,_userId);
    END IF;
    
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateBankCreditCardPolicy`(IN _id INT, IN _bankCreditCardId INT, IN _employmentTypeId INT, IN _minimumCibilScore INT, IN _minAge INT, IN _maxAge INT
, IN _minIncome DECIMAL(15,3), IN _companyCategoryTypeId INT, IN _userId INT)
BEGIN
	IF _id >0 THEN
		UPDATE bankcreditcardpolicies SET bankCreditCardId = _bankCreditCardId, employmentTypeId = _employmentTypeId, minimumCibilScore = _minimumCibilScore, minAge = _minAge
        , maxAge = _maxAge, minIncome = _minIncome, companyCategoryTypeId = _companyCategoryTypeId, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
    ELSE
		INSERT INTO bankcreditcardpolicies(bankCreditCardId, employmentTypeId, minimumCibilScore, minAge, maxAge, minIncome, companyCategoryTypeId, createdBy, modifiedBy) 
        VALUES(_bankCreditCardId, _employmentTypeId, _minimumCibilScore, _minAge, _maxAge, _minIncome, _companyCategoryTypeId, _userId, _userId);
    END IF;
END$$
DELIMITER ;


DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateBankLoanCommission`(IN _bankLoanCommissionId INT, IN _bankId INT, IN _serviceId INT, IN _commissionTypeId INT, IN _commission DECIMAL(5,2), IN _userId INT)
BEGIN
	DECLARE exist INT DEFAULT 0;
    DECLARE _existName VARCHAR(200) DEFAULT '';
    DECLARE finished INT DEFAULT 0;
    IF _bankLoanCommissionId >0 THEN
		BEGIN
			DECLARE cur_checkexist cursor for select id FROM bankloancommissions WHERE bankId = _bankId AND serviceId = _serviceId AND id != _bankLoanCommissionId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBankLoanCommission: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBankLoanCommission;
					END IF;
					IF _existName THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as commissionExist;				
		ELSE
			UPDATE bankloancommissions SET bankId = _bankId, serviceId = _serviceId, commissionTypeId=_commissionTypeId, commission = _commission, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP()
			WHERE id = _bankLoanCommissionId;
        END IF;
	ELSE 
		IF 	EXISTS(SELECT 1 FROM bankloancommissions) THEN
		BEGIN
			DECLARE cur_checkexist cursor for select id FROM bankloancommissions WHERE bankId = _bankId AND serviceId = _serviceId;
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
			OPEN cur_checkexist;
            SET @exist =0;
				getBankLoanCommission: LOOP
					FETCH cur_checkexist INTO _existName;
					IF finished = 1 THEN 
						LEAVE getBankLoanCommission;
					END IF;
					IF _existName THEN
						SET @exist = 1;	
					END IF;
                    END LOOP;
		    CLOSE cur_checkexist;
		END;
		IF @exist = 1 THEN
			SELECT @exist as commissionExist;				
		ELSE
			INSERT INTO bankloancommissions(bankId, serviceId, commissionTypeId, commission, createdBy, modifiedBy) VALUES(_bankId, _serviceId, _commissionTypeId, _commission, _userId, _userId);
        END IF;
	END IF;
    END IF;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateBankPolicy`(IN _bankLoanPolicyId INT, IN _bankId INT, IN _serviceId INT, IN _bankLoanId INT, IN _employmentTypeId INT, IN _cibilScore VARCHAR(200)
,  IN _minIncome DECIMAL(15,3), IN _vintage INT, IN _minTurnOver DECIMAL(16,2), IN _maxTurnOver DECIMAL(16,2)
, IN _tenure VARCHAR(100), IN _ROI DECIMAL(4,2), IN _minLoanAmount DECIMAL(16,2), IN _maxLoanAmount DECIMAL(16,2),IN _itrRequired INT, IN _userId INT,IN _companyCategoryTypeId INT)
BEGIN
	
	IF _bankLoanPolicyId > 0 THEN
		UPDATE bankloanpolicies SET bankId = _bankId, serviceId = _serviceId, bankLoanId = _bankLoanId, employmentTypeId = _employmentTypeId, cibilScore = _cibilScore, minIncome = _minIncome, vintage = _vintage, minTurnOver = _minTurnOver, maxTurnOver = _maxTurnOver, tenure = _tenure, ROI = _ROI, ROI = _ROI, minLoanAmount = _minLoanAmount, maxLoanAmount = _maxLoanAmount, itrRequired = _itrRequired,companyCategoryTypeId = _companyCategoryTypeId, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _bankLoanPolicyId;
	ELSE 
		INSERT INTO bankloanpolicies (bankId, serviceId, bankLoanId, employmentTypeId, cibilScore,  minIncome, vintage, minTurnOver, maxTurnOver, tenure, ROI,  minLoanAmount,maxLoanAmount,itrRequired,companyCategoryTypeId, createdBy, modifiedBy) values (_bankId, _serviceId, _bankLoanId, _employmentTypeId, _cibilScore, _minIncome, _vintage, _minTurnOver, _maxTurnOver, _tenure, _ROI, _minLoanAmount, _maxLoanAmount, _itrRequired,_companyCategoryTypeId, _userId, _userId);
		SET _bankLoanPolicyId = LAST_INSERT_ID();
	END IF;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateBanner`(IN _bannerId INT,IN _roleId VARCHAR(200),IN _url TEXT,IN _fromDate VARCHAR(100),IN _toDate VARCHAR(100),IN _userId INT)
BEGIN
	DECLARE sqlQuery TEXT DEFAULT '';
    SET @sqlQuery = '';
   IF(_bannerId > 0) THEN
		SET @sqlQuery = CONCAT_WS(''," UPDATE banners SET roleId =",_roleId,",url = '",_url,"',modifiedBy =",_userId,",modifiedDate = '",CURRENT_TIMESTAMP(),"'");
	ELSE
		SET @sqlQuery = CONCAT_WS(''," INSERT INTO banners SET roleId =",_roleId,",url = '",_url,"',modifiedBy =",_userId,",modifiedDate = '",CURRENT_TIMESTAMP(),"',createdBy = ",_userId,",createdDate = '",CURRENT_TIMESTAMP(),"'");
	END IF;
    IF(_fromDate != '') THEN
		SET @sqlQuery = CONCAT_Ws('',@sqlQuery,",fromDate = '",_fromDate,"'");
	END IF;
     IF(_toDate != '') THEN
		SET @sqlQuery = CONCAT_Ws('',@sqlQuery,",toDate = '",_toDate,"'");
	END IF;
    IF(_bannerId > 0) THEN
		SET @sqlQuery = CONCAT_WS('',@sqlQuery," WHERE id = ",_bannerId);
	END If;
    PREPARE stmt FROM @sqlQuery;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateBusinessLoanBasicDetail`(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 _label VARCHAR(100),IN _addressLine1 TEXT,IN _addressLine2 TEXT,IN _city VARCHAR(40),IN _district VARCHAR(100),IN _state VARCHAR(100),
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 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,label = _label,addressLine1 = _addressLine1,addressLine2 = _addressLine2,city = _city,district = _district,state = _state, modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerAddressId;
    ELSE
		INSERT INTO customeraddresses(customerId,cityId,pincode,label,addressLine1,addressLine2,city,district,state, createdBy, modifiedBy) VALUES(_customerId,_cityId,_pincode,_label,_addressLine1,_addressLine2,_city,_district,_state, _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);
        
	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 `adminInsertUpdateBusinessLoanBusinessDetail`(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,IN _businessName VARCHAR(200),IN _businessGstNo VARCHAR(15))
BEGIN
	UPDATE customerloanbusinessdetails SET companyTypeId = _companyTypeId, industryTypeId = _industryTypeId, businessNatureId = _businessNatureId, businessAnnualProfitId = _businessAnnualProfitId, currentlyPayEmi = _currentlyPayEmi
    , primaryBankId = _primaryBankId,businessGstNo = _businessGstNo,businessName = _businessName ,modifiedDate=CURRENT_TIMESTAMP(), modifiedBy=_userId WHERE id = _customerLoanBusinessDetailId;
	UPDATE loancompletescreenhistory SET completeScreen = 3 WHERE customerLoanId = _customerLoanId;

END$$
DELIMITER ;


DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCoApplicantEmploymentDetail`(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;
    
    SELECT _customerloancoapplicantemploymentdetailId as customerloancoapplicantemploymentdetailId, _companyAddressId as companyAddressId;
END$$
DELIMITER ;





DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCommissionTemplate`(IN _id INT, IN _name VARCHAR(200),IN _commissionTypeId INT, IN _commission DECIMAL(5,2), IN _userId INT,IN _bankId INT,IN _serviceId INT,IN _bankLoanCommissionId INT)
BEGIN
	IF _id >0 THEN
		UPDATE commissiontemplate SET name = _name, commissionTypeId = _commissionTypeId, commission = _commission,bankId = _bankId,serviceId = _serviceId,bankLoanCommissionId = _bankLoanCommissionId, modifiedBy = _userId, modifiedDate = CURRENT_TIMESTAMP() WHERE id = _id;
    ELSE
		INSERT INTO commissiontemplate(name,commissionTypeId, commission,bankId,serviceId,bankLoanCommissionId, createdBy, modifiedBy) VALUES(_name,_commissionTypeId, _commission,_bankId,_serviceId,_bankLoanCommissionId, _userId, _userId);
    END IF; 
END$$
DELIMITER ;




DELIMITER $$
CREATE  PROCEDURE `adminInsertUpdateCreditCard`(IN _id INT, IN _bankId INT, IN _creditCardName TEXT, IN _benifitDescription TEXT, IN _keyFeatures TEXT,IN _renualFee DECIMAL(10,2),IN _joiningFee DECIMAL(10,2),IN _creditCardUrl TEXT,  IN _userId INT)
BEGIN
	IF _id >0 THEN
		UPDATE bankcreditcard SET bankId = _bankId, creditCardName=_creditCardName, benifitDescription=_benifitDescription, keyFeatures=_keyFeatures,renualFee = _renualFee,joiningFee = _joiningFee,creditCardUrl = _creditCardUrl, modifiedDate=CURRENT_TIMESTAMP()
        , modifiedBy=_userId WHERE id = _id;
    ELSE
