com.bemis.portal.customer.service.impl.CustomerProfileLocalServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.bemis.portal.customer.service.impl.CustomerProfileLocalServiceImpl.java

Source

/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.bemis.portal.customer.service.impl;

import static com.bemis.portal.customer.constants.CustomerProfileConstants.BEMIS_CUSTOMER_ID;
import static com.bemis.portal.customer.constants.CustomerProfileConstants.BEMIS_PARENT_ORGANIZATION;

import aQute.bnd.annotation.ProviderType;

import com.bemis.portal.commons.service.BemisPortalService;
import com.bemis.portal.customer.model.CustomerProfile;
import com.bemis.portal.customer.model.impl.CustomerProfileImpl;
import com.bemis.portal.customer.service.CustomerProfileLocalService;
import com.bemis.portal.customer.service.base.CustomerProfileLocalServiceBaseImpl;

import com.liferay.counter.kernel.service.CounterLocalService;
import com.liferay.expando.kernel.model.ExpandoBridge;
import com.liferay.expando.kernel.model.ExpandoTableConstants;
import com.liferay.expando.kernel.model.ExpandoValue;
import com.liferay.expando.kernel.service.ExpandoColumnLocalService;
import com.liferay.expando.kernel.service.ExpandoTableLocalService;
import com.liferay.expando.kernel.service.ExpandoValueLocalService;
import com.liferay.portal.kernel.dao.orm.Criterion;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.exception.DuplicateOrganizationException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.Address;
import com.liferay.portal.kernel.model.Country;
import com.liferay.portal.kernel.model.ListType;
import com.liferay.portal.kernel.model.Organization;
import com.liferay.portal.kernel.model.OrganizationConstants;
import com.liferay.portal.kernel.model.Region;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.search.Document;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.search.Hits;
import com.liferay.portal.kernel.service.AddressLocalService;
import com.liferay.portal.kernel.service.ClassNameLocalService;
import com.liferay.portal.kernel.service.CountryService;
import com.liferay.portal.kernel.service.ListTypeLocalServiceUtil;
import com.liferay.portal.kernel.service.OrganizationLocalService;
import com.liferay.portal.kernel.service.RegionService;
import com.liferay.portal.kernel.util.GetterUtil;
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.spring.extender.service.ServiceReference;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;

/**
 * @author Tran Hoang
 */
@ProviderType
public class CustomerProfileLocalServiceImpl extends CustomerProfileLocalServiceBaseImpl {

    @Override
    public void addorUpdateCustomerProfile(CustomerProfile customerProfile) throws PortalException {

        long userId = _bemisPortalService.getDefaultUser().getUserId();
        long companyId = _bemisPortalService.getDefaultCompanyId();
        long countryId = 0;
        long regionId = 0;

        // Get country and region information

        String countryName = formatCountryName(customerProfile.getCustomerCountry());

        Country country = _countryService.getCountryByName(countryName);

        if (country != null) {
            countryId = country.getCountryId();

            Region region = _regionService.fetchRegion(countryId, customerProfile.getCustomerState());

            if (region != null) {
                regionId = region.getRegionId();
            }
        }

        // Save the organization

        String bemisCustomerId = customerProfile.getBemisCustomerId();

        Organization storedOrganization = getOrganization(bemisCustomerId);

        // We just update the Organization dont create.

        if (storedOrganization != null) {

            // Validate Address

            if (isValidAddress(customerProfile)) {

                // Update Address

                Address address = storedOrganization.getAddress();

                if (address.getAddressId() == 0) {
                    long addressId = counterLocalService.increment(Address.class.getName());

                    address.setAddressId(addressId);
                }

                address.setCompanyId(companyId);
                address.setUserId(userId);
                address.setClassName(Organization.class.getName());
                address.setClassPK(storedOrganization.getOrganizationId());

                address.setStreet1(customerProfile.getCustomerAddress2());
                address.setStreet2(customerProfile.getCustomerAddress1());
                address.setStreet3(customerProfile.getCustomerPoBox());

                address.setCity(customerProfile.getCustomerCity());
                address.setCountryId(countryId);
                address.setRegionId(regionId);
                address.setZip(customerProfile.getCustomerPostalCde());

                long orgAddressListTypeId = 12000;

                List<ListType> orgAddressListTypes = ListTypeLocalServiceUtil
                        .getListTypes("com.liferay.portal.kernel.model.Organization.address");

                for (ListType orgAddressListType : orgAddressListTypes) {
                    if (orgAddressListType.getName().equals("billing")) {
                        orgAddressListTypeId = orgAddressListType.getListTypeId();
                        break;
                    }
                }

                address.setTypeId(orgAddressListTypeId);

                _addressLocalService.updateAddress(address);
            } else {
                if (_log.isWarnEnabled()) {
                    _log.warn("Address is not valid for customer profile ");
                }
            }
        }
    }

    @Override
    public void addOrUpdateCustomerProfiles(List<CustomerProfile> customerProfiles) throws PortalException {

        for (CustomerProfile customerProfile : customerProfiles) {
            try {
                addorUpdateCustomerProfile(customerProfile);

                if (_log.isInfoEnabled()) {
                    _log.info("Synced customer name " + customerProfile.getCustomerName());
                }
            } catch (DuplicateOrganizationException doe) {
                if (_log.isInfoEnabled()) {
                    _log.error(doe.getMessage());
                }
            }
        }
    }

    @Override
    public int countCustomer(String criteria) {
        long companyId = _bemisPortalService.getDefaultCompanyId();

        LinkedHashMap<String, Object> params = new LinkedHashMap<>();

        params.put(_EXPANDO_ATTRIBUTES, criteria);

        return _organizationLocalService.search(companyId, OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID,
                criteria, params, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null).getLength();
    }

    @Override
    public CustomerProfile createCustomerProfile(String bemisCustomerId, String bemisParentId, String customerName,
            String customerAddress1, String customerAddress2, String customerAddress3, String customerPoBox,
            String customerPoCity, String customerPoState, String customerPoPostalCde, String customerCity,
            String customerState, String customerPostalCde, String customerCountry, String customerPhoneNbr,
            String customerActiveStatusCde) {

        Organization organization = null;

        return new CustomerProfileImpl(organization, bemisCustomerId, bemisParentId, customerName, customerAddress1,
                customerAddress2, customerAddress3, customerPoBox, customerPoCity, customerPoState,
                customerPoPostalCde, customerCity, customerState, customerPostalCde, customerCountry,
                customerPhoneNbr, customerActiveStatusCde);
    }

    @Override
    public Collection<String> getBemisCustomerIds() {
        Collection<CustomerProfile> parentLocations = getParentLocations();

        if ((parentLocations == null) || parentLocations.isEmpty()) {
            return Collections.emptySet();
        }

        Collection<String> customerLocationIds = new ArrayList<>();

        for (CustomerProfile parentLocation : parentLocations) {
            customerLocationIds.addAll(getCustomerLocationBemisIds(parentLocation));
        }

        return customerLocationIds;
    }

    @Override
    public String[] getBemisCustomerIds(User user) {
        List<String> bemisCustomerIds = new ArrayList<>();

        for (CustomerProfile customerProfile : getBemisCustomerProfiles(user)) {
            bemisCustomerIds.add(customerProfile.getBemisCustomerId());
        }

        String[] customerIds = new String[bemisCustomerIds.size()];

        return bemisCustomerIds.toArray(customerIds);
    }

    @Override
    public List<CustomerProfile> getBemisCustomerProfiles(User user) {
        List<CustomerProfile> customerProfiles = new ArrayList<>();

        try {
            List<Organization> userOrganizations = user.getOrganizations();

            for (Organization organization : userOrganizations) {
                customerProfiles.add(getCustomerProfile(organization.getOrganizationId()));
            }
        } catch (PortalException pe) {
            _log.error("Failed to retrieve organizations for user " + user + ": " + pe);
        }

        return customerProfiles;
    }

    @Override
    public Collection<CustomerProfile> getCustomerLocations(CustomerProfile parentLocation) {

        return getCustomerLocationOrgs(parentLocation).stream().map(org -> asCustomerProfile(org))
                .collect(Collectors.toList());
    }

    @Override
    public CustomerProfile getCustomerProfile(long organizationId) throws PortalException {

        Organization org = _organizationLocalService.getOrganization(organizationId);

        return asCustomerProfile(org);
    }

    /**
     * Returns child organization based on bemisCustId
     * @param bemisCustomerId
     * @return
     * @throws PortalException
     */
    @Override
    public Organization getOrganization(String bemisCustomerId) throws PortalException {

        long companyId = _bemisPortalService.getDefaultCompanyId();

        long classNameId = _classNameLocalService.getClassNameId(Organization.class);

        List<ExpandoValue> values = _expandoValueLocalService.getColumnValues(companyId, classNameId,
                ExpandoTableConstants.DEFAULT_TABLE_NAME, BEMIS_CUSTOMER_ID, bemisCustomerId, -1, -1);

        if (values.isEmpty()) {
            return null;
        }

        for (ExpandoValue value : values) {
            long organizationId = value.getClassPK();

            Organization organization = _organizationLocalService.getOrganization(organizationId);

            if (organization.isParentable()) {
                continue;
            }

            return organization;
        }

        return null;
    };

    /**
     * Returns the OSGi service identifier.
     *
     * @return the OSGi service identifier
     */
    @Override
    public String getOSGiServiceIdentifier() {
        return CustomerProfileLocalService.class.getName();
    }

    @Override
    public Collection<CustomerProfile> getParentLocations() {
        return getParentLocationOrgs().stream().map(org -> asCustomerProfile(org)).collect(Collectors.toSet());
    }

    @Override
    public List<CustomerProfile> searchCustomer(String criteria, int start, int end) throws PortalException {

        long companyId = _bemisPortalService.getDefaultCompanyId();

        List<CustomerProfile> customerProfiles = new ArrayList<>();

        LinkedHashMap<String, Object> params = new LinkedHashMap<>();

        params.put(_EXPANDO_ATTRIBUTES, criteria);

        Hits hits = _organizationLocalService.search(companyId,
                OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID, criteria, params, start, end, null);

        Document[] documents = hits.getDocs();

        for (Document doc : documents) {
            long orgId = GetterUtil.getLong(doc.get(Field.ORGANIZATION_ID));

            Organization org = _organizationLocalService.getOrganization(orgId);

            customerProfiles.add(asCustomerProfile(org));
        }

        return customerProfiles;
    }

    protected CustomerProfile asCustomerProfile(Organization org) {
        String bemisCustomerId = getBemisCustomerId(org);
        String bemisParentOrg = getExpandoValue(org, BEMIS_PARENT_ORGANIZATION);

        return new CustomerProfileImpl(org, bemisCustomerId, bemisParentOrg);
    }

    protected String formatCountryName(String countryName) {
        return StringUtil.toLowerCase(countryName.replace(StringPool.SPACE, StringPool.DASH));
    }

    protected String getBemisCustomerId(Organization org) {
        return getExpandoValue(org, BEMIS_CUSTOMER_ID);
    }

    protected Collection<String> getCustomerLocationBemisIds(CustomerProfile parentLocation) {

        Collection<CustomerProfile> customerLocations = getCustomerLocations(parentLocation);

        if ((customerLocations == null) || customerLocations.isEmpty()) {
            return Collections.emptySet();
        }

        return customerLocations.stream().map(CustomerProfile::getBemisCustomerId)
                .filter(bemisCusomerId -> !StringUtils.isEmpty(bemisCusomerId)).collect(Collectors.toSet());
    }

    protected Collection<Organization> getCustomerLocationOrgs(CustomerProfile parentLocation) {

        Organization parentLocationOrg = parentLocation.getOrganization();

        if (parentLocationOrg == null) {
            return Collections.emptySet();
        }

        Collection<Organization> orgs = _organizationLocalService
                .getSuborganizations(parentLocationOrg.getCompanyId(), parentLocationOrg.getOrganizationId());

        return orgs;
    }

    protected String getExpandoValue(Organization org, String attributeName) {
        String expandoValue = StringPool.BLANK;

        ExpandoBridge expandoBridge = org.getExpandoBridge();

        Serializable serializable = expandoBridge.getAttribute(attributeName, false);

        if (serializable != null) {
            expandoValue = serializable.toString();
        }

        return expandoValue;
    }

    protected Collection<Organization> getParentLocationOrgs() {
        DynamicQuery query = _organizationLocalService.dynamicQuery();

        query.add(_IS_PARENT_LOCATION);

        return _organizationLocalService.dynamicQuery(query);
    }

    protected boolean isValidAddress(CustomerProfile customerProfile) {
        if (Validator.isNull(customerProfile.getCustomerAddress1())
                || Validator.isNull(customerProfile.getCustomerCity())
                || Validator.isNull(customerProfile.getCustomerPostalCde())) {

            return false;
        }

        return true;
    }

    @ServiceReference(type = CounterLocalService.class)
    protected CounterLocalService counterLocalService;

    private static final String _EXPANDO_ATTRIBUTES = "expandoAttributes";

    private static final Criterion _IS_PARENT_LOCATION = PropertyFactoryUtil.forName("type").eq("parent-location");

    private static final Log _log = LogFactoryUtil.getLog(CustomerProfileLocalServiceImpl.class);

    @ServiceReference(type = AddressLocalService.class)
    private AddressLocalService _addressLocalService;

    @ServiceReference(type = BemisPortalService.class)
    private BemisPortalService _bemisPortalService;

    @ServiceReference(type = ClassNameLocalService.class)
    private ClassNameLocalService _classNameLocalService;

    @ServiceReference(type = CountryService.class)
    private CountryService _countryService;

    @ServiceReference(type = ExpandoColumnLocalService.class)
    private ExpandoColumnLocalService _expandoColumnLocalService;

    @ServiceReference(type = ExpandoTableLocalService.class)
    private ExpandoTableLocalService _expandoTableLocalService;

    @ServiceReference(type = ExpandoValueLocalService.class)
    private ExpandoValueLocalService _expandoValueLocalService;

    @ServiceReference(type = OrganizationLocalService.class)
    private OrganizationLocalService _organizationLocalService;

    @ServiceReference(type = RegionService.class)
    private RegionService _regionService;

}