Subversion Repositories SmartDukaan

Rev

Rev 23880 | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.util;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.spice.profitmandi.common.enumuration.ContentType;
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.util.FileUtil;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.entity.dtr.*;
import com.spice.profitmandi.dao.entity.fofo.FofoPartnerPaymentOption;
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
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.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.user.*;
import in.shop2020.model.v1.user.CartStatus;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.*;

@Component
public class
MigrationUtil {
        
        @Autowired
        private DocumentRepository documentRepository;
        
        @Autowired
        private UserRepository userRepository;
        
        @Autowired
        private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
        
        @Autowired
        private CartRepository cartRepository;
        
        @Autowired
        private UserAccountRepository userAccountRepository;
        
        @Autowired
        private RetailerRepository retailerRepository;
        
        @Autowired
        private UserRoleRepository userRoleRepository;
        
        @Autowired
        private AddressRepository addressRepository;
        
        @Autowired
        private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
        
        @Autowired
        private PrivateDealUserRepository privateDealUserRepository;
        
        @Autowired
        private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;
        
        @Autowired
        private CounterRepository counterRepository;
        
        @Autowired
        private ShopRepository shopRepository;
        
        @Autowired
        private ShopAddressRepository shopAddressRepository;
        
        @Autowired
        private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;
        
        @Autowired
        private PaymentOptionRepository paymentOptionRepository;
        
        @Autowired
        private RoleRepository roleRepository;
        
        @Autowired
        private Mongo mongoClient;
        
        
        private static final Logger LOGGER = LogManager.getLogger(MigrationUtil.class);
        
        private List<Map<String, String>> getMongoFofoDoc(){
                String fofoFormsJsonString = mongoClient.getFofoFormsJsonString();
                LOGGER.info("mongoFofoDoc {}", fofoFormsJsonString);
                Gson gson = new Gson();
        Type paths = new TypeToken<List<Map<String, String>>>(){}.getType();
        List<Map<String, String>> maps = gson.fromJson(fofoFormsJsonString, paths);
        return maps;
        }
        
        public void migrateMongoDocToDocumentId() throws ProfitMandiBusinessException{
                List<Map<String, String>> maps = this.getMongoFofoDoc();
        Map<Integer, Map<String, Integer>> fofoIdPathMap = new HashMap<>();
        
        for(Map<String, String> map : maps){
                int id = 0;
                Map<String, Integer> pathMap = new HashMap<>();
                for(Map.Entry<String, String> entry : map.entrySet()){
                        if(entry.getKey().equals("_id")){
                                id = (int)Double.parseDouble(entry.getValue());
                        }
                        if(entry.getValue().startsWith("/hsps-docs/")){
                                
                                Document document = new Document();
                                
                                try{
                                        File srcFile = new File(entry.getValue());
                                        String destFileName = entry.getValue().substring(entry.getValue().lastIndexOf('/') + 1);
                                        String destFilePath = "/uploads/"; 
                                        File destFile = new File(destFilePath + destFileName);
                                        FileUtils.copyFile(srcFile, destFile);
                                        ContentType contentType = FileUtil.detectFileType(srcFile);
                                        document.setContentType(contentType);
                                        document.setName(destFileName);
                                        document.setPath(destFilePath);
                                        document.setPersisted(true);
                                        document.setSize(srcFile.length());
                                        documentRepository.persist(document);
                                        pathMap.put(entry.getKey(), document.getId());
                                }catch(IOException ioException) {
                                        LOGGER.info("IOException occurred");
                                }
                        }
                }
                if(!pathMap.isEmpty()){
                        fofoIdPathMap.put(id, pathMap);
                }
        }
        
        LOGGER.info("fofoIdPathMap {}", fofoIdPathMap);
        for(Map.Entry<Integer, Map<String, Integer>> entry : fofoIdPathMap.entrySet()){
                mongoClient.updateColumnsById(entry.getValue(), entry.getKey());
        }
        
        }
        
        private Set<Integer> toRetailerIds(List<UserAccount> userAccounts){
                Set<Integer> retailerIds = new HashSet<>();
                for(UserAccount saholicUserAccount : userAccounts){
                        int retailerId = saholicUserAccount.getAccountKey();
                        retailerIds.add(retailerId);
                }
                return retailerIds;
        }
        
        private Set<Integer> toUserIds(List<UserAccount> userAccounts, Set<Integer> retailerIds){
                Set<Integer> userIds = new HashSet<>();
                for(UserAccount saholicUserAccount : userAccounts){
                        int retailerId = saholicUserAccount.getAccountKey();
                        if(retailerIds.contains(retailerId)){
                                userIds.add(saholicUserAccount.getUserId());
                        }
                }
                return userIds;
        }
        
        public void migrateUserToRetailer() throws ProfitMandiBusinessException{
                
                List<UserAccount> saholicUserAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userRepository.selectIdAll()));
                if(saholicUserAccounts.isEmpty()){
                        return;
                }
                Set<Integer> retailerIds = this.toRetailerIds(saholicUserAccounts);
                List<Integer> foundRetailerIds = retailerRepository.selectIdsByIds(retailerIds);
                retailerIds.removeAll(foundRetailerIds);
                for(int retailerId : retailerIds){
                        Retailer retailer = new Retailer();
                        try {
                                retailer.setId(retailerId);
                                retailer.setMigrated(true);
                                retailerRepository.persist(retailer);
                                LOGGER.info("Retailer migrated {}", retailerId);
                        } catch (ProfitMandiBusinessException e) {
                                LOGGER.info("Error occured while commiting retailer");
                                e.printStackTrace();
                        }
                }
                
                Set<Integer> userIds = this.toUserIds(saholicUserAccounts, retailerIds);
                
                if(userIds.isEmpty()){
                        return;
                }
                
                Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
                
                List<Integer> foundRetailerRoleUserIds = userRoleRepository.selectUserIdsByUserIdsAndRoleId(userIds, roleRetailer.getId());
                
                Set<Integer> notFoundRetailerRoleUserIds = new HashSet<>(userIds);
                notFoundRetailerRoleUserIds.removeAll(foundRetailerRoleUserIds);
                
                
                
                for(int userId : notFoundRetailerRoleUserIds){
                        UserRole retailerRole = new UserRole();
                        retailerRole.setRoleId(roleRetailer.getId());
                        retailerRole.setUserId(userId);
                        try {
                                userRoleRepository.persist(retailerRole);
                                LOGGER.info("UserId {} with Retailer Role migrated", userId);
                        } catch (ProfitMandiBusinessException e) {
                                e.printStackTrace();
                        }
                }
                
                Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
                
                List<Integer> foundUserRoleUserIds = userRoleRepository.selectUserIdsByUserIdsAndRoleId(userIds, roleUser.getId());
                
                Set<Integer> notFoundUserRoleUserIds = new HashSet<>(userIds);
                notFoundUserRoleUserIds.removeAll(foundUserRoleUserIds);
                
                
                for(int userId : notFoundUserRoleUserIds){
                        UserRole userRole = new UserRole();
                        userRole.setRoleId(roleUser.getId());
                        userRole.setUserId(userId);
                        try {
                                userRoleRepository.persist(userRole);
                                LOGGER.info("UserId {} with User Role migrated", userId);
                        } catch (ProfitMandiBusinessException e) {
                                e.printStackTrace();
                        }
                }
                
        }
        
        public void migrateMongoDocToRetailer() throws ProfitMandiBusinessException{
                List<Map<String, String>> maps = this.getMongoFofoDoc();
                //LOGGER.info("mongoFofoDocs {}", maps);
                for(Map<String, String> map : maps){
                        if(map.containsKey("registeredEmail1")){
                                
                                User user = null;
                                
                                try{
                                        user = userRepository.selectByEmailId(map.get("registeredEmail1"));
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                }
                                if(user == null){
                                        user = userRepository.selectBySecondryEmailId(map.get("registeredEmail1"));
                                }
                                if(user == null){
                                        user = new User();
                                        user.setFirstName("");
                                        user.setLastName("");
                                        user.setCity(map.containsKey("city") ? map.get("city") : "");
                                        user.setPinCode(Integer.valueOf(map.containsKey("pincode") ? map.get("pincode") : ""));
                                        user.setMobileNumber(map.containsKey("mobile") ? map.get("mobile") : "");
                                        user.setEmailId(map.get("registeredEmail1"));
                                        user.setUsername(map.get("registeredEmail1"));
                                        user.setPassword("");
                                        user.setMobile_verified(false);
                                        user.setReferral_url("");
                                        user.setGroup_id(1);
                                        user.setStatus(1);
                                        user.setActivated(true);
                                        user.setCreateTimestamp(LocalDateTime.now());
                                        user.setUpdateTimestamp(LocalDateTime.now());
                                        userRepository.persist(user);
                                }
                                
                                
                                //in.shop2020.model.v1.user.User saholicUser = Utils.createSaholicUser(map.get("registeredEmail1"));
                                
                                com.spice.profitmandi.dao.entity.user.User saholicUser = null;
                                boolean foundRetailer = false;
                                try{
                                        saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        
                                }
                                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(map.containsKey("registeredBusinessName") ? map.get("registeredBusinessName") : "");
                                        saholicUser.setActiveCartId(cart.getId());
                                        saholicUser.setCreateTimestamp(LocalDateTime.now());
                                        userUserRepository.persist(saholicUser);
                                }else{
                                        foundRetailer = true;
                                }
                                
                                Retailer retailer = null;
                                
                                try{
                                        retailer = retailerRepository.selectById(saholicUser.getId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        retailer = new Retailer();
                                }
                                retailer.setActive(true);
                                retailer.setId(saholicUser.getId());
                                retailer.setMigrated(true);
                                retailer.setName(map.containsKey("registeredBusinessName") ? map.get("registeredBusinessName") : "");
                                retailer.setType(RetailerType.GSTIN);
                                retailerRepository.persist(retailer);
                                
                                
                                Address retailerAddress = new Address();
                                
                                List<Address> retailerAddresses = addressRepository.selectAllByRetailerId(retailer.getId(), 1, 100);
                                if(retailerAddresses.isEmpty()){
                                        retailerAddress.setCity(map.containsKey(ProfitMandiConstants.CITY) ? map.get(ProfitMandiConstants.CITY) : "");
                                        retailerAddress.setCountry("India");
                                        retailerAddress.setEnabled(true);
                                        retailerAddress.setLandmark("");
                                        retailerAddress.setLine1(map.containsKey(ProfitMandiConstants.LINE1) ? map.get(ProfitMandiConstants.LINE1) : "");
                                        retailerAddress.setLine2(map.containsKey(ProfitMandiConstants.LINE2) ? map.get(ProfitMandiConstants.LINE2) : "");
                                        retailerAddress.setName(map.containsKey("registeredBusinessName") ? map.get("registeredBusinessName") : "");
                                        retailerAddress.setPhoneNumber(map.containsKey("mobile") ? map.get("mobile") : "");
                                        retailerAddress.setPinCode(map.containsKey("pincode") ? map.get("pincode") : "");
                                        retailerAddress.setState(map.containsKey(ProfitMandiConstants.STATE) ? map.get(ProfitMandiConstants.STATE) : "");
                                        retailerAddress.setRetaierId(retailer.getId());
                                        addressRepository.persist(retailerAddress);
                                }
                                
                                
                                RetailerRegisteredAddress retailerRegisteredAddress = null;
                                try{
                                        retailerRegisteredAddress = retailerRegisteredAddressRepository.selectByAddressIdAndRetailerId(retailerAddress.getId(), retailer.getId());
                                        //retailerRegisteredAddress = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        retailerRegisteredAddress = new RetailerRegisteredAddress();
                                        retailerRegisteredAddress.setAddressId(retailerAddress.getId());
                                        retailerRegisteredAddress.setRetailerId(retailer.getId());
                                        retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
                                }
                                
                                
                                List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
                                if(shops.isEmpty()){
                                        Shop shop = new Shop();
                                        shop.setName(retailer.getName());
                                        shop.setAddressId(retailerAddress.getId());
                                        shop.setDocumentId(retailer.getDocumentId());
                                        shop.setRetailerId(retailer.getId());
                                        shopRepository.persist(shop);
                                        ShopAddress shopAddress = new ShopAddress();
                                        shopAddress.setAddressId(retailerAddress.getId());
                                        shopAddress.setShopId(shop.getId());
                                        shopAddressRepository.persist(shopAddress);
                                }
                                
                                UserAccount saholicUserAccounts = null;
                                try{
                                        saholicUserAccounts = userAccountRepository.selectByUserIdRetailerIdAccountType(user.getId(), retailer.getId(), AccountType.saholic);
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        saholicUserAccounts = new UserAccount();
                                        saholicUserAccounts.setAccountKey(saholicUser.getId());
                                        saholicUserAccounts.setType(AccountType.saholic);
                                        saholicUserAccounts.setUserId(user.getId());
                                        userAccountRepository.persist(saholicUserAccounts);
                                        UserAccount cartUserAccounts = new UserAccount();
                                        cartUserAccounts.setAccountKey(saholicUser.getActiveCartId());
                                        cartUserAccounts.setType(AccountType.cartId);
                                        cartUserAccounts.setUserId(user.getId());
                                        userAccountRepository.persist(cartUserAccounts);
                                }
                                
                                Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
                                
                                UserRole userRole = null;
                                
                                try{
                                        userRole = userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleUser.getId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        Role role = roleRepository.selectByName(RoleType.USER.toString());
                                        userRole = new UserRole();
                                        userRole.setRoleId(role.getId());
                                        userRole.setUserId(user.getId());
                                        userRoleRepository.persist(userRole);
                                }
                                
                                Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
                                
                                UserRole retailerRole = null;
                                try{
                                        retailerRole = userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleRetailer.getId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        Role role = roleRepository.selectByName(RoleType.RETAILER.toString());
                                        retailerRole = new UserRole();
                                        retailerRole.setRoleId(role.getId());
                                        retailerRole.setUserId(user.getId());
                                        userRoleRepository.persist(retailerRole);
                                }
                                
                                Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
                                
                                UserRole fofoRole = null;
                                try{
                                        fofoRole = userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
                                }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                        Role role = roleRepository.selectByName(RoleType.FOFO.toString());
                                        fofoRole = new UserRole();
                                        fofoRole.setRoleId(role.getId());
                                        fofoRole.setUserId(user.getId());
                                        userRoleRepository.persist(fofoRole);
                                }
                                
                                List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(retailer.getId());
                                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(retailer.getId());
                                        fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
                                        fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
                                }
                                
                                if(foundRetailer){
                                        LOGGER.info("\n\n\n****retailer found\n\n\n");
                                        PrivateDealUser privateDealUser = null;
                                        try{
                                                privateDealUser = privateDealUserRepository.selectById(saholicUser.getId());
                                        }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                                LOGGER.error("PrivateDealUser not found : ", profitMandiBusinessException);
                                        }
                                        
                                         //= privateDealUserRepository.selectById(saholicUser.getId());
                                        if(privateDealUser == null){
                                                Integer counterId = this.createCounter(user.getEmailId(), map.get("gst"), user.getMobileNumber(), retailer.getName(), retailerAddress.getId());
                                                this.createPrivateDealUser(saholicUser.getId(), counterId);
                                        }else{
                                                if(privateDealUser.getCounterId() == null){
                                                        Integer counterId = this.createCounter(user.getEmailId(), map.get("gst"), user.getMobileNumber(), retailer.getName(), retailerAddress.getId());
                                                        privateDealUser.setCounterId(counterId);
                                                        privateDealUser.setFofo(true);
                                                        privateDealUserRepository.persist(privateDealUser);
                                                }
                                        }
                                }else{
                                        LOGGER.info("retailer not found");
                                        //gst number intergration with counter
                                        Integer counterId = this.createCounter(user.getEmailId(), map.get("gst"), user.getMobileNumber(), retailer.getName(), retailerAddress.getId());
                                        PrivateDealUser privateDealUser = null;
                                        try{
                                                privateDealUser = privateDealUserRepository.selectById(saholicUser.getId());
                                        }catch(ProfitMandiBusinessException profitMandiBusinessException){
                                                LOGGER.error("PrivateDealUser not found : ", profitMandiBusinessException);
                                        }
                                        /* //= privateDealUserRepository.selectById(saholicUser.getId());
                                        if(privateDealUser == null){
                                                int counterId = this.createCounter(user.getEmailId(), map.get("gst"), user.getMobileNumber(), retailer.getName(), retailerAddress.getId());
                                                this.createPrivateDealUser(saholicUser.getId(), counterId);
                                        }*/
                                        
                                                
                                        if(privateDealUser != null){
                                                //LOGGER.info("PrivateDealUser found with id [{}]", saholicUser.getId());
                                                privateDealUser.setCounterId(counterId);
                                                privateDealUser.setFofo(true);
                                                privateDealUserRepository.update(privateDealUser);
                                        }else{  
                                                LOGGER.info("PrivateDealUser not found with id [{}]", saholicUser.getId());
                                                this.createPrivateDealUser(saholicUser.getId(), counterId);
                                        }
                                        PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
                                        privateDealUserAddressMapping.setUserId(retailer.getId());
                                        privateDealUserAddressMapping.setAddressId(retailerAddress.getId());
                                        privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
                                        
                                        saholicUser.setAddressId(retailerAddress.getId());
                                        userUserRepository.persist(saholicUser);
                                }
                        }
                        
                }
                
                
        }
        
        //Specifically set isFofo to true that has to be used by old system
        private void createPrivateDealUser(int retailerId, int counterId){
                PrivateDealUser privateDealUser = new PrivateDealUser();
                privateDealUser.setActive(true);
                privateDealUser.setBulkShipmentAmountLimit(100000);
                privateDealUser.setId(retailerId);
                privateDealUser.setCounterId(counterId);
                privateDealUser.setFofo(true);
                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);
                        counter.setCreatedOn(LocalDateTime.now());
                        counterRepository.persist(counter);
                        return counter.getId();
                }else{
                        return null;
                }
        }
        
        public void migratePrivateDealToRetailer(){
                
        }
}