com.stoxx.portlet.preregcustomeradmin.delegate.CustomerAdminDelegate.java Source code

Java tutorial

Introduction

Here is the source code for com.stoxx.portlet.preregcustomeradmin.delegate.CustomerAdminDelegate.java

Source

package com.stoxx.portlet.preregcustomeradmin.delegate;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.mail.MessagingException;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import com.liferay.portal.NoSuchRoleException;
import com.liferay.portal.NoSuchUserException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.language.LanguageUtil;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ArrayUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ListUtil;
import com.liferay.portal.kernel.util.PrefsPropsUtil;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Country;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.model.UserGroup;
import com.liferay.portal.service.CountryServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.service.UserGroupLocalServiceUtil;
import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.theme.ThemeDisplay;
import com.stoxx.digital.platform.NoSuchEmailDomainException;
import com.stoxx.digital.platform.NoSuchSalesEntryException;
import com.stoxx.digital.platform.model.EmailDomain;
import com.stoxx.digital.platform.model.SalesEntry;
import com.stoxx.digital.platform.service.EmailDomainLocalServiceUtil;
import com.stoxx.digital.platform.service.SalesEntryLocalServiceUtil;
import com.stoxx.portlet.datatransformer.PreRegCustomerRegistrationTransformer;
import com.stoxx.portlet.model.PreRegAdminVO;
import com.stoxx.portlet.model.SalesEntryEditVO;
import com.stoxx.service.business.manageuser.ManageUserService;
import com.stoxx.service.business.packagedetails.PackageDetailsService;
import com.stoxx.service.business.userprofile.UserProfileService;
import com.stoxx.service.constant.STOXXConstants;
import com.stoxx.service.domain.userprofile.UserProfileDetails;
import com.stoxx.service.exception.STOXXException;
import com.stoxx.service.util.STOXXDateUtil;
import com.stoxx.service.util.STOXXEncrypter;
import com.stoxx.service.util.STOXXMailUtil;

public class CustomerAdminDelegate {

    private static final String STOXX_KEY_ACCOUNT_HOLDER_ROLE = "STOXX_KEY_ACCOUNT_HOLDER_ROLE";
    private static final String KEY_SKIPPED_EMAILS = "SKIPPED_EMAILS";
    private static final String KEY_SKIPPED_DOMAINS = "SKIPPED_DOMAINS";

    private static final String USERGROUP_CUSTOMER = "Customer";

    private static final String ENCRYPTION_KEY = "URL-4A144BEBF7EVE7B7DCF26491AE";

    private static Log log = LogFactoryUtil.getLog(CustomerAdminDelegate.class.getName());

    private UserProfileService userProfileService;

    private ManageUserService manageUserService;

    private PackageDetailsService packageDetailsService;

    private STOXXMailUtil stoxxMailUtil;

    public void setUserProfileService(UserProfileService userProfileService) {
        this.userProfileService = userProfileService;
    }

    public UserProfileService getUserProfileService() {
        return userProfileService;
    }

    public ManageUserService getManageUserService() {
        return manageUserService;
    }

    public void setManageUserService(ManageUserService manageUserService) {
        this.manageUserService = manageUserService;
    }

    public PackageDetailsService getPackageDetailsService() {
        return packageDetailsService;
    }

    public void setPackageDetailsService(PackageDetailsService packageDetailsService) {
        this.packageDetailsService = packageDetailsService;
    }

    public STOXXMailUtil getStoxxMailUtil() {
        return stoxxMailUtil;
    }

    public void setStoxxMailUtil(STOXXMailUtil stoxxMailUtil) {
        this.stoxxMailUtil = stoxxMailUtil;
    }

    public void createStoxxUser(String email, String activationLink, Long salesEntryId, String companyName)
            throws STOXXException {
        UserProfileDetails userProfileDetails = new UserProfileDetails();
        userProfileDetails.setEmailAddress(email);
        userProfileDetails.setUserType(STOXXConstants.STOXX_REGISTERED_USER);
        userProfileDetails.setActivationLink(activationLink);
        userProfileDetails.setSalesEntryId(salesEntryId);
        userProfileDetails.setCompanyName(companyName);
        userProfileDetails.setActivationLinkCreatedDate(STOXXDateUtil.convertToSqlDate(new Date()));
        userProfileService.saveUserProfile(userProfileDetails);
    }

    public Boolean checkUserExists(String email) throws STOXXException {
        return userProfileService.checkUserExists(email);
    }

    public List<Country> getAllCountries() throws SystemException {
        return CountryServiceUtil.getCountries();
    }

    public List<String> getAllPackages() {
        return packageDetailsService.getAllPackageNames();
    }

    public Map<String, List<String>> addSalesEntry(PreRegAdminVO preRegAdminVO, ThemeDisplay themeDisplay)
            throws STOXXException, SystemException, PortalException {
        Map<String, List<String>> resultMap = initiateResultMap();

        boolean userLicenseSelected = Boolean.TRUE;
        String keyAccountHolderEmailAddress = preRegAdminVO.getKeyAccountHolderEmailAddress();

        validateForKeyAccountHolderForSalesEntryCreation(keyAccountHolderEmailAddress);

        log.info("Adding sales entry with information: " + preRegAdminVO);
        Date startDate = STOXXDateUtil.convertStringToUtilDate(preRegAdminVO.getLicenseStartDate());
        Date endDate = STOXXDateUtil.convertStringToUtilDate(preRegAdminVO.getLicenseEndDate());
        boolean isDomainLicense = !isEmptyStringList(preRegAdminVO.getDomains());

        SalesEntry salesEntry = SalesEntryLocalServiceUtil.addSalesEntry(preRegAdminVO.getCompanyName(),
                preRegAdminVO.getGroupName(), preRegAdminVO.getProfile(), preRegAdminVO.getPackages(), startDate,
                endDate, preRegAdminVO.getCountryId(), userLicenseSelected, preRegAdminVO.getUsersAllowed(),
                isDomainLicense);
        log.info("Sales entry created with salesEntryId=" + salesEntry.getSalesEntryId());
        log.info("Processing user licenses for sales entry with id = " + salesEntry.getSalesEntryId());
        if (Validator.isNotNull(keyAccountHolderEmailAddress)) {
            processKeyAccountHolderEmail(themeDisplay, resultMap, keyAccountHolderEmailAddress,
                    salesEntry.getSalesEntryId(), salesEntry.getCompanyName());
        }
        List<String> emailAddresses = preRegAdminVO.getEmailAddresses();
        if (emailAddresses != null) {
            for (String emailAddress : emailAddresses) {
                if (Validator.isNotNull(emailAddress)) {
                    processCustomerEmailAddress(themeDisplay, resultMap, salesEntry.getSalesEntryId(),
                            salesEntry.getCompanyName(), emailAddress);
                }
            }
        }

        log.info("Processing domain licenses for sales entry with id " + salesEntry.getSalesEntryId());
        List<String> domains = preRegAdminVO.getDomains();
        if (domains != null) {
            for (String domain : domains) {
                if (Validator.isNotNull(domain)) {
                    processDomain(resultMap, salesEntry.getSalesEntryId(), domain);
                }
            }
        }

        return resultMap;
    }

    private boolean isEmptyStringList(List<String> stringList) {
        return Validator.isNull(StringUtil.trim(ListUtil.toString(stringList, "", "")));
    }

    private void processDomain(Map<String, List<String>> resultMap, long salesEntryId, String domain)
            throws SystemException {
        if (!domain.startsWith(StringPool.AT)) {
            domain = StringPool.AT + domain;
        }
        domain = StringUtil.toLowerCase(domain);
        try {
            EmailDomain emailDomain = EmailDomainLocalServiceUtil.getEmailDomain(domain);
            if (emailDomain.getSalesEntryId() != salesEntryId) {
                log.info("Domain '" + domain + "' already associated with another sales entry id :"
                        + emailDomain.getSalesEntryId());
                addToSkippedDomain(resultMap, domain);
            }
        } catch (NoSuchEmailDomainException e1) {
            EmailDomainLocalServiceUtil.addEmailDomain(salesEntryId, domain);
            log.info("Domain '" + domain + "' added succssfully with sales entry id: " + salesEntryId);
        }
    }

    private void processCustomerEmailAddress(ThemeDisplay themeDisplay, Map<String, List<String>> resultMap,
            long salesEntryId, String companyName, String emailAddress)
            throws SystemException, STOXXException, PortalException {
        processCustomerEmailAddress(themeDisplay, resultMap, salesEntryId, companyName, emailAddress, null, null);
    }

    private void processKeyAccountHolderEmail(ThemeDisplay themeDisplay, Map<String, List<String>> resultMap,
            String keyAccountHolderEmailAddress, long salesEntryId, String companyName)
            throws SystemException, STOXXException, PortalException {
        processKeyAccountHolderEmail(themeDisplay, resultMap, keyAccountHolderEmailAddress, salesEntryId,
                companyName, null, null);
    }

    private void processKeyAccountHolderEmail(ThemeDisplay themeDisplay, Map<String, List<String>> resultMap,
            String keyAccountHolderEmailAddress, long salesEntryId, String companyName, List<Long> roleIdsToRemove,
            List<Long> roleIdsToAdd) throws STOXXException, SystemException, PortalException {
        UserProfileDetails userProfileDetail = getUserProfileDetail(keyAccountHolderEmailAddress);
        processEmailAddress(themeDisplay, resultMap, salesEntryId, companyName, keyAccountHolderEmailAddress,
                userProfileDetail, true, roleIdsToRemove, roleIdsToAdd);
    }

    private void processCustomerEmailAddress(ThemeDisplay themeDisplay, Map<String, List<String>> resultMap,
            long salesEntryId, String companyName, String emailAddress, List<Long> roleIdsToRemove,
            List<Long> roleIdsToAdd) throws STOXXException, SystemException, PortalException {
        UserProfileDetails userProfileDetail = getUserProfileDetail(emailAddress);
        processEmailAddress(themeDisplay, resultMap, salesEntryId, companyName, emailAddress, userProfileDetail,
                false, roleIdsToRemove, roleIdsToAdd);
    }

    private void processEmailAddress(ThemeDisplay themeDisplay, Map<String, List<String>> resultMap,
            long salesEntryId, String companyName, String emailAddress, UserProfileDetails userProfileDetail,
            boolean isKeyAccountHolder, List<Long> roleIdsToRemove, List<Long> roleIdsToAdd)
            throws STOXXException, SystemException, PortalException {
        log.info("Processing email address:" + emailAddress);
        long companyId = themeDisplay.getCompanyId();
        if (Validator.isNotNull(emailAddress)) {
            emailAddress = StringUtil.toLowerCase(emailAddress);
            if (userProfileDetail == null) {
                log.info("Creating new user as customer with email:" + emailAddress);
                boolean userCreationSuccess = createNewCustomer(themeDisplay, emailAddress, salesEntryId,
                        companyName, isKeyAccountHolder);
                if (!userCreationSuccess) {
                    addToSkippedEmails(resultMap, emailAddress);
                } else if (isKeyAccountHolder) {
                    try {
                        SalesEntryLocalServiceUtil.updateKeyAccountHolderEmail(salesEntryId, emailAddress);
                    } catch (NoSuchSalesEntryException e) {
                        log.error("Sales entry not found with id " + salesEntryId
                                + " while updating key account holder");
                    }
                }
            } else if (Validator.equals(userProfileDetail.getStatus(), Integer.valueOf(4))) {
                boolean deletedUserHandled = handleDeletedUser(userProfileDetail, salesEntryId, companyName,
                        themeDisplay, isKeyAccountHolder);
                if (!deletedUserHandled) {
                    addToSkippedEmails(resultMap, emailAddress);
                } else if (isKeyAccountHolder) {
                    try {
                        SalesEntryLocalServiceUtil.updateKeyAccountHolderEmail(salesEntryId, emailAddress);
                    } catch (NoSuchSalesEntryException e) {
                        log.error("Sales entry not found with id " + salesEntryId
                                + " while updating key account holder");
                    }
                }
            } else if (STOXXConstants.STOXX_GENERAL_USER.equals(userProfileDetail.getUserType())) {
                boolean userTypeChangeSuccess = changeGeneralUserToCustomer(userProfileDetail, salesEntryId,
                        themeDisplay);
                if (userTypeChangeSuccess) {
                    List<Long> roleIdList = new ArrayList<Long>();
                    SalesEntry salesEntry = SalesEntryLocalServiceUtil.getSalesEntry(salesEntryId);
                    if (Validator.isNotNull(salesEntry)) {
                        String packageNames = salesEntry.getPackageNames();
                        String[] roleNames = StringUtils.split(packageNames, StringPool.COMMA);
                        if (ArrayUtils.isNotEmpty(roleNames)) {
                            for (String role : roleNames) {
                                Role liferayRole = RoleLocalServiceUtil.fetchRole(companyId, role.trim());
                                if (Validator.isNotNull(liferayRole)) {
                                    roleIdList.add(liferayRole.getRoleId());
                                }
                            }
                        }
                    }
                    if (Validator.isNotNull(roleIdList) && roleIdList.size() > 0) {
                        roleIdsToAdd = new ArrayList<Long>();
                        roleIdsToAdd.addAll(roleIdList);
                    }
                    updateRoleAssignments(themeDisplay, roleIdsToRemove, roleIdsToAdd,
                            userProfileDetail.getEmailAddress());
                    if (isKeyAccountHolder) {
                        log.info("Updating sales entry with KAH=" + emailAddress);
                        try {
                            SalesEntryLocalServiceUtil.updateKeyAccountHolderEmail(salesEntryId, emailAddress);
                            try {
                                User existingKAHUser = UserLocalServiceUtil
                                        .getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);
                                Role gatewayUserRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                                        STOXX_KEY_ACCOUNT_HOLDER_ROLE);
                                RoleLocalServiceUtil.addUserRole(existingKAHUser.getUserId(), gatewayUserRole);
                            } catch (NoSuchUserException ex) {
                                log.error("Key acount holder not yet registered. " + ex.getMessage());
                            } catch (PortalException ex) {
                                log.error("PortalException while adding key account holder role to user.", ex);
                            }
                        } catch (NoSuchSalesEntryException e) {
                            log.error("Sales entry not found with id " + salesEntryId
                                    + " while updating key account holder");
                        }
                    }
                } else {
                    log.info("Adding emailAddress '" + emailAddress
                            + "' to skipped list because unable to convert it to customer.");
                    addToSkippedEmails(resultMap, emailAddress);
                }

            } else if (STOXXConstants.STOXX_STAFF_USER.equals(userProfileDetail.getUserType())) {
                log.info("Skipping emailaddress '" + emailAddress + "' as it is staff in system.");
                addToSkippedEmails(resultMap, emailAddress);
            } else if (STOXXConstants.STOXX_VENDOR_USER.equals(userProfileDetail.getUserType())) {
                log.info("Skipping emailaddress '" + emailAddress + "' as it is vendor in system.");
                addToSkippedEmails(resultMap, emailAddress);
            } else if (GetterUtil.getLong(userProfileDetail.getSalesEntryId()) != salesEntryId) {
                log.info("Skipping emailaddress '" + emailAddress
                        + "' as it is customer for another sales entry id:" + userProfileDetail.getSalesEntryId());
                addToSkippedEmails(resultMap, emailAddress);
            } else if (Validator.isNotNull(userProfileDetail.getSalesEntryId())
                    && STOXXConstants.STOXX_REGISTERED_USER.equalsIgnoreCase(userProfileDetail.getUserType())
                    && GetterUtil.getLong(userProfileDetail.getSalesEntryId()) == salesEntryId) {
                SalesEntry salesEntry = SalesEntryLocalServiceUtil
                        .getSalesEntry(userProfileDetail.getSalesEntryId());
                log.info("salesEntry Id latest   is    >>> " + salesEntry.getSalesEntryId());
                boolean isKeyAccountRole = Boolean.FALSE;
                String keyEmailAddress = salesEntry.getKeyEmailAddress();
                log.info("salesEntry Id latest   is    >>> " + keyEmailAddress + " and the emailAddress is "
                        + emailAddress);
                if (StringUtils.isNotBlank(keyEmailAddress) && keyEmailAddress.equalsIgnoreCase(emailAddress)) {
                    isKeyAccountRole = Boolean.TRUE;
                }
                log.info("from front end isKeyAccountRole is >>> " + isKeyAccountRole
                        + " and from back end isKeyAccountRole >>> " + isKeyAccountRole);

                if ((isKeyAccountHolder && isKeyAccountRole) || (!isKeyAccountHolder && !isKeyAccountRole)) {
                    log.info("Skipping emailaddress '" + emailAddress
                            + "' as it is customer for another sales entry id:"
                            + userProfileDetail.getSalesEntryId());
                    addToSkippedEmails(resultMap, emailAddress);

                }
            }
        }
    }

    private boolean handleDeletedUser(UserProfileDetails userProfileDetail, long salesEntryId, String companyName,
            ThemeDisplay themeDisplay, boolean isKeyAccountHolder) {
        boolean result = false;
        String emailAddress = userProfileDetail.getEmailAddress().toLowerCase();
        try {
            String encryptedEmailId = STOXXEncrypter.encrypt(emailAddress, ENCRYPTION_KEY);
            String ownActivationLink = themeDisplay.getPortalURL() + themeDisplay.getRequest().getContextPath()
                    + PrefsPropsUtil.getString("stoxx-pre-reg-admin-acount-registration") + encryptedEmailId;

            userProfileDetail.setUserType(STOXXConstants.STOXX_REGISTERED_USER);
            userProfileDetail.setActivationLink(ownActivationLink);
            userProfileDetail.setSalesEntryId(salesEntryId);
            userProfileDetail.setCompanyName(companyName);
            userProfileDetail.setActivationLinkCreatedDate(STOXXDateUtil.convertToSqlDate(new Date()));
            userProfileDetail.setStatus(4);
            userProfileService.updateUserProfileDetails(userProfileDetail);

            if (isKeyAccountHolder) {
                String accountDetailLink = themeDisplay.getPortalURL() + themeDisplay.getRequest().getContextPath()
                        + PrefsPropsUtil.getString("stoxx-pre-reg-acount-registration");
                sendActivationEmailToKeyAccountHolder(emailAddress, ownActivationLink, accountDetailLink,
                        themeDisplay.getLocale());
            } else {
                sendActivationEmailToCustomer(emailAddress, ownActivationLink, themeDisplay.getLocale());
            }
            result = true;
        } catch (SystemException e) {
            log.error("SystemException in CustomerAdminController", e);
        } catch (STOXXException e) {
            log.error("Unable to save stoxx user with email address:" + emailAddress, e);
        } catch (MessagingException e) {
            log.error("Unable to send activation email to address:" + emailAddress, e);
        }
        return result;
    }

    private void updateRoleAssignments(ThemeDisplay themeDisplay, List<Long> roleIdsToRemove,
            List<Long> roleIdsToAdd, String emailAddress2) throws SystemException {
        try {
            User user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress2);
            if (Validator.isNotNull(roleIdsToRemove) && !roleIdsToRemove.isEmpty()) {
                log.info("Deleting removed package roles to user " + user.getEmailAddress());
                RoleLocalServiceUtil.deleteUserRoles(user.getUserId(), ArrayUtil.toLongArray(roleIdsToRemove));
            }
            if (Validator.isNotNull(roleIdsToAdd) && !roleIdsToAdd.isEmpty()) {
                log.info("Adding added package roles to user " + user.getEmailAddress());
                RoleLocalServiceUtil.addUserRoles(user.getUserId(), ArrayUtil.toLongArray(roleIdsToAdd));
            }
        } catch (NoSuchUserException nsue) {
            log.info(nsue.getMessage());
        } catch (PortalException pe) {
            log.error(pe.getMessage());
        }
    }

    private boolean createNewCustomer(ThemeDisplay themeDisplay, String emailAddress, long salesEntryId,
            String companyName, boolean isKeyAccountHolder) {
        boolean result = false;
        try {
            String encryptedEmailId = STOXXEncrypter.encrypt(emailAddress, ENCRYPTION_KEY);
            String ownActivationLink = themeDisplay.getPortalURL() + themeDisplay.getRequest().getContextPath()
                    + PrefsPropsUtil.getString("stoxx-pre-reg-admin-acount-registration") + encryptedEmailId;
            createStoxxUser(emailAddress.toLowerCase(), ownActivationLink, salesEntryId, companyName);
            if (isKeyAccountHolder) {
                String accountDetailLink = themeDisplay.getPortalURL() + themeDisplay.getRequest().getContextPath()
                        + PrefsPropsUtil.getString("stoxx-pre-reg-acount-registration");
                sendActivationEmailToKeyAccountHolder(emailAddress, ownActivationLink, accountDetailLink,
                        themeDisplay.getLocale());
            } else {
                sendActivationEmailToCustomer(emailAddress, ownActivationLink, themeDisplay.getLocale());
            }
            result = true;
        } catch (SystemException e) {
            log.error("SystemException in CustomerAdminController", e);
        } catch (STOXXException e) {
            log.error("Unable to save stoxx user with email address:" + emailAddress, e);
        } catch (MessagingException e) {
            log.error("Unable to send activation email to address:" + emailAddress, e);
        }
        return result;
    }

    private void sendActivationEmailToKeyAccountHolder(String emailAddress, String ownActivationLink,
            String accountDetailLink, Locale locale) throws SystemException, MessagingException {
        Map<String, Object> emailBodyMap = new HashMap<String, Object>();
        emailBodyMap.put("userActivationLink", ownActivationLink);
        emailBodyMap.put("staffActivationLink", accountDetailLink);
        emailBodyMap.put("fromName", PrefsPropsUtil.getString("stoxx-mail-from-name"));
        emailBodyMap.put("fromAddress", PropsUtil.get("stoxx-prereg-customer-admin-mail-from-address"));
        emailBodyMap.put("portalURL", PrefsPropsUtil.getString("stoxx-mail-from-url"));
        log.info("Sending activation link to key account holder user " + emailAddress);
        sendActivationEmail(emailAddress, locale, emailBodyMap, "templates/translatorActivationMail.vm");
    }

    private void sendActivationEmailToCustomer(String emailAddress, String ownActivationLink, Locale locale)
            throws SystemException, MessagingException {
        Map<String, Object> emailBodyMap = new HashMap<String, Object>();
        emailBodyMap.put("userActivationLink", ownActivationLink);
        emailBodyMap.put("fromName", PrefsPropsUtil.getString("stoxx-mail-from-name"));
        emailBodyMap.put("fromAddress", PropsUtil.get("stoxx-prereg-customer-admin-mail-from-address"));
        emailBodyMap.put("portalURL", PrefsPropsUtil.getString("stoxx-mail-from-url"));
        log.info("Sending activation link to customer user " + emailAddress);
        sendActivationEmail(emailAddress, locale, emailBodyMap, "templates/customerActivationMail.vm");
    }

    private void sendActivationEmail(String emailAddress, Locale locale, Map<String, Object> emailBodyMap,
            String emailVelocityTemplate) throws MessagingException {
        stoxxMailUtil.sendEmailNotification(emailAddress,
                PropsUtil.get("stoxx-prereg-customer-admin-mail-from-address"), emailVelocityTemplate,
                LanguageUtil.get(locale, "stoxx-prereg-email-subject"), emailBodyMap);
    }

    private void validateForKeyAccountHolderForSalesEntryCreation(String keyAccountHolderEmailAddress)
            throws STOXXException {
        if (Validator.isNotNull(keyAccountHolderEmailAddress)) {
            log.info("Validating key account holder email address:" + keyAccountHolderEmailAddress);
            UserProfileDetails kahUserProfileDetail = getUserProfileDetail(keyAccountHolderEmailAddress);
            log.info("KAH user profile detail: " + kahUserProfileDetail);
            boolean isDeletedUser = (kahUserProfileDetail != null
                    && Validator.equals(kahUserProfileDetail.getStatus(), Integer.valueOf(4)));
            if (kahUserProfileDetail != null && GetterUtil.getLong(kahUserProfileDetail.getSalesEntryId()) > 0) {
                throw new STOXXException("KAHInAnotherSE",
                        "Key account holder already member of another sales entry.");
            } else if (kahUserProfileDetail != null
                    && STOXXConstants.STOXX_VENDOR_USER.equals(kahUserProfileDetail.getUserType())
                    && !isDeletedUser) {
                throw new STOXXException("KAHIsVendor",
                        "Key account holder vendor, can't become key account holder");
            } else if (kahUserProfileDetail != null
                    && STOXXConstants.STOXX_STAFF_USER.equals(kahUserProfileDetail.getUserType())
                    && !isDeletedUser) {
                throw new STOXXException("KAHIsStaff", "Key account holder staff, can't become key account holder");
            }
        }
    }

    private void addToSkippedEmails(Map<String, List<String>> resultMap, String emailAddress) {
        resultMap.get(KEY_SKIPPED_EMAILS).add(emailAddress);
    }

    private UserProfileDetails getUserProfileDetail(String emailAddress) throws STOXXException {
        UserProfileDetails userProfileDetail = userProfileService.getUserProfileData(emailAddress);
        if (userProfileDetail != null && Validator.isNull(userProfileDetail.getEmailAddress())) {
            userProfileDetail = null;
        }
        return userProfileDetail;
    }

    private boolean changeGeneralUserToCustomer(UserProfileDetails userProfileDetail, long salesEntryId,
            ThemeDisplay themeDisplay) {
        log.info("Changing general user to customer with email address:" + userProfileDetail.getEmailAddress()
                + " and salesEntryId:" + salesEntryId);
        boolean changeSuccess = false;
        userProfileDetail.setUserType(STOXXConstants.STOXX_REGISTERED_USER);
        userProfileDetail.setSalesEntryId(salesEntryId);
        try {
            userProfileService.updateUserProfileDetails(userProfileDetail);
            User liferayUser = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(),
                    userProfileDetail.getEmailAddress());
            UserGroup customerUserGroup = UserGroupLocalServiceUtil.getUserGroup(themeDisplay.getCompanyId(),
                    USERGROUP_CUSTOMER);
            UserLocalServiceUtil.addUserGroupUser(customerUserGroup.getUserGroupId(), liferayUser.getUserId());
            UserGroup customerSalesEntryGroup = UserGroupLocalServiceUtil.getUserGroup(themeDisplay.getCompanyId(),
                    STOXXConstants.STOXX_SALES_ENTRY);
            UserLocalServiceUtil.addUserGroupUser(customerSalesEntryGroup.getUserGroupId(),
                    liferayUser.getUserId());
            changeSuccess = true;
            log.info("User '" + userProfileDetail.getEmailAddress() + "' changed to customer successfully!");
        } catch (STOXXException e) {
            log.error("Unable to convert user '" + userProfileDetail.getEmailAddress() + "' to customer.");
        } catch (SystemException e) {
            log.error(
                    "SystemException: Unable to update liferay information while changing user type to customer for email '"
                            + userProfileDetail.getEmailAddress() + "'");
        } catch (PortalException e) {
            log.error(
                    "PortalException: Unable to update liferay information while changing user type to customer for email '"
                            + userProfileDetail.getEmailAddress() + "'");
        }
        return changeSuccess;
    }

    /**
     * Return true if sales entry exist with group name
     * @param groupName
     * @return
     * @throws SystemException
     */
    public boolean hasSalesEntryByGroupName(String groupName) throws SystemException {
        boolean hasSalesEntryByGroupName = false;
        try {
            hasSalesEntryByGroupName = SalesEntryLocalServiceUtil.getSalesEntryByGroupName(groupName) != null;
        } catch (NoSuchSalesEntryException e) {
            log.debug("No sales entry exist by group name '" + groupName + "'");
        }
        return hasSalesEntryByGroupName;
    }

    public SalesEntryEditVO getSalesEntry(long salesEntryId)
            throws PortalException, SystemException, STOXXException {
        SalesEntry salesEntry = SalesEntryLocalServiceUtil.getSalesEntry(salesEntryId);
        SalesEntryEditVO salesEntryEditVO = PreRegCustomerRegistrationTransformer
                .convertToSalesEntryEditVO(salesEntry);
        if (salesEntry.isDomainLicense()) {
            List<EmailDomain> emailDomainsOfSalesEntry = EmailDomainLocalServiceUtil.getEmailDomains(salesEntryId);
            log.info("Total domain in sales entry are :" + emailDomainsOfSalesEntry.size());
            salesEntryEditVO.setDomains(
                    PreRegCustomerRegistrationTransformer.convertToDomainsList(emailDomainsOfSalesEntry));
        }
        if (salesEntry.isUserLicense()) {
            salesEntryEditVO.setUsedUserLicenses(userProfileService.getLicensedUsers(salesEntryId).size());
        }
        return salesEntryEditVO;
    }

    public Map<String, List<String>> updateSalesEntry(SalesEntryEditVO salesEntryEditVO, ThemeDisplay themeDisplay)
            throws STOXXException, PortalException, SystemException {
        Map<String, List<String>> resultMap = initiateResultMap();

        SalesEntry existingSalesEntry = SalesEntryLocalServiceUtil
                .getSalesEntry(salesEntryEditVO.getSalesEntryId());
        String newKAHEmailAddress = salesEntryEditVO.getKeyAccountHolderEmailAddress();
        String existingKAHEmailAddress = existingSalesEntry.getKeyEmailAddress();
        List<String> existingPagkageList = ListUtil.fromString(existingSalesEntry.getPackageNames(),
                StringPool.COMMA);
        long salesEntryId = existingSalesEntry.getSalesEntryId();
        if (Validator.isNotNull(newKAHEmailAddress)
                && !newKAHEmailAddress.equalsIgnoreCase(existingKAHEmailAddress)) {
            UserProfileDetails userProfileDetails = getUserProfileDetail(newKAHEmailAddress);
            if (userProfileDetails == null) {
                processEmailAddress(themeDisplay, resultMap, salesEntryId, salesEntryEditVO.getCompanyName(),
                        newKAHEmailAddress, null, true, null, null);
            } else {
                if (STOXXConstants.STOXX_STAFF_USER.equals(userProfileDetails.getUserType())) {
                    throw new STOXXException("KAHIsStaff",
                            "Key account holder staff, can't become key account holder");
                } else if (STOXXConstants.STOXX_VENDOR_USER.equals(userProfileDetails.getUserType())) {
                    throw new STOXXException("KAHIsVendor",
                            "Key account holder vendor, can't become key account holder");
                } else if (userProfileDetails.getSalesEntryId() != null
                        && userProfileDetails.getSalesEntryId() != salesEntryId) {
                    throw new STOXXException("KAHInAnotherSE",
                            "Key account holder already member of another sales entry.");
                } else if (Validator.equals(userProfileDetails.getStatus(), Integer.valueOf(4))) {
                    processEmailAddress(themeDisplay, resultMap, salesEntryId, salesEntryEditVO.getCompanyName(),
                            newKAHEmailAddress, userProfileDetails, true, null, null);
                }
            }
        }
        List<String> domains = salesEntryEditVO.getDomains();
        if (domains == null) {
            domains = new ArrayList<String>(0);
        }

        boolean isDomainLicense = !isEmptyStringList(domains);

        Date startDate = STOXXDateUtil.convertStringToUtilDate(salesEntryEditVO.getLicenseStartDate());
        Date endDate = STOXXDateUtil.convertStringToUtilDate(salesEntryEditVO.getLicenseEndDate());
        SalesEntry updatedSalesEntry = SalesEntryLocalServiceUtil.updateSalesEntry(salesEntryId,
                salesEntryEditVO.getCompanyName(), salesEntryEditVO.getProfile(), salesEntryEditVO.getPackages(),
                startDate, endDate, salesEntryEditVO.getCountryId(), salesEntryEditVO.getUsersAllowed() > 0,
                salesEntryEditVO.getUsersAllowed(), newKAHEmailAddress, isDomainLicense);
        log.info("Sales entry id " + salesEntryId + "updated successfully!");
        Role keyAccountHolderRole = RoleLocalServiceUtil.getRole(themeDisplay.getCompanyId(),
                STOXX_KEY_ACCOUNT_HOLDER_ROLE);
        if (Validator.isNotNull(existingKAHEmailAddress)) {
            try {
                User existingKAHUser = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(),
                        existingKAHEmailAddress);
                RoleLocalServiceUtil.deleteUserRole(existingKAHUser.getUserId(), keyAccountHolderRole.getRoleId());
                log.info("Deleted key account holder role mapping with user " + existingKAHEmailAddress);
            } catch (NoSuchUserException ex) {
                log.error("Unable to remove key account holder role mapping for user. " + ex.getMessage());
            }
        }
        if (Validator.isNotNull(newKAHEmailAddress)) {
            try {
                User newKAHUser = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(),
                        newKAHEmailAddress);
                RoleLocalServiceUtil.addUserRole(newKAHUser.getUserId(), keyAccountHolderRole.getRoleId());
                log.info("Added key account holder role mapping with user " + newKAHEmailAddress);
            } catch (NoSuchUserException ex) {
                log.debug("Key account holder not yet registered.");
            }
        }

        List<String> newPackageList = ListUtil.fromString(updatedSalesEntry.getPackageNames(), StringPool.COMMA);
        for (Iterator<String> iter = existingPagkageList.iterator(); iter.hasNext();) {
            String existingPackageName = iter.next();
            if (newPackageList.contains(existingPackageName)) {
                iter.remove();
            }
        }
        List<Long> roleIdsToRemove = getRoleIdsList(themeDisplay, existingPagkageList);
        List<Long> roleIdsToAdd = getRoleIdsList(themeDisplay, newPackageList);

        List<UserProfileDetails> existingUserProfiles = userProfileService.getLicensedUsers(salesEntryId);
        for (UserProfileDetails userProfileDetails : existingUserProfiles) {
            updateRoleAssignments(themeDisplay, roleIdsToRemove, roleIdsToAdd,
                    userProfileDetails.getEmailAddress());
        }

        List<String> newEmailAddresses = salesEntryEditVO.getNewEmailAddresses();
        if (newEmailAddresses != null) {
            for (String emailAddress : newEmailAddresses) {
                if (Validator.isNotNull(emailAddress)) {
                    processCustomerEmailAddress(themeDisplay, resultMap, updatedSalesEntry.getSalesEntryId(),
                            updatedSalesEntry.getCompanyName(), emailAddress, roleIdsToRemove, roleIdsToAdd);
                }
            }
        }
        List<EmailDomain> existingDomains = EmailDomainLocalServiceUtil.getEmailDomains(salesEntryId);
        for (String domain : domains) {
            if (Validator.isNotNull(domain)) {
                processDomain(resultMap, salesEntryId, domain);
            }
        }
        if (existingDomains != null) {
            for (EmailDomain existingEmailDomain : existingDomains) {
                String existingDomain = existingEmailDomain.getDomain();
                if (!domains.contains(existingDomain)) {
                    log.info("Processing deletion of domain " + existingDomain);
                    List<UserProfileDetails> domainUsers = userProfileService.getLicensedUsersOfDomain(salesEntryId,
                            existingDomain);
                    if (domainUsers != null) {
                        log.info("Removing " + domainUsers.size() + " users of domain " + existingDomain);
                        for (UserProfileDetails userProfileToDelete : domainUsers) {
                            deleteUser(userProfileToDelete, themeDisplay);
                        }
                    }
                    log.info("Deleting existing domain " + existingEmailDomain.getEmailDomainId() + existingDomain);
                    EmailDomainLocalServiceUtil.deleteEmailDomain(existingEmailDomain.getEmailDomainId());
                }
            }
        }

        return resultMap;
    }

    private List<Long> getRoleIdsList(ThemeDisplay themeDisplay, List<String> existingPagkageList)
            throws PortalException, SystemException {
        List<Long> roleIdsToRemove = new ArrayList<Long>();
        for (String existingPackageToRemove : existingPagkageList) {
            try {
                roleIdsToRemove.add(RoleLocalServiceUtil
                        .getRole(themeDisplay.getCompanyId(), StringUtil.trim(existingPackageToRemove))
                        .getRoleId());
            } catch (NoSuchRoleException e) {
                log.info("No role exist with name " + existingPackageToRemove);
            }
        }
        return roleIdsToRemove;
    }

    private void deleteUser(UserProfileDetails userProfileToDelete, ThemeDisplay themeDisplay) {
        String emailAddress = userProfileToDelete.getEmailAddress();
        log.info("Deleting user profile detail of email address : " + emailAddress);
        try {
            manageUserService.deleteUserByEmail(themeDisplay.getCompanyId(), emailAddress, themeDisplay.getUser());
        } catch (Exception e) {
            log.error("Exception in deleteUser  " + e);
        }
    }

    private void addToSkippedDomain(Map<String, List<String>> resultMap, String domain) {
        resultMap.get(KEY_SKIPPED_DOMAINS).add(domain);
    }

    private Map<String, List<String>> initiateResultMap() {
        Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
        resultMap.put(KEY_SKIPPED_EMAILS, new ArrayList<String>());
        resultMap.put(KEY_SKIPPED_DOMAINS, new ArrayList<String>());
        return resultMap;
    }

    public int checkUserExistsForComapny(List<String> emailAddress) throws STOXXException {
        return userProfileService.checkUserExistsForComapny(emailAddress);
    }

}