Creating Discount for all products in electronicsstore.

Solutions:-

Below files will describes their functionality   these files will helps to do the Task(Trail)

1)multistorecore-items.xml-à to define the discount to the cmssite

2)Solr.impex–à to create facet of site discount in the plp(we have to define valueprovider)

3)multistorefacades-spring.xml —> register the populators of pdp(logic we have to write),plp(logic will comw from value provide)

4)MultiStoreSiteDiscoutPriceValueProvider.java-àvalue provider to calculate the discount value with base price in plp

5)MultiStoreSiteDiscoutPriceValueProviderTest.java-à test class to MultiStoreSiteDiscoutPriceValueProvider

6)ProductSearchResultPopulator.java-à it is used to populate the data in PLP

7)productListerItemPrice.tag–à to display price in plp

8)MultistoreProductDiscountPricePopulator.java–àto populate the discounted price of product in pdp

9)productPricePanel.tag-à to display price in plp

10)MultiStoreSiteDiscountPriceFactory.java-àto calculate the base price with diconted price in cart page

11)multistorecore-spring.xmlàregistering the all classes related in core extenstion

1) multistorecore-items.xml

<itemtype code=”MultiStoreSiteDiscount” autocreate=”true” generate=”true”>

<attributes>

<attribute qualifier=”code” type=”java.lang.String”>

<persistence type=”property” />

<modifiers read=”true” write=”false” search=”true”

initial=”true” optional=”false” unique=”true” />

</attribute>

<attribute qualifier=”sitediscount” type=”java.lang.Double”autocreate=”true”>

<persistence type=”property” />

<modifiers read=”true” write=”true” search=”true” />

</attribute>

</attributes>

</itemtype>

<itemtype code=”CMSSite” autocreate=”false” generate=”false”>

<attributes>

<attribute type=”MultiStoreSiteDiscount” qualifier=”multistoreSiteDiscount

autocreate=”true” generate=”true”>

<persistence type=”property” />

</attribute>

</attributes>

</itemtype>

2) Solr.impex

#

# Import the Solr common configuration

# Other facet properties

$productCatalog=electronicsProductCatalog

$catalogVersions=catalogVersions(catalog(id),version);

$serverConfigName=electronicsSolrServerConfig

$indexConfigName=electronicsSolrIndexConfig

$searchConfigName=electronicsPageSize

$facetSearchConfigName=electronicsIndex

$facetSearchConfigDescription=Electronics Solr Index

$searchIndexNamePrefix=electronics

$solrIndexedType=electronicsProductType

$indexBaseSite=electronics

$indexLanguages=ja,en,de,zh

$indexCurrencies=JPY,USD

INSERT_UPDATE SolrIndexedProperty;solrIndexedType(identifier)[unique = true];name[unique = true];type(code);sortableType(code);currency[default = true]; localized[default = false]; multiValue[default = false]; facet[default = false]; facetType(code); facetSort(code); priority; visible; useForSpellchecking[default = false]; useForAutocomplete[default = false]; fieldValueProvider; facetDisplayNameProvider; customFacetSortProvider; topValuesProvider; rangeSets(name)

; $solrIndexedType                         ; sitediscount      ; double ; ; true ; ;      ; ;  ;   ;  ;  ; ; ; sitediscountPriceValueProvider  ;                                    ; ;  ;

  • Run above the Impex
  • See in system->facat->indextype-> sitediscount

3) multistorecore-spring.xml

We have to register id of sitediscountPriceValueProvider (fieldValueProvider) in spring.xml file.

<bean id=”sitediscountPriceValueProvider”

class=”com.e.core.solr.MultiStoreSiteDiscoutPriceValueProvider”

             parent=”abstractPropertyFieldValueProvider”>

             <property name=”fieldNameProvider” ref=”solrFieldNameProvider” />

             <property name=”priceService” ref=”priceService” />

             <property name=”commonI18NService” ref=”commonI18NService” />

             <property name=”catalogVersionService” ref=”catalogVersionService” />

       </bean>

4) MultiStoreSiteDiscoutPriceValueProvider.java

1)getting the product(final ProductModel product = (ProductModel) model;)

2) getting base site using  indexConfig object(final BaseSiteModel site = indexConfig.getBaseSite();)

3)getting  sitediscount in Cmssite(final MultiStoreSiteDiscountModel multiStoreSiteDiscount = ((CMSSiteModel) site).getMultistoreSiteDiscount();)

4)setCatalog version for perticular product

5)getting all Currencyies in the facet

6)setting the currencies in commonI18NService

7)getting the price from priceInformation

8)checking the Currencyies IsoCode and  Price Currencyies Iso code

9)getting the currency by setting the currencies Iso code

10)passing arrgument and caculating the discount

11)getting all  collections of fieldName

12)adding our discont value

import de.hybris.platform.basecommerce.model.site.BaseSiteModel;

import de.hybris.platform.catalog.CatalogVersionService;

import de.hybris.platform.cms2.model.site.CMSSiteModel;

import de.hybris.platform.core.model.c2l.CurrencyModel;

import de.hybris.platform.core.model.product.ProductModel;

import de.hybris.platform.jalo.order.price.PriceInformation;

import de.hybris.platform.product.PriceService;

import de.hybris.platform.servicelayer.i18n.CommonI18NService;

import de.hybris.platform.solrfacetsearch.config.IndexConfig;

import de.hybris.platform.solrfacetsearch.config.IndexedProperty;

import de.hybris.platform.solrfacetsearch.config.exceptions.FieldValueProviderException;

import de.hybris.platform.solrfacetsearch.provider.FieldNameProvider;

import de.hybris.platform.solrfacetsearch.provider.FieldValue;

import de.hybris.platform.solrfacetsearch.provider.FieldValueProvider;

import de.hybris.platform.solrfacetsearch.provider.impl.AbstractPropertyFieldValueProvider;

import java.io.Serializable;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import org.apache.log4j.Logger;

import com.multistore.core.model.MultiStoreSiteDiscountModel;

// This MultiStoreSiteDiscoutPriceValueProvider will provide site discount price

public class MultiStoreSiteDiscoutPriceValueProvider extends AbstractPropertyFieldValueProvider

private CatalogVersionService catalogVersionService;

private CommonI18NService commonI18NService;

private PriceService priceService;

private FieldNameProvider fieldNameProvider;

@Override

public Collection<FieldValue> getFieldValues(final IndexConfig indexConfig, final IndexedProperty indexedProperty, final Object model)

throws FieldValueProviderException {

final List<FieldValue> fieldValues = new ArrayList<FieldValue>();

// getting the product

final ProductModel product = (ProductModel) model;

// getting base site using  indexConfig object

final BaseSiteModel site = indexConfig.getBaseSite();

//getting  sitediscount in Cmssite

final MultiStoreSiteDiscountModel multiStoreSiteDiscount = ((CMSSiteModel) site).getMultistoreSiteDiscount();

 if (multiStoreSiteDiscount != null && product != null) {

 final Double sitediscount = multiStoreSiteDiscount.getSitediscount();

 if (sitediscount != null) {

//setCatalog version for perticular product

        catalogVersionService.setSessionCatalogVersions(Arrays.asList((product).getCatalogVersion()));

//getting all Currencyies in the facet

final Collection<CurrencyModel> currencies = indexConfig.getCurrencies();

if (CollectionUtils.isNotEmpty(currencies)) {

for (final CurrencyModel currencyModel : currencies) {

//setting the currencies in commonI18NService

commonI18NService.setCurrentCurrency(currencyModel);

//getting the price from priceInformation

final List<PriceInformation> priceInfos = priceService.getPriceInformationsForProduct(product);

for (final PriceInformation priceInformation : priceInfos) {

//checking the Currencyies IsoCode and  Price Currencyies Iso code

if (currencyModel.getIsocode().equalsIgnoreCase(priceInformation.getPriceValue().getCurrencyIso())) {

//getting the currency by setting the currencies Iso code

 final CurrencyModel oneCurrency = commonI18NService

.getCurrency(priceInformation.getPriceValue().getCurrencyIso());

//passing arrgument and caculating the discount

addFieldValues(fieldValues, indexedProperty, currencyModel.getIsocode(),

new Double(commonI18NService.roundCurrency((priceInformation.getPriceValue().getValue()

                                                – ((priceInformation.getPriceValue().getValue() * sitediscount.doubleValue()) / 100)),

                                                oneCurrency.getDigits().intValue())));

                            }

                        }

                    }

                }

            }

        }

        return fieldValues;

    }

 protected void addFieldValues(final List<FieldValue> fieldValues, final IndexedProperty indexedProperty, final String currencyIso,

            final Double value) {

//getting all  collections of fieldName

final Collection<String> fieldNames = getFieldNameProvider().getFieldNames(indexedProperty, currencyIso);

for (final String fieldName : fieldNames) {

//adding our discont value

fieldValues.add(new FieldValue(fieldName, value));

        }

    }

// setters and getters

}

backoffice

Do solr indexing

BAckoffice -> System à click On FacetSerch Config ->click on index ->operation values(full)-> start

 

 

5) multistorefacades-spring.xml:- to register the populator

<bean id=”multiStoreProductSearchResultPopulator”

class=”com..multistore.facades.populators.ProductSearchResultPopulator”>

<property name=”commonI18NService” ref=”commonI18NService” />

<property name=”priceDataFactory” ref=”priceDataFactory” />

</bean>

<bean parent=”modifyPopulatorList”>

<property name=”list” ref=”commerceSearchResultProductConverter” />

<property name=”add” ref=”multiStoreProductSearchResultPopulator” />

</bean>

 

6)ProductSearchResultPopulator.java:- used topopulating the discounted price of the product which is coming from value provider data in PLP page.

 

import de.hybris.platform.commercefacades.product.PriceDataFactory;

import de.hybris.platform.commercefacades.product.data.PriceDataType;

import de.hybris.platform.commercefacades.product.data.ProductData;

import de.hybris.platform.commerceservices.search.resultdata.SearchResultValueData;

import de.hybris.platform.converters.Populator;

import de.hybris.platform.servicelayer.dto.converter.ConversionException;

import de.hybris.platform.servicelayer.i18n.CommonI18NService;

import java.math.BigDecimal;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Required;

import com.google.common.base.Preconditions;

public class ProductSearchResultPopulator implements Populator<SearchResultValueData, ProductData> {

private PriceDataFactory priceDataFactory;

    private CommonI18NService commonI18NService;

    @Override

    public void populate(final SearchResultValueData source, final ProductData target) throws ConversionException {

        Preconditions.checkArgument(null != source, “Source cann’t be null”);

        Preconditions.checkArgument(null != target, “Target cann’t be null”);

        final Double sitediscount = this.<Double> getValue(source, “sitediscount”);

        if (null != sitediscount) {

            target.setSitediscount(priceDataFactory.create(PriceDataType.BUY, BigDecimal.valueOf(sitediscount.doubleValue()),

                    commonI18NService.getCurrentCurrency()));

        }

    }

    protected <T> T getValue(final SearchResultValueData source, final String propertyName) {

        if (source.getValues() == null) {

            return null;

        }

 

        // DO NOT REMOVE the cast (T) below, while it should be unnecessary it

        // is required by the javac compiler

        return (T) source.getValues().get(propertyName);

    }

// SETTERS AND GETTER FILES

}

 7)productListerItemPrice.tag

<c:choose>

<c:when test=”${product.multidimensional and (product.priceRange.minPrice.value ne product.priceRange.maxPrice.value)}”>

<format:price priceData=”${product.priceRange.minPrice}”/> – <format:price priceData=”${product.priceRange.maxPrice}”/>

                    </c:when>

                    <c:otherwise>

                          <strike >

                               <font size=”1″ >

                                    <format:price  priceData=”${product.price}”/>

                                </font>

                             </strike><br>

                          <format:price priceData=”${product.sitediscount}”/>

                    </c:otherwise>

       </c:choose>

</ycommerce:testId>

plp

8)

<alias name=”defaultMultistoreProductPricePopulator” alias=”multistoreProductPricePopulator” />

<bean id=”defaultMultistoreProductPricePopulator”

class=”com.multistore.facades.populators.MultistoreProductDiscountPricePopulator” parent=”abstractPopulatingConverter”>

<property name=”commonI18NService” ref=”commonI18NService” />

<property name=”priceDataFactory” ref=”priceDataFactory” />

<property name=”cmsSiteService” ref=”cmsSiteService” />

<property name=”priceService” ref=”priceService” />

<property name=”modelService” ref=”modelService” />

</bean>

<bean parent=”modifyPopulatorList”>

<property name=”list” ref=”productConverter” />

<property name=”add” ref=”multistoreProductPricePopulator” />

</bean>

 

 

9)MultistoreProductDiscountPricePopulator.java:- To populate the discount price in PDP page.for that we have to calculate the discounted price of the product in pdp

 

 

      

import de.hybris.platform.cms2.servicelayer.services.CMSSiteService;

import de.hybris.platform.commercefacades.product.PriceDataFactory;

import de.hybris.platform.commercefacades.product.converters.populator.AbstractProductPopulator;

import de.hybris.platform.commercefacades.product.data.PriceData;

import de.hybris.platform.commercefacades.product.data.PriceDataType;

import de.hybris.platform.commercefacades.product.data.ProductData;

import de.hybris.platform.core.model.c2l.CurrencyModel;

import de.hybris.platform.core.model.product.ProductModel;

import de.hybris.platform.jalo.order.price.PriceInformation;

import de.hybris.platform.product.PriceService;

import de.hybris.platform.servicelayer.dto.converter.ConversionException;

import de.hybris.platform.servicelayer.i18n.CommonI18NService;

 

import java.math.BigDecimal;

import java.util.List;

 

import org.apache.commons.collections.CollectionUtils;

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Required;

 

import com.google.common.base.Preconditions;

public class MultistoreProductDiscountPricePopulator<SOURCE extends ProductModel, TARGET extends ProductData>

extends AbstractProductPopulator<SOURCE, TARGET> {

    private PriceDataFactory priceDataFactory;

    private CommonI18NService commonI18NService;

    /** The price service. */

    private PriceService priceService;

    private CMSSiteService cmsSiteService;

    @Override

    public void populate(final SOURCE productModel, final TARGET productData) throws ConversionException {

        Preconditions.checkArgument(null != productModel, “Source cann’t be null”);

        Preconditions.checkArgument(null != productData, “Target cann’t be null”);

        final List<PriceInformation> priceInfos = priceService.getPriceInformationsForProduct(productModel);

        final CurrencyModel currencyModel = commonI18NService.getCurrentCurrency();

        final Double sitediscount = cmsSiteService.getCurrentSite().getMultistoreSiteDiscount().getSitediscount();

  if (sitediscount != null && CollectionUtils.isNotEmpty(priceInfos)) {

            for (final PriceInformation priceInformation : priceInfos) {

               if (currencyModel.getIsocode().equalsIgnoreCase(priceInformation.getPriceValue().getCurrencyIso())) {

                    final CurrencyModel oneCurrency = commonI18NService.getCurrency(priceInformation.getPriceValue().getCurrencyIso());

 

                    final double discount = commonI18NService.roundCurrency(

                            (priceInformation.getPriceValue().getValue()

                                    – (priceInformation.getPriceValue().getValue() * sitediscount.doubleValue()) / 100),

                            oneCurrency.getDigits().intValue());

                    final PriceData priceData = priceDataFactory.create(PriceDataType.BUY, BigDecimal.valueOf(discount), currencyModel);

                    productData.setSitediscount(priceData);

 

                }

 

            }

        }

 

    }

 

   //setters and getters

}

 

10)productPricePanel.tag to Display the price information in PDP

 

<c:choose>

       <c:when test=”${empty product.volumePrices}”>

             <c:choose>

                    <c:when test=”${(not empty product.priceRange) and (product.priceRange.minPrice.value ne product.priceRange.maxPrice.value) and ((empty product.baseProduct) or (not empty isOrderForm and isOrderForm))}”>

                          <span>

                                 <format:price priceData=”${product.priceRange.minPrice}”/>

                          </span>

                          <span>

                                 –

                          </span>

                          <span>

                                 <format:price priceData=”${product.priceRange.maxPrice}”/>

                          </span>

                    </c:when>

                    <c:otherwise>

                          <p class=”price”>

                 <strike >

                      <font size=”2″ >

                        <format:price  priceData=”${product.price}”/>

                        </font>

                  </strike><br>

                                   <format:price priceData=”${product.sitediscount}”/>

                        </p>

                    </c:otherwise>

             </c:choose>

       </c:when>

       <c:otherwise>

             <table class=”volume__prices” cellpadding=”0″ cellspacing=”0″ border=”0″>

                    <thead>

                    <th class=”volume__prices-quantity”><spring:theme code=”product.volumePrices.column.qa”/></th>

                    <th class=”volume__price-amount”><spring:theme code=”product.volumePrices.column.price”/></th>

                    </thead>

                    <tbody>

                    <c:forEach var=”volPrice” items=”${product.volumePrices}”>

                          <tr>

                                 <td class=”volume__price-quantity”>

                                       <c:choose>

                                              <c:when test=”${empty volPrice.maxQuantity}”>

                                                     ${volPrice.minQuantity}+

                                              </c:when>

                                              <c:otherwise>

                                                     ${volPrice.minQuantity}-${volPrice.maxQuantity}

                                              </c:otherwise>

                                       </c:choose>

                                 </td>

                                 <td class=”volume__price-amount text-right”>${volPrice.formattedValue}</td>

                          </tr>

                    </c:forEach>

                    </tbody>

             </table>

       </c:otherwise>

</c:choose>

 

 pdp

 

 

11)multistorecore-spring.xml:- register the MultiStoreSiteDiscountPriceFactory.java is is user to display the discounted price of product in cart page

<alias name=”defaultMultiStoreSiteDiscountPriceFactory” alias=”europe1.manager” />

<bean id=”defaultMultiStoreSiteDiscountPriceFactory”

class=”com.multistore.core.pricefactory.MultiStoreSiteDiscountPriceFactory”>

<property name=”cmsSiteService” ref=”cmsSiteService” />

<property name=”retrieveChannelStrategy” ref=”retrieveChannelStrategy” />

</bean>

 

europe1.manager:- we are overriding so we have to define alias as its perant class bean id.

 

 

12) MultiStoreSiteDiscountPriceFactory.java:-This class is used for calculating the base price with site discounted price.for that we are overriding the getBasePrice(final AbstractOrderEntry entry) method from base class.

import de.hybris.platform.catalog.jalo.CatalogAwareEurope1PriceFactory;

import de.hybris.platform.cms2.servicelayer.services.CMSSiteService;

import de.hybris.platform.europe1.jalo.PriceRow;

import de.hybris.platform.jalo.SessionContext;

import de.hybris.platform.jalo.c2l.Currency;

import de.hybris.platform.jalo.enumeration.EnumerationValue;

import de.hybris.platform.jalo.order.AbstractOrder;

import de.hybris.platform.jalo.order.AbstractOrderEntry;

import de.hybris.platform.jalo.order.price.JaloPriceFactoryException;

import de.hybris.platform.jalo.product.Product;

import de.hybris.platform.jalo.product.Unit;

import de.hybris.platform.jalo.user.User;

import de.hybris.platform.util.PriceValue;

import de.hybris.platform.util.localization.Localization;

import java.util.Date;

import org.apache.log4j.Logger;

public class MultiStoreSiteDiscountPriceFactory extends CatalogAwareEurope1PriceFactory {

private CMSSiteService cmsSiteService;

    /**

     * to calculate base price with site discount

     */

    @Override

    public PriceValue getBasePrice(final AbstractOrderEntry entry) throws JaloPriceFactoryException {

        super.getBasePrice(entry);

        final SessionContext ctx = this.getSession().getSessionContext();

        final AbstractOrder order = entry.getOrder(ctx);

        Currency currency = null;

        EnumerationValue productGroup = null;

        User user = null;

        EnumerationValue userGroup = null;

        Unit unit = null;

        long quantity = 0L;

        boolean net = false;

        Date date = null;

        final Product product = entry.getProduct();

        final boolean giveAwayMode = entry.isGiveAway(ctx).booleanValue();

        final boolean entryIsRejected = entry.isRejected(ctx).booleanValue();

        PriceRow row;

        if (giveAwayMode && entryIsRejected) {

            row = null;

        } else {

            row = this.matchPriceRowForPrice(ctx, product, productGroup = this.getPPG(ctx, product), user = order.getUser(),

                    userGroup = this.getUPG(ctx, user), quantity = entry.getQuantity(ctx).longValue(), unit = entry.getUnit(ctx),

                    currency = order.getCurrency(ctx), date = order.getDate(ctx), net = order.isNet().booleanValue(), giveAwayMode);

        }

        if (row != null) {

            final Currency msg1 = row.getCurrency();

            double price;

            double price1 = 0.0d;

            final Double sitediscount = cmsSiteService.getCurrentSite().getMultistoreSiteDiscount().getSitediscount();

            if (currency.equals(msg1)) {

                price = row.getPriceAsPrimitive() / row.getUnitFactorAsPrimitive();

                price1 = row.getPriceAsPrimitive() – (row.getPriceAsPrimitive() * sitediscount) / 100;

            } else {

                price = msg1.convert(currency, row.getPriceAsPrimitive() / row.getUnitFactorAsPrimitive());

            }

            final Unit priceUnit = row.getUnit();

            final Unit entryUnit = entry.getUnit();

            final double convertedPrice = priceUnit.convertExact(entryUnit, price1);

            return new PriceValue(currency.getIsoCode(), convertedPrice, row.isNetAsPrimitive());

        } else if (giveAwayMode) {

            return new PriceValue(order.getCurrency(ctx).getIsoCode(), 0.0D, order.isNet().booleanValue());

        } else {

            final String msg = Localization.getLocalizedString(“exception.europe1pricefactory.getbaseprice.jalopricefactoryexception1”,

                    new Object[] { product, productGroup, user, userGroup, Long.toString(quantity), unit, currency, date,

                            Boolean.toString(net) });

            throw new JaloPriceFactoryException(msg, 0);

        }

    }

//setter and getter price

}

 

cart