Subversion Repositories SmartDukaan

Rev

Rev 31685 | Rev 31734 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.service.user;

import com.google.common.hash.Hashing;
import com.spice.profitmandi.common.enumuration.ActivationType;
import com.spice.profitmandi.common.enumuration.FofoType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.*;
import com.spice.profitmandi.common.util.StringUtils;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.dtr.*;
import com.spice.profitmandi.dao.entity.fofo.*;
import com.spice.profitmandi.dao.entity.inventory.State;
import com.spice.profitmandi.dao.entity.user.*;
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
import com.spice.profitmandi.dao.enumuration.dtr.RetailerType;
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
import com.spice.profitmandi.dao.enumuration.transaction.PartnerVerificationApprovalStatus;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.dao.repository.dtr.*;
import com.spice.profitmandi.dao.repository.fofo.FofoPartnerPaymentOptionRepository;
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
import com.spice.profitmandi.dao.repository.fofo.PincodePartnerRepository;
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
import com.spice.profitmandi.dao.repository.user.*;
import com.spice.profitmandi.service.offers.PartnerCriteria;
import in.shop2020.model.v1.user.CartStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
public class RetailerServiceImpl implements RetailerService {

        private static final Logger LOGGER = LogManager.getLogger(RetailerServiceImpl.class);

        @Autowired
        private RetailerRepository retailerRepository;

        @Autowired
        private RetailerBlockBrandsRepository retailerBlockBrandsRepository;

        @Autowired
        private UserAccountRepository userAccountRepository;

        @Autowired
        private Mongo mongoClient;

        @Autowired
        private UserRepository userRepository;

        @Autowired
        private CartRepository cartRepository;

        @Autowired
        private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;

        @Autowired
        private AddressRepository addressRepository;

        @Autowired
        private ShopRepository shopRepository;

        @Autowired
        private ShopAddressRepository shopAddressRepository;

        @Autowired
        private UserRoleRepository userRoleRepository;

        @Autowired
        private DocumentRepository documentRepository;

        @Autowired
        private PrivateDealUserRepository privateDealUserRepository;

        @Autowired
        private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;

        @Autowired
        private CounterRepository counterRepository;

        @Autowired
        private StateRepository stateRepository;

        @Autowired
        @Qualifier("userUserRepository")
        private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;

        @Autowired
        private DistrictMasterRepository districtMasterRepository;

        @Autowired
        private FofoStoreRepository fofoStoreRepository;

        @Autowired
        private PaymentOptionRepository paymentOptionRepository;

        @Autowired
        private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;

        @Autowired
        private RoleRepository roleRepository;

        @Autowired
        private StoreTimelineTatService storeTimelineTatService;

        @Autowired
        private PartnerOnBoardingPanelRepository partnerOnBoardingPanelRepository;

        @Autowired
        private PartnerOnboardingVerificationRepository partnerOnboardingVerificationRepository;

        @Autowired
        private PincodePartnerRepository pincodePartnerRepository;

        @Override
        public Map<String, Object> getByEmailIdOrMobileNumber(String emailIdOrMobileNumber)
                        throws ProfitMandiBusinessException {
                User user = null;
                int fofoId = Utils.SYSTEM_PARTNER_ID;

                try {
                        user = userRepository.selectByEmailIdOrMobileNumber(emailIdOrMobileNumber);
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {

                }
                if (user == null) {
                        try {
                                user = userRepository.selectBySecondryEmailId(emailIdOrMobileNumber);
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {

                        }
                }
                Map<String, Object> map = new HashMap<>();
                map.put("stateNames", stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));

                if (user != null) {

                        List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());

                        Role role = roleRepository.selectByName(RoleType.FOFO.toString());

                        map.put("userRoles", userRoles);
                        map.put("user", user);
                        // map.put("retailer", retailer);
                        map.put("fofoRole", this.containsRoleType(userRoles, role.getId()));

                        map.put("userRoleNames", this.toString(userRoles));
                        try {
                                int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());
                                Retailer retailer = retailerRepository.selectById(retailerId);

                                map.put("retailer", retailer);

                                List<String> retailerBlockBrands = null;
                                Set<String> brands = null;
                                if (retailer.getId() != fofoId) {
                                        brands = mongoClient.getMongoBrands(retailer.getId(), null, 3).stream()
                                                        .map(x -> (String) x.get("name")).collect(Collectors.toSet());
                                        retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
                                                        .map(x -> x.getBlockBrands()).collect(Collectors.toList());

                                        LOGGER.info("loginDetailsFofoId" + retailer.getId());
                                } else {
                                        LOGGER.info("fofoId" + fofoId);
                                        brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
                                                        .collect(Collectors.toSet());
                                }
                                map.put("brands", brands);
                                map.put("retailerBlockBrands", retailerBlockBrands);
                                if (this.containsRoleType(userRoles, role.getId())) {
                                        try {
                                                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
                                                map.put("fofoStore", fofoStore);
                                                // map.put("counterSize", fofoStore.getCounterSize().toString());
                                                // LOGGER.info("fofoStore" + fofoStore);
                                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                                LOGGER.error("FofoStore code not found");
                                        }
                                }

                                try {
                                        PrivateDealUser privateDealUser = privateDealUserRepository.selectById(retailer.getId());
                                        if (privateDealUser.getCounterId() != null) {
                                                Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
                                                map.put("gstNumber", counter.getGstin());
                                                // LOGGER.info("gstNumber" + counter.getGstin());
                                        }
                                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                        LOGGER.error("PrivateDealUser not found");
                                }
                                try {
                                        int retailerAddressId = retailerRegisteredAddressRepository
                                                        .selectAddressIdByRetailerId(retailer.getId());
                                        Address retailerAddress = addressRepository.selectById(retailerAddressId);
                                        map.put("retailerAddress", retailerAddress);
                                        State state = stateRepository.selectByName(retailerAddress.getState());
                                        // LOGGER.info("retailerAddress.." + retailerAddress);
                                        List<DistrictMaster> districtMasters = districtMasterRepository
                                                        .selectByStateShortName(state.getShortName());
                                        map.put("districtMasters", districtMasters);
                                        // LOGGER.info("districtMasters" + districtMasters);
                                        List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
                                        map.put("shops", shops);
                                        this.addAddress(shops);
                                        // LOGGER.info("shops" + shops);
                                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                        LOGGER.error("Retailer Registered Address not found");
                                }
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                LOGGER.error("Retailer not found in user_account");
                        }
                }

                return map;
        }

        private boolean containsRoleType(List<UserRole> userRoles, int roleId) {
                for (UserRole userRole : userRoles) {
                        if (userRole.getRoleId() == roleId) {
                                return true;
                        }
                }
                return false;
        }

        private List<UserRole> addRole(List<UserRole> userRoles, int userId, int roleId) {
                if (userRoles == null) {
                        userRoles = new ArrayList<>();
                }
                if (!this.containsRoleType(userRoles, roleId)) {
                        UserRole userRole = new UserRole();
                        userRole.setUserId(userId);
                        userRole.setRoleId(roleId);
                        try {
                                userRoleRepository.persist(userRole);
                        } catch (ProfitMandiBusinessException e) {
                                LOGGER.error("UserRole is already exist");
                        }
                        userRoles.add(userRole);
                }
                return userRoles;

        }

        private List<UserRole> removeRole(List<UserRole> userRoles, int userId, int roleId) {
                if (userRoles == null) {
                        userRoles = new ArrayList<>();
                        return userRoles;
                }
                try {
                        userRoles.remove(userRoleRepository.deleteByRoleUserId(userId, roleId));
                } catch (Exception e) {

                }
                return userRoles;

        }

        @SuppressWarnings("unchecked")
        @Override
        public Map<String, Object> updateRetailerDetails(UpdateRetailerRequest updateRetailerRequest)
                        throws ProfitMandiBusinessException {
                Map<String, Object> map = this.getByEmailIdOrMobileNumber(updateRetailerRequest.getEmailIdOrMobileNumber());
                User user = (User) map.get("user");

                user = this.createUser(user, updateRetailerRequest);

                map.put("user", user);
                List<UserRole> userRoles = (List<UserRole>) map.get("userRoles");
                Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
                userRoles = this.addRole(userRoles, user.getId(), roleUser.getId());
                Retailer retailer = (Retailer) map.get("retailer");
                retailer = this.updateRetailer(user, retailer, updateRetailerRequest);

                map.put("retailer", retailer);

                List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
                                .map(x -> x.getBlockBrands()).collect(Collectors.toList());

                LOGGER.info("retailerBlockBrands" + retailerBlockBrands);

                if (!retailerBlockBrands.isEmpty()) {
                        retailerBlockBrandsRepository.deleteBrands(retailer.getId());
                }

                for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
                        RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();

                        retailerBlockBrand.setFofoId(retailer.getId());
                        retailerBlockBrand.setBlockBrands(blockBrand);
                        retailerBlockBrandsRepository.persist(retailerBlockBrand);

                }
                map.put("retailerBlockBrands", retailerBlockBrands);

                Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());

                userRoles = this.addRole(userRoles, user.getId(), roleRetailer.getId());

                Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());

                if (updateRetailerRequest.isFofo()) {
                        userRoles = this.addRole(userRoles, user.getId(), roleFofo.getId());
                } else {
                        userRoles = this.removeRole(userRoles, user.getId(), roleFofo.getId());
                }
                map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));

                if (this.containsRoleType(userRoles, roleFofo.getId())) {
                        this.createDefaultPaymentOption(retailer.getId());
                }

                map.put("userRoles", userRoles);
                map.put("userRoleNames", this.toString(userRoles));

                Address retailerAddress = (Address) map.get("retailerAddress");
                retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(),
                                retailer.getId());
                map.put("retailerAddress", retailerAddress);

                if (updateRetailerRequest.isFofo()) {
                        FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(),
                                        updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
                        map.put("fofoStore", fofoStore);
                        fofoStore.setActive(updateRetailerRequest.isActive());
                }

                this.createPrivateDealUser(user, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer,
                                retailerAddress.getId());
                map.put("gstNumber", updateRetailerRequest.getGstNumber());
                this.updateSaholicUser(retailer.getId(), retailerAddress.getId());

                List<Shop> shops = (List<Shop>) map.get("shops");
                if (shops == null) {
                        shops = new ArrayList<>();
                        map.put("shops", shops);
                }
                this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);

                return map;

        }

        private void createDefaultPaymentOption(int fofoId) {
                List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
                if (paymentOptionIds.isEmpty()) {
                        PaymentOption paymentOption = null;
                        try {
                                paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                paymentOption = new PaymentOption();
                                paymentOption.setName(PaymentOptionType.CASH.toString());
                                paymentOptionRepository.persist(paymentOption);
                        }
                        FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
                        fofoPartnerPaymentOption.setFofoId(fofoId);
                        fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
                        fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
                }

        }

        private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) {
                if (user == null) {
                        user = new User();
                        user.setCity("");
                        user.setPinCode(0);
                        user.setState("");
                        user.setPassword("");
                        user.setMobile_verified(false);
                        user.setReferral_url("");
                        user.setGroup_id(1);
                        user.setStatus(1);
                        user.setActivated(true);
                        user.setCreateTimestamp(LocalDateTime.now());
                }
                user.setActivated(updateRetailerRequest.isActive());
                user.setFirstName(updateRetailerRequest.getUserFirstName());
                user.setLastName(updateRetailerRequest.getUserLastName());
                user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
                user.setEmailId(updateRetailerRequest.getUserEmailId());
                user.setUsername(updateRetailerRequest.getUserEmailId());
                user.setUpdateTimestamp(LocalDateTime.now());
                userRepository.persist(user);
                return user;

        }

        private int createSaholicUser(User user, String retailerName) {
                com.spice.profitmandi.dao.entity.user.User saholicUser = null;
                try {
                        saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.info("User doesnt exist in old system");
                }
                if (saholicUser == null) {
                        Cart cart = new Cart();
                        cart.setCartStatus(CartStatus.ACTIVE);
                        cartRepository.persist(cart);
                        saholicUser = new com.spice.profitmandi.dao.entity.user.User();
                        saholicUser.setEmailId(user.getEmailId());
                        saholicUser.setName(retailerName);
                        saholicUser.setActiveCartId(cart.getId());
                        saholicUser.setCreateTimestamp(LocalDateTime.now());
                        userUserRepository.persist(saholicUser);

                        UserAccount ua = new UserAccount();
                        ua.setAccountKey(saholicUser.getId());
                        ua.setUserId(user.getId());
                        ua.setType(AccountType.saholic);
                        userAccountRepository.persist(ua);

                        UserAccount ua2 = new UserAccount();
                        ua2.setAccountKey(saholicUser.getActiveCartId());
                        ua2.setUserId(user.getId());
                        ua2.setType(AccountType.cartId);
                        userAccountRepository.persist(ua2);
                        LOGGER.info("created....");
                }
                return saholicUser.getId();
        }

        private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
                        LoginRequestResponseModel loginRequestResponseModel) {
                com.spice.profitmandi.dao.entity.user.User saholicUser = null;
                try {
                        saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
                        saholicUser.setCreateTimestamp(LocalDateTime.now());
                } catch (ProfitMandiBusinessException e) {
                        LOGGER.info("User doesnt exist in old system");
                }
                if (saholicUser == null) {
                        Cart cart = new Cart();
                        cart.setCartStatus(CartStatus.ACTIVE);
                        cartRepository.persist(cart);
                        saholicUser = new com.spice.profitmandi.dao.entity.user.User();
                        saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
                        saholicUser.setEmailId(loginRequestResponseModel.getEmail());
                        saholicUser.setName(loginRequestResponseModel.getCustomerName());
                        saholicUser.setActiveCartId(cart.getId());
                        saholicUser.setCreateTimestamp(LocalDateTime.now());
                        loginRequestResponseModel.setPassword(null);
                        userUserRepository.persist(saholicUser);
                }
                return saholicUser;
        }

        private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest)
                        throws ProfitMandiBusinessException {
                if (retailer == null) {
                        LOGGER.info("createSaholicUser.....");
                        int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
                        retailer = new Retailer();
                        retailer.setId(saholicUserId);
                }
                retailer.setActive(updateRetailerRequest.isActive());
                user.setActivated(updateRetailerRequest.isActive());//
                // this.createRole(user.getId(), RoleType.RETAILER);
                retailer.setName(updateRetailerRequest.getName());
                retailer.setNumber(updateRetailerRequest.getNumber());
                if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
                        retailer.setType(RetailerType.UNREGISTERED_SHOP);
                } else {
                        retailer.setType(RetailerType.GSTIN);
                }
                if (updateRetailerRequest.getDocumentId() > 0) {
                        if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
                                try {
                                        documentRepository.deleteById(retailer.getDocumentId());
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                        retailer.setDocumentId(updateRetailerRequest.getDocumentId());
                        documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
                }
                retailerRepository.persist(retailer);
                return retailer;
        }

        private void updateSaholicUser(int retailerId, int retailerAddressId) {
                try {
                        com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
                        user.setAddressId(retailerAddressId);
                } catch (ProfitMandiBusinessException e) {

                }
        }

        private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
                        int retailerAddressId) {
                PrivateDealUser privateDealUser = null;
                try {
                        privateDealUser = privateDealUserRepository.selectById(retailer.getId());
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        LOGGER.error("PrivateDealUser not found");
                }

                // = privateDealUserRepository.selectById(saholicUser.getId());
                if (privateDealUser == null) {
                        Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
                                        retailer.getName(), retailerAddressId);
                        try {
                                this.createPrivateDealUser(retailer.getId(), counterId, fofo);
                        } catch (Exception e) {
                                LOGGER.error("ERROR : ", e);
                        }
                } else {
                        if (privateDealUser.getCounterId() == null) {
                                Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
                                                retailer.getName(), retailerAddressId);
                                privateDealUser.setCounterId(counterId);
                                privateDealUser.setFofo(fofo);
                                privateDealUserRepository.persist(privateDealUser);
                        } else {
                                Counter counter = null;
                                try {
                                        counter = counterRepository.selectById(privateDealUser.getCounterId());
                                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                        LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
                                }
                                if (counter == null) {
                                        this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(),
                                                        retailerAddressId);
                                } else {
                                        counter.setGstin(gstNumber);
                                        counterRepository.persist(counter);
                                }
                                privateDealUser.setFofo(fofo);
                                privateDealUserRepository.persist(privateDealUser);
                        }
                }

                PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
                privateDealUserAddressMapping.setUserId(retailer.getId());
                privateDealUserAddressMapping.setAddressId(retailerAddressId);
                privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
        }

        // Specifically set isFofo to true that has to be used by old system
        private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
                PrivateDealUser privateDealUser = new PrivateDealUser();
                privateDealUser.setActive(true);
                privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
                privateDealUser.setId(retailerId);
                privateDealUser.setCounterId(counterId);
                privateDealUser.setFofo(fofo);
                privateDealUserRepository.persist(privateDealUser);
        }

        private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
                if (gstNumber != null && !gstNumber.isEmpty()) {
                        Counter counter = new Counter();
                        counter.setEmailId(emailId);
                        counter.setGstin(gstNumber);
                        counter.setMobileNumber(mobileNumber);
                        counter.setName(name);
                        counter.setAddressId(addressId);
                        counterRepository.persist(counter);
                        return counter.getId();
                } else {
                        return null;
                }
        }

        private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId)
                        throws ProfitMandiBusinessException {
                if (address == null) {
                        address = new Address();
                        address.setRetaierId(retailerId);
                        this.updateAddress(address, customAddress);
                        // addressRepository.persist(addressRetailer);

                        final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
                        retailerRegisteredAddress.setRetailerId(retailerId);
                        retailerRegisteredAddress.setAddressId(address.getId());
                        retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
                } else {
                        this.updateAddress(address, customAddress);
                        RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository
                                        .selectByRetailerId(retailerId);
                        retailerRegisteredAddress.setAddressId(address.getId());
                        retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
                }
                return address;
        }

        private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
                address.setName(customAddress.getName());
                address.setPhoneNumber(customAddress.getPhoneNumber());
                address.setLine1(customAddress.getLine1());
                address.setLine2(customAddress.getLine2());
                address.setCity(customAddress.getCity());
                address.setPinCode(customAddress.getPinCode());
                State state = stateRepository.selectByName(customAddress.getState());
                if (state == null) {
                        throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology",
                                        "Invalid State - Pls Contact Technology");
                }
                address.setState(state.getName());
                addressRepository.persist(address);
                LOGGER.info("Address Updated" + address);
        }

        private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId,
                        Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
                if (shops.isEmpty()) {
                        for (CustomShop customShop : customShops) {
                                Shop shop = new Shop();
                                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
                                shops.add(shop);
                        }
                } else {
                        for (Shop shop : shops) {
                                for (CustomShop customShop : customShops) {
                                        if (shop.getId() == customShop.getShopId()) {
                                                this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
                                        }
                                }
                        }
                        for (CustomShop customShop : customShops) {
                                if (customShop.getShopId() == 0) {
                                        Shop shop = new Shop();
                                        this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
                                        shops.add(shop);
                                }
                        }
                }
        }

        private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId,
                        Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
                shop.setRetailerId(retailerId);
                shop.setName(customShop.getName());
                if (customShop.getDocumentId() > 0) {
                        if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
                                try {
                                        documentRepository.deleteById(shop.getDocumentId());
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                        shop.setDocumentId(customShop.getDocumentId());
                        documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
                }
                if (shop.getAddressId() == null) {
                        Address address = null;
                        if (customShop.isSameAsRetailerAddress()) {
                                address = sameAsRetailerAddressValue;
                        } else {
                                // shop.setDocumentId(customShop.getDocumentId());
                                address = new Address();
                                this.updateAddress(address, customShop.getAddress());
                        }
                        shop.setAddressId(address.getId());
                        shop.setAddress(address);
                        shopRepository.persist(shop);
                        ShopAddress shopAddress = null;
                        try {
                                shopAddress = shopAddressRepository.selectByShopId(shop.getId());
                                shopAddress.setAddressId(address.getId());
                        } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                shopAddress = new ShopAddress();
                                shopAddress.setAddressId(address.getId());
                                shopAddress.setShopId(shop.getId());
                        }
                        shopAddressRepository.persist(shopAddress);
                } else {
                        Address address = null;
                        try {
                                address = addressRepository.selectById(shop.getAddressId());
                                CustomAddress customAddress = customShop.getAddress();
                                if (!(address.getName().equals(customAddress.getName())
                                                && address.getLine1().equals(customAddress.getLine1())
                                                && address.getLine2().equals(customAddress.getLine2())
                                                && address.getCity().equals(customAddress.getCity())
                                                && address.getPinCode().equals(customAddress.getPinCode())
                                                && address.getState().equals(customAddress.getState()))) {
                                        address = new Address();
                                        ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
                                        this.updateAddress(address, customAddress);
                                        shopAddress.setAddressId(address.getId());
                                        shopAddressRepository.persist(shopAddress);
                                        shop.setAddress(address);
                                        shopRepository.persist(shop);
                                }
                        } catch (Exception e) {
                                if (customShop.isSameAsRetailerAddress()) {
                                        address = sameAsRetailerAddressValue;
                                } else {
                                        // shop.setDocumentId(customShop.getDocumentId());
                                        address = new Address();
                                        this.updateAddress(address, customShop.getAddress());
                                }
                                shop.setAddressId(address.getId());
                                shop.setAddress(address);
                                shopRepository.persist(shop);
                                ShopAddress shopAddress = null;
                                try {
                                        shopAddress = shopAddressRepository.selectByShopId(shop.getId());
                                        shopAddress.setAddressId(address.getId());
                                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                                        shopAddress = new ShopAddress();
                                        shopAddress.setAddressId(address.getId());
                                        shopAddress.setShopId(shop.getId());
                                }
                                shopAddressRepository.persist(shopAddress);
                        }

                }

        }

        private void addAddress(List<Shop> shops) {
                Set<Integer> shopIds = this.toShopIds(shops);
                if (shopIds.isEmpty()) {
                        return;
                }
                List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
                Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);

                for (Shop shop : shops) {
                        shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
                }
        }

        private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) {
                Map<Integer, Address> addressIdAddressMap = new HashMap<>();
                List<Integer> addressIds = this.toAddressIds(shopAddresses);
                List<Address> addresses = addressRepository.selectByIds(addressIds);
                for (Address address : addresses) {
                        addressIdAddressMap.put(address.getId(), address);
                }
                return addressIdAddressMap;
        }

        private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
                Function<ShopAddress, Integer> shopAddressToAddressIdFunction = new Function<ShopAddress, Integer>() {
                        @Override
                        public Integer apply(ShopAddress shopAddress) {
                                return shopAddress.getAddressId();
                        }
                };
                return shopAddresses.stream().map(shopAddressToAddressIdFunction).collect(Collectors.toList());
        }

        private Set<Integer> toShopIds(List<Shop> shops) {
                Function<Shop, Integer> shopToAddressIdFunction = new Function<Shop, Integer>() {
                        @Override
                        public Integer apply(Shop shop) {
                                return shop.getId();
                        }
                };
                return shops.stream().map(shopToAddressIdFunction).collect(Collectors.toSet());
        }

        private String toString(List<UserRole> userRoles) {
                Set<Integer> roleIds = new HashSet<>();
                for (UserRole userRole : userRoles) {
                        roleIds.add(userRole.getRoleId());
                }
                List<Role> roles = roleRepository.selectByIds(roleIds);
                Function<Role, String> roleToNameFunction = new Function<Role, String>() {
                        public String apply(Role role) {
                                return String.valueOf(role.getName());
                        };
                };
                Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
                return String.join(", ", userRoleStrings);
        }

        private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String stateName,
                        UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
                FofoStore fofoStore = null;
                try {
                        fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
                        fofoStore.setActivationType(ActivationType.ACTIVE);

                } catch (ProfitMandiBusinessException profitMandiBusinessException) {

                }

                if (fofoStore != null) {
                        fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
                        fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
                        fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
                        fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
                        fofoStore.setFofoType(updateRetailerRequest.getFofoType());

                } else {
                        int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
                        Address retailerAddress = addressRepository.selectById(retailerAddressId);

                        // StateInfo stateInfo = null;
                        State stateInfo = null;
                        try {

                                stateInfo = stateRepository.selectByName(retailerAddress.getState());
                                // stateInfo = Utils.getStateInfo(retailerAddress.getState());
                        } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                // throw new ProfitMandiBusinessException();
                        }
                        DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName,
                                        stateInfo.getShortName());

                        fofoStore = new FofoStore();
                        fofoStore.setId(retailerId);
                        fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
                        fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());

                        fofoStore.setCounterPotential(updateRetailerRequest.getCounterPotential());
                        fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
                        String latestStoreCode = fofoStoreRepository.selectLatestStore().getCode();
                        int latestCodeCounter = Integer.parseInt(latestStoreCode.replaceAll("[A-Z]", ""));
                        String fofoStoreCode = StringUtils.generateFofoStoreSequence(
                                        districtMaster.getStateShortName() + districtMaster.getShortName(), latestCodeCounter + 1);
                        fofoStore.setCode(fofoStoreCode);
                        fofoStore.setBagsLastCredited(LocalDateTime.now());
                        fofoStore.setFofoType(updateRetailerRequest.getFofoType());
                        fofoStore.setActivationType(ActivationType.ACTIVE);
                        fofoStoreRepository.persist(fofoStore);

                        // Auto fill in onboarding Panel
                        PartnerOnBoardingPanel pobp = partnerOnBoardingPanelRepository
                                        .selectByPhoneNumber(Long.parseLong(retailerAddress.getPhoneNumber()));
                        if (pobp != null) {

                                PartnerVerificationpanel partnerVerificationpanel = partnerOnboardingVerificationRepository
                                                .selectByOnboardingId(pobp.getId());

                                if (partnerVerificationpanel != null) {
                                        if (partnerVerificationpanel.getApproval().equals(PartnerVerificationApprovalStatus.YES)) {
                                                pobp.setCode(fofoStore.getCode());

                                                storeTimelineTatService.onCodeCreated(pobp.getId());

                                        }

                                }

                        }

                        PincodePartner pincodePartner = pincodePartnerRepository
                                        .selectPartnerByPincode(retailerAddress.getPinCode(), fofoStore.getId());
                        if (pincodePartner == null) {
                                PincodePartner pinPartner = new PincodePartner();
                                pinPartner.setFofoId(fofoStore.getId());
                                pinPartner.setPincode(retailerAddress.getPinCode());
                                pincodePartnerRepository.perist(pinPartner);
                        }
                }

                return fofoStore;
        }

        @Override
        public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String stateName,
                        UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
                User user = userRepository.selectById(userId);
                // = userAccountRepository.selectRetailerIdByUserId(user.getId());
                UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
                Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
                Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
                try {
                        userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
                } catch (ProfitMandiBusinessException profitMandiBusinessException) {
                        throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
                }
                return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);

        }

        @Override
        public List<DistrictMaster> getAllDistrictMaster(String stateName) {
                // StateInfo stateInfo = null;
                State stateInfo = null;
                try {
                        // stateInfo = Utils.getStateInfo(stateName);

                        stateInfo = stateRepository.selectByName(stateName);
                } catch (Exception e) {
                        e.printStackTrace();
                        // throw new ProfitMandiBusinessException();
                }
                return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
        }

        @Override
        public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) {
                List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
                Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
                                .filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
                List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
                Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
                for (Address address : addresses) {
                        com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
                        CustomRetailer customRetailer = new CustomRetailer();
                        customRetailer.setEmail(user.getEmailId());
                        customRetailer.setBusinessName(address.getName());
                        customRetailer.setMobileNumber(address.getPhoneNumber());
                        try {
                                FofoStore fs = fofoStoreRepository.selectByRetailerId(address.getRetaierId());
                                customRetailer.setCode(fs.getCode());
                                customRetailer.setActivationType(fs.getActivationType());
                                customRetailer.setCounterSize(fs.getCounterSize());

                                customRetailer.setWarehouseId(fs.getWarehouseId());
                                customRetailer.setPartnerId(fs.getId());
                                customRetailer.setFofoType(fs.getFofoType());
                        } catch (Exception e) {
                                continue;
                        }
                        try {
                                customRetailer.setCartId(user.getActiveCartId());
                                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
                                Counter counter = counterRepository.selectById(pdu.getCounterId());
                                customRetailer.setGstNumber(counter.getGstin());
                        } catch (Exception e) {
                                customRetailer.setGstNumber(null);
                        }
                        CustomAddress address1 = new CustomAddress();
                        address1.setCity(address.getCity());
                        address1.setState(address.getState());
                        address1.setLine1(address.getLine1());
                        address1.setLine2(address.getLine2());
                        address1.setPinCode(address.getPinCode());
                        address1.setName(address.getName());
                        customRetailer.setAddress(address1);
                        customRetailer.setDisplayName(
                                        customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + address1.getCity());
                        customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
                }
                return customRetailersMap;
        }

        @Override
        @Cacheable(value = "getFofoRetailer", cacheManager = "thirtyMinsTimeOutCacheManager")
        public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
                com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
                FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
                Address address = null;
                try {
                        address = addressRepository.selectById(saholicUser.getAddressId());
                } catch (ProfitMandiBusinessException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
                CustomRetailer customRetailer = new CustomRetailer();
                customRetailer.setEmail(saholicUser.getEmailId());
                customRetailer.setBusinessName(address.getName());
                customRetailer.setMobileNumber(address.getPhoneNumber());
                try {
                        customRetailer.setCartId(saholicUser.getActiveCartId());
                        PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
                        Counter counter = counterRepository.selectById(pdu.getCounterId());
                        customRetailer.setGstNumber(counter.getGstin());
                } catch (Exception e) {
                        customRetailer.setGstNumber(null);
                }
                CustomAddress address1 = new CustomAddress();
                address1.setCity(address.getCity());
                address1.setState(address.getState());
                address1.setLine1(address.getLine1());
                address1.setLine2(address.getLine2());
                address1.setPinCode(address.getPinCode());
                address1.setPhoneNumber(address.getPhoneNumber());
                address1.setName(address.getName());
                customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
                customRetailer.setAddress(address1);
                customRetailer.setPartnerId(address.getRetaierId());
                customRetailer.setCode(store.getCode());
                customRetailer.setActivationType(store.getActivationType());
                customRetailer.setWarehouseId(store.getWarehouseId());
                customRetailersMap.put(address.getRetaierId(), customRetailer);
                return customRetailer;

        }

        @Override
        public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) {
                List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
                Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
                                .filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
                List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
                Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
                for (Address address : addresses) {
                        com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
                        CustomRetailer customRetailer = new CustomRetailer();
                        customRetailer.setEmail(user.getEmailId());
                        customRetailer.setBusinessName(address.getName());
                        customRetailer.setMobileNumber(address.getPhoneNumber());
                        int userId = 0;
                        try {
                                userId = userAccountRepository.selectUserIdByRetailerId(user.getId());
                        } catch (ProfitMandiBusinessException e) {
                                continue;
                        }
                        try {
                                customRetailer.setCartId(user.getActiveCartId());
                                PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
                                Counter counter = counterRepository.selectById(pdu.getCounterId());
                                customRetailer.setGstNumber(counter.getGstin());
                        } catch (Exception e) {
                                customRetailer.setGstNumber(null);
                        }
                        CustomAddress address1 = new CustomAddress();
                        address1.setCity(address.getCity());
                        address1.setState(address.getState());
                        address1.setLine1(address.getLine1());
                        address1.setLine2(address.getLine2());
                        address1.setPinCode(address.getPinCode());
                        address1.setName(address.getName());
                        customRetailer.setAddress(address1);
                        customRetailer.setPartnerId(address.getRetaierId());
                        customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + address1.getCity());
                        customRetailersMap.put(userId, customRetailer);
                }
                return customRetailersMap;
        }

        @Override
        public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() {
                Role roleFofo = null;
                try {
                        roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
                } catch (ProfitMandiBusinessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                Role roleRetailer = null;
                try {
                        roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
                } catch (ProfitMandiBusinessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
                Set<Integer> roleIds = new HashSet<>();
                roleIds.add(roleFofo.getId());
                roleIds.add(roleRetailer.getId());
                List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
                List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
                Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
                Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
                for (User user : users) {
                        retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
                }
                return retailerIdEmailIdMap;
        }

        private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
                List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
                Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
                for (UserAccount userAccount : userAccounts) {
                        userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
                }
                return userIdRetailerIdMap;
        }

        private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) {
                List<User> users = userRepository.selectAllByIds(userIds);
                Map<Integer, String> userIdEmailIdMap = new HashMap<>();
                for (User user : users) {
                        userIdEmailIdMap.put(user.getId(), user.getEmailId());
                }
                return userIdEmailIdMap;
        }

        @Override
        public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) {
                List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
                Set<Integer> userIds = new HashSet<>();
                for (UserAccount userAccount : userAccounts) {
                        userIds.add(userAccount.getUserId());
                }
                Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
                Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
                for (UserAccount userAccount : userAccounts) {
                        retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
                }
                return retailerIdEmailIdMap;
        }

        @Override
        public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) {
                Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
                Map<Integer, String> retailerIdNameMap = new HashMap<>();
                for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
                        retailerIdNameMap.put(entry.getKey(),
                                        entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
                }
                return retailerIdNameMap;
        }

        @Override
        @Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, String> getAllFofoRetailerIdNameMap() {
                List<FofoStore> stores = fofoStoreRepository.selectAll();
                List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
                return this.getAllFofoRetailerIdNameMap(storeIds);
        }

        @Override
        public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() {
                List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
                // TODO Auto-generated method stub
                Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
                fofoIdNameMap.forEach((fofoId, name) -> {
                        MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
                        idWrapper.setKey(fofoId);
                        idWrapper.setValue(name);
                        mapWrappers.add(idWrapper);
                });
                return mapWrappers;
        }

        @Override
        @Cacheable(value = "retailerNames", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) {
                // TODO Auto-generated method stub
                Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream().filter(x -> !x.isInternal());
                if (activeOnly) {
                        storeStream = storeStream.filter(x -> x.isActive());
                }
                List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
                return this.getFofoRetailers(storeIds);
        }

        @Override
        @Cacheable(value = "allFofoRetailers", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, CustomRetailer> getAllFofoRetailers() {
                // TODO Auto-generated method stub
                Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();

                List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
                return this.getFofoRetailers(storeIds);
        }

        @Override
        public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel)
                        throws ProfitMandiBusinessException {

                com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
                loginRequestModel.setUserId(saholicUser.getId());

                this.createRetailerAddress(loginRequestModel);

                this.createPrivateDealUser(loginRequestModel);
                this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());

                return loginRequestModel;

        }

        private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {

                Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(),
                                loginRequestModel.getBusinessAddress().getPhoneNumber(),
                                loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
                try {
                        this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
                } catch (Exception e) {
                        LOGGER.error("ERROR : ", e);
                }

                PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
                privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
                privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
                privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);

        }

        private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel)
                        throws ProfitMandiBusinessException {
                Address businessAddress = loginRequestResponseModel.getBusinessAddress();
                businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
                addressRepository.persist(businessAddress);
        }

        private String getHash256(String originalString) {
                String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
                LOGGER.info("Hash String {}", hashString);
                return hashString;
        }

        @Override
        @Cacheable(value = "fofoIdUrl", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
                Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
                List<FofoStore> stores = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive())
                                .collect(Collectors.toList());
                Map<Integer, com.spice.profitmandi.dao.entity.user.User> userMap = userUserRepository
                                .selectByIds(stores.stream().map(x -> x.getId()).collect(Collectors.toList())).stream()
                                .collect(Collectors.toMap(x -> x.getId(), x -> x));
                for (FofoStore store : stores) {
                        LOGGER.info("Store is {}", store);
                        String districtShortName = store.getCode().replaceAll("\\d+", "").substring(2);
                        String stateShortName = store.getCode().replaceAll("\\d+", "").substring(0, 2);
                        DistrictMaster districtMaster = null;
                        LOGGER.info("Store shortname is {}", districtShortName);
                        districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName(districtShortName,
                                        stateShortName);
                        if (districtMaster == null) {
                                districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName("FB", "HR");
                        }
                        LOGGER.info("Store id - {}", store.getId());
                        // com.spice.profitmandi.dao.entity.user.User user = userMap.get(store.getId());
                        String urlString = districtMaster.getStateShortName() + "/"
                                        + Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
                        fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
                        LOGGER.info("Store is {} end", store);

                }
                return fofoRetailerUrlMap;
        }

        @Override
        @Cacheable(value = "storeCodeRetailerMap", cacheManager = "thirtyMinsTimeOutCacheManager")
        public Map<String, Integer> getStoreCodeRetailerMap() {
                Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
                Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
                        String[] splitString = x.getValue().split("/");
                        return splitString[splitString.length - 1];
                }, x -> x.getKey()));
                LOGGER.info("returnMap {}", returnMap);
                return returnMap;
        }

        @Override
        public String getPartnerCriteriaString(PartnerCriteria partnerCriteria) {

                StringBuilder sb = new StringBuilder();
                if (partnerCriteria.getFofoIds().size() > 0) {
                        List<Integer> fofoIds = partnerCriteria.getFofoIds();
                        Map<Integer, CustomRetailer> customRetailers = this.getFofoRetailerUserId(fofoIds);
                        List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName())
                                        .collect(Collectors.toList());
                        sb.append(String.join(", ", businessNames));

                } else {
                        sb.append("All");
                        if (partnerCriteria.getPartnerTypes().size() > 0) {
                                sb.append(" ").append(String.join(", ", partnerCriteria.getPartnerTypes().stream()
                                                .map(x -> x.getValue()).collect(Collectors.toList())));
                        }
                        sb.append(" partners ");
                        if (partnerCriteria.getRegionIds().size() > 0) {
                                sb.append("from ");
                                sb.append(String.join(", ", partnerCriteria.getRegionIds().stream()
                                                .map(x -> ProfitMandiConstants.WAREHOUSE_MAP.get(x)).collect(Collectors.toList())));
                        }
                        if (partnerCriteria.getExcludeFofoIds() != null && partnerCriteria.getExcludeFofoIds().size() > 0) {
                                sb.append("excluding ");
                                Map<Integer, CustomRetailer> customRetailers = this
                                                .getFofoRetailerUserId(partnerCriteria.getExcludeFofoIds());
                                List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName())
                                                .collect(Collectors.toList());
                                sb.append(String.join(", ", businessNames));
                        }
                }
                return sb.toString();
        }

        @Override
        public Map<Integer, CustomRetailer> getFofoRetailersPaginated(boolean activeOnly, int offset, int limit,
                        FofoType fofoType) {

                Stream<FofoStore> storeStream = fofoStoreRepository.selectByStatusFofoType(activeOnly, fofoType, offset, limit)
                                .stream();

                List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
                return this.getFofoRetailers(storeIds);
        }

}