From 7c7236b719ba7781748ffe8df1cfdf5510831da2 Mon Sep 17 00:00:00 2001 From: nueue23 Date: Mon, 30 May 2022 16:20:37 +0530 Subject: [PATCH 01/15] update deprecated code and add junit --- .../core/business/utils/DataUtils.java | 23 ++-- .../test/business/utils/DataUtilsTest.java | 109 ++++++++++++++++++ 2 files changed, 120 insertions(+), 12 deletions(-) create mode 100644 sm-core/src/test/java/com/salesmanager/test/business/utils/DataUtilsTest.java diff --git a/sm-core/src/main/java/com/salesmanager/core/business/utils/DataUtils.java b/sm-core/src/main/java/com/salesmanager/core/business/utils/DataUtils.java index 2d2175e748..b254ccae56 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/utils/DataUtils.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/utils/DataUtils.java @@ -1,6 +1,7 @@ package com.salesmanager.core.business.utils; import java.math.BigDecimal; +import java.math.RoundingMode; import com.salesmanager.core.constants.MeasureUnit; import com.salesmanager.core.model.merchant.MerchantStore; @@ -33,23 +34,21 @@ public static double getWeight(double weight, MerchantStore store, double weightConstant = 2.2; if (base.equals(MeasureUnit.LB.name())) { if (store.getWeightunitcode().equals(MeasureUnit.LB.name())) { - return new BigDecimal(String.valueOf(weight)).setScale(2, - BigDecimal.ROUND_HALF_UP).doubleValue(); + return new BigDecimal(String.valueOf(weight)) + .setScale(2, RoundingMode.HALF_UP).doubleValue(); } else {// pound = kilogram double answer = weight * weightConstant; BigDecimal w = new BigDecimal(answer); - return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return w.setScale(2, RoundingMode.HALF_UP).doubleValue(); } } else {// need KG if (store.getWeightunitcode().equals(MeasureUnit.KG.name())) { return new BigDecimal(String.valueOf(weight)).setScale(2, - BigDecimal.ROUND_HALF_UP).doubleValue(); + RoundingMode.HALF_UP).doubleValue(); } else { - double answer = weight / weightConstant; BigDecimal w = new BigDecimal(answer); - return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - + return w.setScale(2, RoundingMode.HALF_UP).doubleValue(); } } } @@ -70,25 +69,25 @@ public static double getMeasure(double measure, MerchantStore store, if (base.equals(MeasureUnit.IN.name())) { if (store.getSeizeunitcode().equals(MeasureUnit.IN.name())) { return new BigDecimal(String.valueOf(measure)).setScale(2, - BigDecimal.ROUND_HALF_UP).doubleValue(); + RoundingMode.HALF_UP).doubleValue(); } else {// centimeter (inch to centimeter) double measureConstant = 2.54; double answer = measure * measureConstant; BigDecimal w = new BigDecimal(answer); - return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return w.setScale(2, RoundingMode.HALF_UP).doubleValue(); } } else {// need CM if (store.getSeizeunitcode().equals(MeasureUnit.CM.name())) { - return new BigDecimal(String.valueOf(measure)).setScale(2) - .doubleValue(); + return new BigDecimal(String.valueOf(measure)).setScale(2, + RoundingMode.HALF_UP).doubleValue(); } else {// in (centimeter to inch) double measureConstant = 0.39; double answer = measure * measureConstant; BigDecimal w = new BigDecimal(answer); - return w.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); + return w.setScale(2, RoundingMode.HALF_UP).doubleValue(); } } diff --git a/sm-core/src/test/java/com/salesmanager/test/business/utils/DataUtilsTest.java b/sm-core/src/test/java/com/salesmanager/test/business/utils/DataUtilsTest.java new file mode 100644 index 0000000000..1c1a954d13 --- /dev/null +++ b/sm-core/src/test/java/com/salesmanager/test/business/utils/DataUtilsTest.java @@ -0,0 +1,109 @@ +package com.salesmanager.test.business.utils; + +import com.salesmanager.core.business.utils.DataUtils; +import com.salesmanager.core.constants.MeasureUnit; +import com.salesmanager.core.model.merchant.MerchantStore; + +import org.junit.Test; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class DataUtilsTest { + + /** + * This methods tests {@link DataUtils#trimPostalCode(String)} + */ + @Test + public void testTrimPostalCode(){ + String result = DataUtils.trimPostalCode(" 364856-A56 - B888@ "); + assertEquals("364856A56B888", result); + } + + /** + * This methods tests {@link DataUtils#getWeight(double, MerchantStore, String)} + */ + @Test + public void testGetWeight_When_StoreUnit_LB_MeasurementUnit_LB(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getWeightunitcode()).thenReturn(MeasureUnit.LB.name()); + double result = DataUtils.getWeight(100.789, store, MeasureUnit.LB.name()); + assertEquals(100.79, result, 0); + } + + /** + * This methods tests {@link DataUtils#getWeight(double, MerchantStore, String)} + */ + @Test + public void testGetWeight_When_StoreUnit_KG_MeasurementUnit_LB(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getWeightunitcode()).thenReturn(MeasureUnit.KG.name()); + double result = DataUtils.getWeight(100.789, store, MeasureUnit.LB.name()); + assertEquals(221.74, result, 0); + } + + /** + * This methods tests {@link DataUtils#getWeight(double, MerchantStore, String)} + */ + @Test + public void testGetWeight_When_StoreUnit_KG_MeasurementUnit_KG(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getWeightunitcode()).thenReturn(MeasureUnit.KG.name()); + double result = DataUtils.getWeight(100.789, store, MeasureUnit.KG.name()); + assertEquals(100.79, result, 0); + } + + /** + * This methods tests {@link DataUtils#getWeight(double, MerchantStore, String)} + */ + @Test + public void testGetWeight_When_StoreUnit_LB_MeasurementUnit_KG(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getWeightunitcode()).thenReturn(MeasureUnit.LB.name()); + double result = DataUtils.getWeight(100.789, store, MeasureUnit.KG.name()); + assertEquals(45.81, result, 0); + } + + /** + * This methods tests {@link DataUtils#getMeasure(double, MerchantStore, String)} + */ + @Test + public void testGetMeasureWhen_StoreUnit_IN_MeasurementUnit_IN(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getSeizeunitcode()).thenReturn(MeasureUnit.IN.name()); + double result = DataUtils.getMeasure(100.789, store, MeasureUnit.IN.name()); + assertEquals(100.79, result, 0); + } + + /** + * This methods tests {@link DataUtils#getMeasure(double, MerchantStore, String)} + */ + @Test + public void testGetMeasureWhen_StoreUnit_CM_MeasurementUnit_IN(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getSeizeunitcode()).thenReturn(MeasureUnit.CM.name()); + double result = DataUtils.getMeasure(100.789, store, MeasureUnit.IN.name()); + assertEquals(256.00, result, 0); + } + + /** + * This methods tests {@link DataUtils#getMeasure(double, MerchantStore, String)} + */ + @Test + public void testGetMeasureWhen_StoreUnit_CM_MeasurementUnit_CM(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getSeizeunitcode()).thenReturn(MeasureUnit.CM.name()); + double result = DataUtils.getMeasure(100.789, store, MeasureUnit.CM.name()); + assertEquals(100.79, result, 0); + } + + /** + * This methods tests {@link DataUtils#getMeasure(double, MerchantStore, String)} + */ + @Test + public void testGetMeasureWhen_StoreUnit_IN_MeasurementUnit_CM(){ + MerchantStore store = mock(MerchantStore.class); + when(store.getSeizeunitcode()).thenReturn(MeasureUnit.IN.name()); + double result = DataUtils.getMeasure(100.789, store, MeasureUnit.CM.name()); + assertEquals(39.31, result, 0); + } +} From ec24049e3cd64638a35daff50bc7429bdfa6c907 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Wed, 1 Jun 2022 12:03:47 -0400 Subject: [PATCH 02/15] refactoring, events --- .../core/model/catalog/product/Product.java | 16 ++++ .../product/instance/ProductInstance.java | 4 +- .../model/shoppingcart/ShoppingCartItem.java | 18 +++- .../AsynchronousEventsConfiguration.java | 26 ++++++ .../ProductCreationEventListener.java | 20 +++++ .../events/products/ProductEvent.java | 31 +++++++ .../events/products/PublishProductAspect.java | 46 ++++++++++ .../product/ProductRepositoryCustom.java | 2 + .../product/ProductRepositoryImpl.java | 90 +++++++++++++------ .../ProductAvailabilityRepository.java | 2 + .../instance/ProductInstanceRepository.java | 24 +---- .../catalog/product/ProductService.java | 10 +++ .../catalog/product/ProductServiceImpl.java | 23 ++++- .../generic/SalesManagerEntityService.java | 1 + .../test/catalog/ProductNextGenTest.java | 2 +- .../test/catalog/ProductTest.java | 2 +- .../salesmanager/test/order/InvoiceTest.java | 2 +- .../salesmanager/test/order/OrderTest.java | 2 +- .../shipping/ShippingQuoteByWeightTest.java | 2 +- .../test/shoppingcart/ShoppingCartTest.java | 2 +- .../PersistableShoppingCartItem.java | 7 ++ .../model/shoppingcart/ShoppingCartItem.java | 2 +- .../cart/ReadableShoppingCartMapper.java | 7 -- .../mapper/catalog/ReadableProductMapper.java | 13 ++- .../PersistableProductInstanceMapper.java | 5 ++ .../ShoppingCartDataPopulator.java | 2 +- .../ShoppingCartModelPopulator.java | 9 +- .../api/v1/shoppingCart/ShoppingCartApi.java | 8 +- .../customer/facade/CustomerFacadeImpl.java | 1 + .../facade/ShoppingCartFacade.java | 15 ++-- .../facade/ShoppingCartFacadeImpl.java | 54 +++++------ .../product/ProductCommonFacadeImpl.java | 2 +- .../product/ProductDefinitionFacadeImpl.java | 2 +- .../facade/product/ProductFacadeV2Impl.java | 15 +--- .../product/ProductInstanceFacadeImpl.java | 3 +- 35 files changed, 339 insertions(+), 131 deletions(-) create mode 100644 sm-core/src/main/java/com/salesmanager/core/business/configuration/events/AsynchronousEventsConfiguration.java create mode 100644 sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java create mode 100644 sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductEvent.java create mode 100644 sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/Product.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/Product.java index fb84209abf..155ef331e9 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/Product.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/Product.java @@ -534,6 +534,22 @@ public void setOwner(Customer owner) { this.owner = owner; } + public Set getInstances() { + return instances; + } + + public void setInstances(Set instances) { + this.instances = instances; + } + + public void setAvailable(boolean available) { + this.available = available; + } + + public void setProductShipeable(boolean productShipeable) { + this.productShipeable = productShipeable; + } + diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java index a6b7250ba3..f6018bdab6 100644 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java @@ -35,7 +35,9 @@ @Entity @EntityListeners(value = AuditListener.class) @Table(name = "PRODUCT_INSTANCE", -uniqueConstraints = @UniqueConstraint(columnNames = { "PRODUCT_ID", +uniqueConstraints = + @UniqueConstraint(columnNames = { + "PRODUCT_ID", "SKU" })) public class ProductInstance extends SalesManagerEntity implements Auditable { private static final long serialVersionUID = 1L; diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java index 319b9d089d..c89bea4008 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java @@ -23,7 +23,6 @@ import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.salesmanager.core.constants.SchemaConstant; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.price.FinalPrice; import com.salesmanager.core.model.common.audit.AuditListener; @@ -52,14 +51,17 @@ public class ShoppingCartItem extends SalesManagerEntity private ShoppingCart shoppingCart; @Column(name="QUANTITY") - private Integer quantity = new Integer(1); - + private Integer quantity = 1; @Embedded private AuditSection auditSection = new AuditSection(); - @Column(name="PRODUCT_ID", nullable=false) //TODO CODE + @Column(name="PRODUCT_ID", nullable=false) private Long productId; + + //SKU + @Column(name="SKU", nullable=true) + private String sku; @JsonIgnore @Transient @@ -229,4 +231,12 @@ public void setProductVirtual(boolean productVirtual) { this.productVirtual = productVirtual; } + public String getSku() { + return sku; + } + + public void setSku(String sku) { + this.sku = sku; + } + } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/AsynchronousEventsConfiguration.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/AsynchronousEventsConfiguration.java new file mode 100644 index 0000000000..6091503d58 --- /dev/null +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/AsynchronousEventsConfiguration.java @@ -0,0 +1,26 @@ +package com.salesmanager.core.business.configuration.events; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ApplicationEventMulticaster; +import org.springframework.context.event.SimpleApplicationEventMulticaster; +import org.springframework.core.task.SimpleAsyncTaskExecutor; + +/** + * Events will be asynchronous (in a different thread) + * @author carlsamson + * + */ +@Configuration +public class AsynchronousEventsConfiguration { + + @Bean(name = "applicationEventMulticaster") + public ApplicationEventMulticaster simpleApplicationEventMulticaster() { + SimpleApplicationEventMulticaster eventMulticaster + = new SimpleApplicationEventMulticaster(); + + eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor()); + return eventMulticaster; + } + +} diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java new file mode 100644 index 0000000000..c9105cdacf --- /dev/null +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java @@ -0,0 +1,20 @@ +package com.salesmanager.core.business.configuration.events.products; + +import org.springframework.context.ApplicationListener; +import org.springframework.stereotype.Component; + +/** + * Index product + * @author carlsamson + * + */ +@Component +public class ProductCreationEventListener implements ApplicationListener { + + @Override + public void onApplicationEvent(ProductEvent event) { + // TODO Auto-generated method stub + + } + +} diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductEvent.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductEvent.java new file mode 100644 index 0000000000..8f74257762 --- /dev/null +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductEvent.java @@ -0,0 +1,31 @@ +package com.salesmanager.core.business.configuration.events.products; + +import org.springframework.context.ApplicationEvent; + +import com.salesmanager.core.model.catalog.product.Product; + +public class ProductEvent extends ApplicationEvent { + + private static final long serialVersionUID = 1L; + + private Product product; + + + public ProductEvent(Object source, Product product) { + super(source); + this.product = product; + } + + + public Product getProduct() { + return product; + } + + public void setProduct(Product product) { + this.product = product; + } + + + + +} diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java new file mode 100644 index 0000000000..bcbdeb3cdd --- /dev/null +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java @@ -0,0 +1,46 @@ +package com.salesmanager.core.business.configuration.events.products; + +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Component; + +/** + * Aspect class that will trigger an event once a product is created + * Code inspired from http://www.discoversdk.com/blog/spring-event-handling-and-aop + * @author carlsamson + * + */ + +@Component +@Aspect +public class PublishProductAspect { + + private ApplicationEventPublisher eventPublisher; + @Autowired + public void setEventPublisher(ApplicationEventPublisher eventPublisher) { + this.eventPublisher = eventPublisher; + } + + @Pointcut("@target(org.springframework.stereotype.Service)") + public void serviceMethods() {} + + @Pointcut("execution(* com.salesmanager.core.business.services.catalog.product.ProductService.createProduct(com.salesmanager.core.model.catalog.product.Product))") + public void createProductMethod() {} + + + @Pointcut("serviceMethods() && createProductMethod()") + public void entityCreationMethods() {} + + @AfterReturning(value = "entityCreationMethods()", returning = "entity") + public void createEvent(JoinPoint jp, Object entity) throws Throwable { + System.out.println("*********** INTO THE METHOD ******************"); + //eventPublisher.publishEvent( + // new FooCreationEvent(entity)); + } + + +} diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryCustom.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryCustom.java index 3d1597f30c..c9c318c7c5 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryCustom.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryCustom.java @@ -41,6 +41,8 @@ Product getProductForLocale(long productId, Language language, Product getByCode(String productCode, Language language); Product getByCode(String productCode, MerchantStore store); + + Product getBySku(String sku, MerchantStore store, Language language); List getProductsForLocale(MerchantStore store, Set categoryIds, Language language, Locale locale); diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java index 60c573466c..4ade7aed0b 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java @@ -73,35 +73,6 @@ private Product get(Long productId, MerchantStore merchant) { List ids = new ArrayList(); StringBuilder qs = new StringBuilder(); - /*qs.append("select distinct p from Product as p "); - qs.append("join fetch p.availabilities pa "); - qs.append("join fetch p.merchantStore merch "); - qs.append("join fetch p.descriptions pd "); - - qs.append("left join fetch p.categories categs "); - qs.append("left join fetch categs.descriptions categsd "); - - qs.append("left join fetch pa.prices pap "); - qs.append("left join fetch pap.descriptions papd "); - - // images - qs.append("left join fetch p.images images "); - // options - qs.append("left join fetch p.attributes pattr "); - qs.append("left join fetch pattr.productOption po "); - qs.append("left join fetch po.descriptions pod "); - qs.append("left join fetch pattr.productOptionValue pov "); - qs.append("left join fetch pov.descriptions povd "); - qs.append("left join fetch p.relationships pr "); - // other lefts - qs.append("left join fetch p.manufacturer manuf "); - qs.append("left join fetch manuf.descriptions manufd "); - qs.append("left join fetch p.type type "); - qs.append("left join fetch p.taxClass tx "); - - // RENTAL - qs.append("left join fetch p.owner owner ");*/ - qs.append(productQuery()); qs.append("where p.id=:pid"); @@ -1063,6 +1034,7 @@ public List listByTaxClass(TaxClass taxClass) { } + private String productQuery() { StringBuilder qs = new StringBuilder(); qs.append("select distinct p from Product as p "); @@ -1103,4 +1075,64 @@ private String productQuery() { return qs.toString(); } + @Override + public Product getBySku(String sku, MerchantStore store, Language language) { + + try { + + StringBuilder qs = new StringBuilder(); + qs.append("select distinct p from Product as p "); + qs.append("join fetch p.descriptions pd "); + qs.append("join fetch p.merchantStore pm "); + + qs.append("left join fetch p.categories categs "); + qs.append("left join fetch categs.descriptions categsd "); + + // options + qs.append("left join fetch p.attributes pattr "); + qs.append("left join fetch pattr.productOption po "); + qs.append("left join fetch po.descriptions pod "); + qs.append("left join fetch pattr.productOptionValue pov "); + qs.append("left join fetch pov.descriptions povd "); + qs.append("left join fetch p.relationships pr "); + // other lefts + qs.append("left join fetch p.manufacturer manuf "); + qs.append("left join fetch manuf.descriptions manufd "); + qs.append("left join fetch p.type type "); + + //variants + qs.append("left join fetch p.instances pinst "); + qs.append("left join fetch pinst.variant pv "); + qs.append("left join fetch pv.productOption pvpo "); + qs.append("left join fetch pv.productOptionValue pvpov "); + qs.append("left join fetch pvpo.descriptions pvpod "); + qs.append("left join fetch pvpov.descriptions pvpovd "); + + qs.append("left join fetch pinst.variantValue pvv "); + qs.append("left join fetch pvv.productOption pvvpo "); + qs.append("left join fetch pvv.productOptionValue pvvpov "); + qs.append("left join fetch pvvpo.descriptions povvpod "); + qs.append("left join fetch pvpov.descriptions povvpovd "); + + //instance availability and price + qs.append("left join fetch pinst.availabilities pinsta "); + qs.append("left join fetch pinsta.prices pinstap "); + qs.append("left join fetch pinst.productInstanceGroup "); + + qs.append("where pinst.sku=:code or p.sku=:code and pm.id=:id"); + + String hql = qs.toString(); + Query q = this.em.createQuery(hql); + + q.setParameter("code", sku); + q.setParameter("id", store.getId()); + + return (Product) q.getSingleResult(); + + } catch (javax.persistence.NoResultException ers) { + return null; + } + + } + } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/availability/ProductAvailabilityRepository.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/availability/ProductAvailabilityRepository.java index ce61947a0c..4e6e2629ae 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/availability/ProductAvailabilityRepository.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/availability/ProductAvailabilityRepository.java @@ -62,6 +62,7 @@ public interface ProductAvailabilityRepository extends JpaRepository getBySku(String productCode); diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/instance/ProductInstanceRepository.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/instance/ProductInstanceRepository.java index 78bb9be54f..ce4d4e40ff 100644 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/instance/ProductInstanceRepository.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/instance/ProductInstanceRepository.java @@ -112,7 +112,6 @@ public interface ProductInstanceRepository extends JpaRepository findByProduct(Long productId, Integer storeId, Integer languageId); - **/ + } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductService.java b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductService.java index ef067864ba..72911eae29 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductService.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductService.java @@ -34,6 +34,8 @@ public interface ProductService extends SalesManagerEntityService List getProducts(List categoryIds) throws ServiceException; List getProductsByIds(List productIds) throws ServiceException; + + Product createProduct(Product product) throws ServiceException; /** * Get a product with only MerchantStore object @@ -76,6 +78,14 @@ List getProducts(List categoryIds, Language language) Product getByCode(String productCode, Language language); Product getByCode(String productCode, MerchantStore merchant); + + /** + * Product and or product instance + * @param productCode + * @param merchant + * @return + */ + Product getBySku(String productCode, MerchantStore merchant, Language language); /** * Find a product for a specific merchant diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductServiceImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductServiceImpl.java index bfb19067d4..2dff886b95 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductServiceImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/ProductServiceImpl.java @@ -263,8 +263,10 @@ public void update(Product product) throws ServiceException { saveOrUpdate(product); searchService.index(product.getMerchantStore(), product); } + + - private void saveOrUpdate(Product product) throws ServiceException { + private Product saveOrUpdate(Product product) throws ServiceException { LOGGER.debug("Save or update product "); Validate.notNull(product, "product cannot be null"); Validate.notNull(product.getAvailabilities(), "product must have at least one availability"); @@ -333,10 +335,14 @@ private void saveOrUpdate(Product product) throws ServiceException { } } } + + } catch (Exception e) { LOGGER.error("Cannot save images " + e.getMessage()); } + + return product; } @@ -370,6 +376,21 @@ public Product getByCode(String productCode, MerchantStore merchant) { return productRepository.getByCode(productCode, merchant); } + @Override + public Product createProduct(Product product) throws ServiceException{ + try { + return this.saveOrUpdate(product); + } catch (ServiceException e) { + throw new ServiceException("Cannot create product [" + product.getId() + "]", e); + } + + } + + @Override + public Product getBySku(String productCode, MerchantStore merchant, Language language) { + return productRepository.getBySku(productCode, merchant, language); + } + } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityService.java b/sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityService.java index ff18c08cb5..23f409b960 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityService.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/common/generic/SalesManagerEntityService.java @@ -40,6 +40,7 @@ public interface SalesManagerEntityService getAttributes() { public void setAttributes(List attributes) { this.attributes = attributes; } + public String getSku() { + return sku; + } + public void setSku(String sku) { + this.sku = sku; + } } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java index e25e3eacf0..54e7591263 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java @@ -19,7 +19,7 @@ public class ShoppingCartItem extends ShopEntity implements Serializable { private BigDecimal productPrice; private int quantity; private long productId; - private String productCode; + private String productCode;//sku private String code;//shopping cart code private boolean productVirtual; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java index bd7536b5f7..4bb1814569 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java @@ -111,13 +111,6 @@ public ReadableShoppingCart merge(ShoppingCart source, ReadableShoppingCart dest readableMinimalProductMapper.merge(item.getProduct(), shoppingCartItem, store, language); - // ReadableProductPopulator readableProductPopulator = new - // ReadableProductPopulator(); - // readableProductPopulator.setPricingService(pricingService); - // readableProductPopulator.setimageUtils(imageUtils); - // readableProductPopulator.populate(item.getProduct(), shoppingCartItem, store, - // language); - shoppingCartItem.setPrice(item.getItemPrice()); shoppingCartItem.setFinalPrice(pricingService.getDisplayAmount(item.getItemPrice(), store)); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java index 24508c438e..841d33c49b 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java @@ -30,6 +30,7 @@ import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.mapper.Mapper; +import com.salesmanager.shop.mapper.catalog.product.ReadableProductInstanceMapper; import com.salesmanager.shop.model.catalog.category.ReadableCategory; import com.salesmanager.shop.model.catalog.manufacturer.ReadableManufacturer; import com.salesmanager.shop.model.catalog.product.ProductSpecification; @@ -42,6 +43,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductProperty; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductPropertyValue; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.product.instance.ReadableProductInstance; import com.salesmanager.shop.model.catalog.product.type.ReadableProductType; import com.salesmanager.shop.model.references.DimensionUnitOfMeasure; import com.salesmanager.shop.model.references.WeightUnitOfMeasure; @@ -68,6 +70,9 @@ public class ReadableProductMapper implements Mapper { @Autowired private ReadableProductTypeMapper readableProductTypeMapper; + + @Autowired + private ReadableProductInstanceMapper readableProductInstanceMapper; @Autowired private ReadableManufacturerMapper readableManufacturerMapper; @@ -223,12 +228,18 @@ public ReadableProduct merge(Product source, ReadableProduct destination, Mercha } } } + + //variants + if(!CollectionUtils.isEmpty(source.getInstances())) { + List instances = source.getInstances().stream().map(i -> readableProductInstanceMapper.convert(i, store, language)).collect(Collectors.toList()); + destination.setVariants(instances); + } // availability ProductAvailability availability = null; for (ProductAvailability a : source.getAvailabilities()) { // TODO validate region - // if(availability.getRegion().equals(Constants.ALL_REGIONS)) {//TODO REL 2.1 + // if(availability.getRegion().equals(Constants.ALL_REGIONS)) {//TODO REL 3.X // accept a region availability = a; destination.setQuantity(availability.getProductQuantity() == null ? 1 : availability.getProductQuantity()); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java index aca8908036..13dcf0a31f 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java @@ -17,6 +17,7 @@ import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.mapper.Mapper; import com.salesmanager.shop.model.catalog.product.product.instance.PersistableProductInstance; +import com.salesmanager.shop.store.api.exception.OperationNotAllowedException; import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; import com.salesmanager.shop.store.api.exception.ServiceRuntimeException; import com.salesmanager.shop.utils.DateUtil; @@ -89,6 +90,10 @@ public ProductInstance merge(PersistableProductInstance source, ProductInstance throw new ResourceNotFoundException("Product [" + source.getId() + "] + not found for store [" + store.getCode() + "]"); } + if(product.getSku() != null && product.getSku().equals(source.getSku())) { + throw new OperationNotAllowedException("Product instance sku [" + source.getSku() + "] + must be different than product instance sku [" + product.getSku() + "]"); + } + destination.setProduct(product); return destination; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java index c5b3f61f94..eb7608b58d 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java @@ -40,7 +40,7 @@ * */ - +@Deprecated public class ShoppingCartDataPopulator extends AbstractDataPopulator { diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java index 98cba26ba5..30b002704d 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java @@ -188,12 +188,13 @@ public ShoppingCart populate(ShoppingCartData shoppingCart,ShoppingCart cartMdel } - private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem( com.salesmanager.core.model.shoppingcart.ShoppingCart cart, - ShoppingCartItem shoppingCartItem, - MerchantStore store ) - throws Exception + private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem( + com.salesmanager.core.model.shoppingcart.ShoppingCart cart, + ShoppingCartItem shoppingCartItem, + MerchantStore store ) throws Exception { + //TODO Product product = productService.getById( shoppingCartItem.getProductId() ); if ( product == null ) diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java index 955a4b5f1e..fc46e941b4 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java @@ -120,7 +120,7 @@ public ResponseEntity modifyCart( @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public ResponseEntity modifyCart( - @PathVariable String code, + @PathVariable String code,//shopping cart code @PathVariable String promo, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @@ -150,8 +150,10 @@ public ResponseEntity modifyCart( @ApiOperation(httpMethod = "POST", value = "Add to an existing shopping cart or modify an item quantity", notes = "No customer ID in scope. Modify cart for non authenticated users, as simple as {\"product\":1232,\"quantity\":0} for instance will remove item 1234 from cart", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) - public ResponseEntity modifyCart(@PathVariable String code, - @Valid @RequestBody PersistableShoppingCartItem[] shoppingCartItems, @ApiIgnore MerchantStore merchantStore, + public ResponseEntity modifyCart( + @PathVariable String code, + @Valid @RequestBody PersistableShoppingCartItem[] shoppingCartItems, + @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { try { diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java index 6b85c9b1ae..ae3259cfb1 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java @@ -283,6 +283,7 @@ public ShoppingCart mergeCart(final Customer customerModel, final String session @Override + //KEEP public Customer getCustomerByUserName(String userName, MerchantStore store){ try { diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java index 6e70d5eb09..55f03f5f80 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java @@ -46,18 +46,19 @@ public interface ShoppingCartFacade { * @return * @throws Exception */ - public ShoppingCartData getShoppingCartData(final Customer customer,final MerchantStore store,final String shoppingCartId, Language language) throws Exception; - public ShoppingCartData getShoppingCartData(final ShoppingCart shoppingCart, Language language) throws Exception; - public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language lnguage) throws Exception; + //public ShoppingCartData getShoppingCartData(final Customer customer,final MerchantStore store,final String shoppingCartId, Language language) throws Exception; + //public ShoppingCartData getShoppingCartData(final ShoppingCart shoppingCart, Language language) throws Exception; + //public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language lnguage) throws Exception; - public ShoppingCartData removeCartItem(final Long itemID, final String cartId,final MerchantStore store,final Language language ) throws Exception; - public ShoppingCartData updateCartItem(final Long itemID, final String cartId, final long quantity,final MerchantStore store,Language language ) throws Exception; + //public ShoppingCartData removeCartItem(final Long itemID, final String cartId,final MerchantStore store,final Language language ) throws Exception; + //public ShoppingCartData updateCartItem(final Long itemID, final String cartId, final long quantity,final MerchantStore store,Language language ) throws Exception; public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception; - ShoppingCartData updateCartItems(Optional promoCode, List shoppingCartItems, - MerchantStore store, Language language) throws Exception; + //ShoppingCartData updateCartItems(Optional promoCode, List shoppingCartItems, + // MerchantStore store, Language language) throws Exception; public ShoppingCart getShoppingCartModel(final String shoppingCartCode, MerchantStore store) throws Exception; public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Exception; public ShoppingCart getShoppingCartModel(final Customer customer, MerchantStore store) throws Exception; + void deleteShoppingCart(String code, MerchantStore store) throws Exception; void saveOrUpdateShoppingCart(ShoppingCart cart) throws Exception; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java index 55c60e7420..46c3b9e4dc 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java @@ -63,7 +63,7 @@ /** * @author Umesh Awasthi * @author Carl Samson - * @version 2.0 + * @version 3.2.0 * @since 1.0 */ @Service( value = "shoppingCartFacade" ) @@ -114,9 +114,13 @@ public void deleteShoppingCart(final String code, final MerchantStore store) thr } } - @Override + //@Override + //REMOVE public ShoppingCartData addItemsToShoppingCart( final ShoppingCartData shoppingCartData, - final ShoppingCartItem item, final MerchantStore store, final Language language,final Customer customer ) + final ShoppingCartItem item, + final MerchantStore store, + final Language language, + final Customer customer ) throws Exception { @@ -175,7 +179,6 @@ public ShoppingCartData addItemsToShoppingCart( final ShoppingCartData shoppingC } if(!duplicateFound) { - //shoppingCartItem.getAttributes().stream().forEach(a -> {a.setProductAttributeId(productAttributeId);}); cartModel.getLineItems().add( shoppingCartItem ); } @@ -272,10 +275,11 @@ private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem } - //used for api + //KEEP private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(ShoppingCart cartModel, PersistableShoppingCartItem shoppingCartItem, MerchantStore store) throws Exception { + //USE Product or ProductAvailability from SKU Product product = productService.getById(shoppingCartItem.getProduct()); if (product == null) { @@ -479,7 +483,8 @@ private Object getKeyValue( final String key ) return reqAttr.getRequest().getAttribute( key ); } - @Override + //@Override + //DELETE public ShoppingCartData getShoppingCartData(final Customer customer, final MerchantStore store, final String shoppingCartId, Language language) throws Exception @@ -535,27 +540,10 @@ public ShoppingCartData getShoppingCartData(final Customer customer, final Merch shoppingCartDataPopulator.setPricingService( pricingService ); shoppingCartDataPopulator.setimageUtils(imageUtils); - //Language language = (Language) getKeyValue( Constants.LANGUAGE ); MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE ); ShoppingCartData shoppingCartData = shoppingCartDataPopulator.populate( cart, merchantStore, language ); -/* List unavailables = new ArrayList(); - List availables = new ArrayList(); - //Take out items no more available - List items = shoppingCartData.getShoppingCartItems(); - for(ShoppingCartItem item : items) { - String code = item.getProductCode(); - Product p =productService.getByCode(code, language); - if(!p.isAvailable()) { - unavailables.add(item); - } else { - availables.add(item); - } - - } - shoppingCartData.setShoppingCartItems(availables); - shoppingCartData.setUnavailables(unavailables);*/ return shoppingCartData; @@ -578,7 +566,8 @@ public ShoppingCartData getShoppingCartData( ShoppingCart shoppingCartModel, Lan return shoppingCartDataPopulator.populate( shoppingCartModel, merchantStore, language ); } - @Override + //@Override + //DELETE public ShoppingCartData removeCartItem( final Long itemID, final String cartId ,final MerchantStore store,final Language language ) throws Exception { @@ -618,7 +607,8 @@ public ShoppingCartData removeCartItem( final Long itemID, final String cartId , return null; } - @Override + //@Override + //DELETE public ShoppingCartData updateCartItem( final Long itemID, final String cartId, final long newQuantity,final MerchantStore store, final Language language ) throws Exception { @@ -664,7 +654,8 @@ public ShoppingCartData updateCartItem( final Long itemID, final String cartId, //TODO promoCode request parameter - @Override + //@Override + //DELETE public ShoppingCartData updateCartItems( Optional promoCode, final List shoppingCartItems, final MerchantStore store, final Language language ) throws Exception { @@ -748,7 +739,8 @@ private ShoppingCart getCartModel( final String cartId,final MerchantStore store return null; } - @Override + //@Override + //DELETE public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language language) { try { ShoppingCart cartModel = shoppingCartService.getByCode( code, store ); @@ -809,6 +801,7 @@ public ReadableShoppingCart getCart(Customer customer, MerchantStore store, Lang } @Override + //KEEP ** ENTRY POINT ** public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore store, Language language) { @@ -840,6 +833,7 @@ public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, Merchant @Override + //KEEP public @Nullable ReadableShoppingCart removeShoppingCartItem(String cartCode, Long productId, MerchantStore merchant, Language language, boolean returnCart) throws Exception { Validate.notNull(cartCode, "Shopping cart code must not be null"); @@ -932,6 +926,7 @@ private ReadableShoppingCart readableShoppingCart(ShoppingCart cartModel, Persis } @Override + //KEEP public ReadableShoppingCart readableCart(ShoppingCart cart, MerchantStore store, Language language) { return readableShoppingCartMapper.convert(cart, store, language); @@ -1031,6 +1026,7 @@ private ReadableShoppingCart modifyCart(ShoppingCart cartModel, PersistableShopp * @return * @throws Exception */ + //KEEP private ReadableShoppingCart modifyCartMulti(ShoppingCart cartModel, List cartItems, MerchantStore store, Language language) throws Exception { @@ -1089,6 +1085,7 @@ private ReadableShoppingCart modifyCartMulti(ShoppingCart cartModel, List items, MerchantStore store, Language language) throws Exception { Validate.notNull(cartCode, "String cart code cannot be null"); Validate.notNull(items, "PersistableShoppingCartItem cannot be null"); @@ -1166,6 +1165,7 @@ public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Ex } @Override + //KEEP public ReadableShoppingCart getByCode(String code, MerchantStore store, Language language) throws Exception { ShoppingCart cart = shoppingCartService.getByCode(code, store); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductCommonFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductCommonFacadeImpl.java index 30d0bb30c2..f390a0eb21 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductCommonFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductCommonFacadeImpl.java @@ -107,7 +107,7 @@ public PersistableProduct saveProduct(MerchantStore store, PersistableProduct pr if (target.getId() != null && target.getId() > 0) { productService.update(target); } else { - productService.create(target); + productService.createProduct(target); product.setId(target.getId()); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductDefinitionFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductDefinitionFacadeImpl.java index 100e6b4e3d..e147e268ed 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductDefinitionFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductDefinitionFacadeImpl.java @@ -55,7 +55,7 @@ public Long saveProductDefinition(MerchantStore store, PersistableProductDefinit if (target.getId() != null && target.getId() > 0) { productService.update(target); } else { - productService.create(target); + productService.createProduct(target); product.setId(target.getId()); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java index b620806318..eabd3ef6f4 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java @@ -101,9 +101,9 @@ public Product getProduct(Long id, MerchantStore store) { @Override public ReadableProduct getProductByCode(MerchantStore store, String uniqueCode, Language language) { + - - Product product = productService.getByCode(uniqueCode, language); + Product product = productService.getBySku(uniqueCode, store, language); if (product == null) { throw new ResourceNotFoundException("Product [" + uniqueCode + "] not found for merchant [" + store.getCode() + "]"); @@ -113,17 +113,8 @@ public ReadableProduct getProductByCode(MerchantStore store, String uniqueCode, throw new ResourceNotFoundException("Product [" + uniqueCode + "] not found for merchant [" + store.getCode() + "]"); } - ReadableProduct readableProduct = readableProductMapper.convert(product, store, language); - //get all instances for this product group by option - //limit to 15 searches - List instances = productInstanceService.getByProductId(store, product, language); - - - //the above get all possible images - List readableInstances = instances.stream().map(p -> this.productInstance(p, store, language)).collect(Collectors.toList()); - readableProduct.setVariants(readableInstances); - + ReadableProduct readableProduct = readableProductMapper.convert(product, store, language); return readableProduct; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceFacadeImpl.java index 3e4cfcab2d..548688fc64 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceFacadeImpl.java @@ -95,8 +95,7 @@ public Long create(PersistableProductInstance productInstance, Long productId, M Validate.notNull(store, "MerchantStore cannot be null"); Validate.notNull(productInstance, "ProductInstance cannot be null"); Validate.notNull(productId, "Product id cannot be null"); - - + //variation and variation value should not be of same product option code if( productInstance.getVariant() != null && productInstance.getVariant().longValue() > 0 && From 33281c9e3e287372495256af2f73f48d76e9bc23 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Sun, 5 Jun 2022 21:32:14 -0400 Subject: [PATCH 03/15] cart management with instances --- .../order/orderproduct/OrderProduct.java | 3 +- .../ShoppingCartAttributeItem.java | 1 - .../model/shoppingcart/ShoppingCartItem.java | 18 +- .../events/products/PublishProductAspect.java | 2 +- .../ordertotal/OrderTotalServiceImpl.java | 13 +- .../shoppingcart/ShoppingCartService.java | 29 +- .../shoppingcart/ShoppingCartServiceImpl.java | 237 +-- .../business/utils/ProductPriceUtils.java | 23 +- .../shop/model/order/OrderProduct.java | 7 + .../shop/model/order/v0/Order.java | 1 + .../shop/model/order/v0/PersistableOrder.java | 2 +- .../shop/model/order/v0/ReadableOrder.java | 2 +- .../model/order/v0/ReadableOrderList.java | 2 +- .../PersistableShoppingCartItem.java | 23 +- .../shoppingcart/ReadableShoppingCart.java | 17 +- .../model/shoppingcart/ShoppingCartItem.java | 21 +- .../order/OrderProductPopulator.java | 6 +- .../order/ShoppingCartItemPopulator.java | 9 +- .../ShoppingCartDataPopulator.java | 3 +- .../ShoppingCartModelPopulator.java | 27 +- .../api/v0/order/OrderRESTController.java | 313 --- .../api/v1/shoppingCart/ShoppingCartApi.java | 7 +- .../customer/facade/CustomerFacadeImpl.java | 2 +- .../order/facade/OrderFacadeImpl.java | 2 +- .../facade/ShoppingCartFacade.java | 12 +- .../facade/ShoppingCartFacadeImpl.java | 1770 ++++++++--------- .../shoppingCart/ShoppingCartFacadeImpl.java | 2 +- .../test/shop/common/ServicesTestSupport.java | 2 +- .../cart/ShoppingCartAPIIntegrationTest.java | 28 +- 29 files changed, 1097 insertions(+), 1487 deletions(-) delete mode 100755 sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/order/OrderRESTController.java diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/order/orderproduct/OrderProduct.java b/sm-core-model/src/main/java/com/salesmanager/core/model/order/orderproduct/OrderProduct.java index f6b3061df4..59d9f52118 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/order/orderproduct/OrderProduct.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/order/orderproduct/OrderProduct.java @@ -17,7 +17,6 @@ import javax.persistence.TableGenerator; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.salesmanager.core.constants.SchemaConstant; import com.salesmanager.core.model.generic.SalesManagerEntity; import com.salesmanager.core.model.order.Order; @@ -32,7 +31,7 @@ public class OrderProduct extends SalesManagerEntity { @GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN") private Long id; - @Column (name="PRODUCT_SKU") //yess !!! rename to code + @Column (name="PRODUCT_SKU") private String sku; @Column (name="PRODUCT_NAME" , length=64 , nullable=false) diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartAttributeItem.java b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartAttributeItem.java index b9853ff930..af0a84631d 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartAttributeItem.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartAttributeItem.java @@ -14,7 +14,6 @@ import javax.persistence.Transient; import com.fasterxml.jackson.annotation.JsonIgnore; -import com.salesmanager.core.constants.SchemaConstant; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.common.audit.AuditListener; import com.salesmanager.core.model.common.audit.AuditSection; diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java index c89bea4008..bdf2d799a8 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/shoppingcart/ShoppingCartItem.java @@ -56,8 +56,9 @@ public class ShoppingCartItem extends SalesManagerEntity @Embedded private AuditSection auditSection = new AuditSection(); + @Deprecated //Use sku @Column(name="PRODUCT_ID", nullable=false) - private Long productId; + private Long productId; //SKU @Column(name="SKU", nullable=true) @@ -69,6 +70,9 @@ public class ShoppingCartItem extends SalesManagerEntity @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "shoppingCartItem") private Set attributes = new HashSet(); + + @Column(name="PRODUCT_INSTANCE", nullable=true) + private Long productInstance; @JsonIgnore @Transient @@ -132,8 +136,6 @@ public void setId(Long id) { } - - public void setAttributes(Set attributes) { this.attributes = attributes; } @@ -158,8 +160,6 @@ public Integer getQuantity() { return quantity; } - - public ShoppingCart getShoppingCart() { return shoppingCart; } @@ -239,4 +239,12 @@ public void setSku(String sku) { this.sku = sku; } + public Long getProductInstance() { + return productInstance; + } + + public void setProductInstance(Long productInstance) { + this.productInstance = productInstance; + } + } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java index bcbdeb3cdd..60b89a9485 100644 --- a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java @@ -37,7 +37,7 @@ public void entityCreationMethods() {} @AfterReturning(value = "entityCreationMethods()", returning = "entity") public void createEvent(JoinPoint jp, Object entity) throws Throwable { - System.out.println("*********** INTO THE METHOD ******************"); + //System.out.println("*********** INTO THE METHOD ******************"); //eventPublisher.publishEvent( // new FooCreationEvent(entity)); } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/order/ordertotal/OrderTotalServiceImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/services/order/ordertotal/OrderTotalServiceImpl.java index 7a6f5d9a3b..874a65e406 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/order/ordertotal/OrderTotalServiceImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/order/ordertotal/OrderTotalServiceImpl.java @@ -2,14 +2,15 @@ import java.util.ArrayList; import java.util.List; + import javax.annotation.Resource; import javax.inject.Inject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; + import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.reference.language.LanguageService; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.customer.Customer; import com.salesmanager.core.model.merchant.MerchantStore; @@ -30,9 +31,7 @@ public class OrderTotalServiceImpl implements OrderTotalService { @Inject private ProductService productService; - - @Inject - private LanguageService languageService; + @Override public OrderTotalVariation findOrderTotalVariation(OrderSummary summary, Customer customer, MerchantStore store, Language language) @@ -48,9 +47,9 @@ public OrderTotalVariation findOrderTotalVariation(OrderSummary summary, Custome List items = summary.getProducts(); for(ShoppingCartItem item : items) { - - Long productId = item.getProductId(); - Product product = productService.getProductForLocale(productId, language, languageService.toLocale(language, store)); + + Product product = productService.getBySku(item.getSku(), store, language); + //Product product = productService.getProductForLocale(productId, language, languageService.toLocale(language, store)); OrderTotal orderTotal = module.caculateProductPiceVariation(summary, item, product, customer, store); if(orderTotal==null) { diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/shoppingcart/ShoppingCartService.java b/sm-core/src/main/java/com/salesmanager/core/business/services/shoppingcart/ShoppingCartService.java index 10b0172fc1..626e21605a 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/shoppingcart/ShoppingCartService.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/shoppingcart/ShoppingCartService.java @@ -5,6 +5,7 @@ import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.common.generic.SalesManagerEntityService; import com.salesmanager.core.model.catalog.product.Product; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.customer.Customer; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.shipping.ShippingProduct; @@ -13,7 +14,7 @@ public interface ShoppingCartService extends SalesManagerEntityService { - ShoppingCart getShoppingCart(Customer customer) throws ServiceException; + ShoppingCart getShoppingCart(Customer customer, MerchantStore store) throws ServiceException; void saveOrUpdate(ShoppingCart shoppingCart) throws ServiceException; @@ -21,7 +22,6 @@ public interface ShoppingCartService extends SalesManagerEntityService createShippingProduct(ShoppingCart cart) throws ServiceException; /** - * Looks if the items in the ShoppingCart are free of charges - * - * @param cart - * @return - * @throws ServiceException - */ - //boolean isFreeShoppingCart(ShoppingCart cart) throws ServiceException; - - //boolean isFreeShoppingCart(List items) throws ServiceException; - - /** - * Populates a ShoppingCartItem from a Product and attributes if any + * Populates a ShoppingCartItem from a Product and attributes if any. Calculate price based on availability * * @param product * @return * @throws ServiceException */ - ShoppingCartItem populateShoppingCartItem(Product product) throws ServiceException; + ShoppingCartItem populateShoppingCartItem(Product product, MerchantStore store) throws ServiceException; void deleteCart(ShoppingCart cart) throws ServiceException; @@ -68,15 +57,7 @@ public interface ShoppingCartService extends SalesManagerEntityService shoppingCarts = shoppingCartRepository.findByCustomer(customer.getId()); - - //elect valid shopping cart - List validCart = shoppingCarts.stream() - .filter((cart) -> cart.getOrderId()==null) + + // elect valid shopping cart + List validCart = shoppingCarts.stream().filter((cart) -> cart.getOrderId() == null) .collect(Collectors.toList()); - + ShoppingCart shoppingCart = null; - - if(!CollectionUtils.isEmpty(validCart)) { + + if (!CollectionUtils.isEmpty(validCart)) { shoppingCart = validCart.get(0); - getPopulatedShoppingCart(shoppingCart); + getPopulatedShoppingCart(shoppingCart, store); if (shoppingCart != null && shoppingCart.isObsolete()) { delete(shoppingCart); shoppingCart = null; } } - + return shoppingCart; } catch (Exception e) { @@ -108,31 +106,27 @@ public void saveOrUpdate(ShoppingCart shoppingCart) throws ServiceException { Validate.notNull(shoppingCart, "ShoppingCart must not be null"); Validate.notNull(shoppingCart.getMerchantStore(), "ShoppingCart.merchantStore must not be null"); - try { UserContext userContext = UserContext.getCurrentInstance(); - if(userContext!=null) { + if (userContext != null) { shoppingCart.setIpAddress(userContext.getIpAddress()); } - } catch(Exception s) { + } catch (Exception s) { LOGGER.error("Cannot add ip address to shopping cart ", s); } - if (shoppingCart.getId() == null || shoppingCart.getId() == 0) { super.create(shoppingCart); } else { super.update(shoppingCart); } - - } /** - * Get a {@link ShoppingCart} for a given id and MerchantStore. Will update - * the shopping cart prices and items based on the actual inventory. This - * method will remove the shopping cart if no items are attached. + * Get a {@link ShoppingCart} for a given id and MerchantStore. Will update the + * shopping cart prices and items based on the actual inventory. This method + * will remove the shopping cart if no items are attached. */ @Override @Transactional @@ -143,7 +137,7 @@ public ShoppingCart getById(final Long id, final MerchantStore store) throws Ser if (shoppingCart == null) { return null; } - getPopulatedShoppingCart(shoppingCart); + getPopulatedShoppingCart(shoppingCart, store); if (shoppingCart.isObsolete()) { delete(shoppingCart); @@ -160,38 +154,30 @@ public ShoppingCart getById(final Long id, final MerchantStore store) throws Ser /** * Get a {@link ShoppingCart} for a given id. Will update the shopping cart - * prices and items based on the actual inventory. This method will remove - * the shopping cart if no items are attached. + * prices and items based on the actual inventory. This method will remove the + * shopping cart if no items are attached. + */ + /* + * @Override + * + * @Transactional public ShoppingCart getById(final Long id, MerchantStore + * store) throws { + * + * try { ShoppingCart shoppingCart = shoppingCartRepository.findOne(id); if + * (shoppingCart == null) { return null; } + * getPopulatedShoppingCart(shoppingCart); + * + * if (shoppingCart.isObsolete()) { delete(shoppingCart); return null; } else { + * return shoppingCart; } } catch (Exception e) { // TODO Auto-generated catch + * block e.printStackTrace(); } return null; + * + * } */ - @Override - @Transactional - public ShoppingCart getById(final Long id) { - - try { - ShoppingCart shoppingCart = shoppingCartRepository.findOne(id); - if (shoppingCart == null) { - return null; - } - getPopulatedShoppingCart(shoppingCart); - - if (shoppingCart.isObsolete()) { - delete(shoppingCart); - return null; - } else { - return shoppingCart; - } - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return null; - - } /** - * Get a {@link ShoppingCart} for a given code. Will update the shopping - * cart prices and items based on the actual inventory. This method will - * remove the shopping cart if no items are attached. + * Get a {@link ShoppingCart} for a given code. Will update the shopping cart + * prices and items based on the actual inventory. This method will remove the + * shopping cart if no items are attached. */ @Override @Transactional @@ -202,7 +188,7 @@ public ShoppingCart getByCode(final String code, final MerchantStore store) thro if (shoppingCart == null) { return null; } - getPopulatedShoppingCart(shoppingCart); + getPopulatedShoppingCart(shoppingCart, store); if (shoppingCart.isObsolete()) { delete(shoppingCart); @@ -228,24 +214,21 @@ public void deleteCart(final ShoppingCart shoppingCart) throws ServiceException } } -/* @Override - @Transactional - public ShoppingCart getByCustomer(final Customer customer) throws ServiceException { - - try { - List shoppingCart = shoppingCartRepository.findByCustomer(customer.getId()); - if (shoppingCart == null) { - return null; - } - return getPopulatedShoppingCart(shoppingCart); - - } catch (Exception e) { - throw new ServiceException(e); - } - }*/ + /* + * @Override + * + * @Transactional public ShoppingCart getByCustomer(final Customer customer) + * throws ServiceException { + * + * try { List shoppingCart = + * shoppingCartRepository.findByCustomer(customer.getId()); if (shoppingCart == + * null) { return null; } return getPopulatedShoppingCart(shoppingCart); + * + * } catch (Exception e) { throw new ServiceException(e); } } + */ @Transactional(noRollbackFor = { org.springframework.dao.EmptyResultDataAccessException.class }) - private ShoppingCart getPopulatedShoppingCart(final ShoppingCart shoppingCart) throws Exception { + private ShoppingCart getPopulatedShoppingCart(final ShoppingCart shoppingCart, MerchantStore store) throws Exception { try { @@ -263,20 +246,17 @@ private ShoppingCart getPopulatedShoppingCart(final ShoppingCart shoppingCart) t // HashSet(); for (ShoppingCartItem item : items) { LOGGER.debug("Populate item " + item.getId()); - getPopulatedItem(item); + getPopulatedItem(item, store); LOGGER.debug("Obsolete item ? " + item.isObsolete()); if (item.isObsolete()) { cartIsObsolete = true; } } - // shoppingCart.setLineItems(shoppingCartItems); Set refreshedItems = new HashSet<>(items); - //if (refreshCart) { - shoppingCart.setLineItems(refreshedItems); - update(shoppingCart); - //} + shoppingCart.setLineItems(refreshedItems); + update(shoppingCart); if (cartIsObsolete) { shoppingCart.setObsolete(true); @@ -294,11 +274,13 @@ private ShoppingCart getPopulatedShoppingCart(final ShoppingCart shoppingCart) t } @Override - public ShoppingCartItem populateShoppingCartItem(final Product product) throws ServiceException { + public ShoppingCartItem populateShoppingCartItem(Product product, MerchantStore store) throws ServiceException { Validate.notNull(product, "Product should not be null"); Validate.notNull(product.getMerchantStore(), "Product.merchantStore should not be null"); + Validate.notNull(store, "MerchantStore should not be null"); ShoppingCartItem item = new ShoppingCartItem(product); + item.setSku(product.getSku()); // set item price FinalPrice price = pricingService.calculateProductPrice(product); @@ -308,12 +290,9 @@ public ShoppingCartItem populateShoppingCartItem(final Product product) throws S } @Transactional - private void getPopulatedItem(final ShoppingCartItem item) throws Exception { - - Product product = null; + private void getPopulatedItem(final ShoppingCartItem item, MerchantStore store) throws Exception { - Long productId = item.getProductId(); - product = productService.getById(productId); + Product product = productService.getBySku(item.getSku(), store, store.getDefaultLanguage()); if (product == null) { item.setObsolete(true); @@ -321,6 +300,7 @@ private void getPopulatedItem(final ShoppingCartItem item) throws Exception { } item.setProduct(product); + item.setSku(product.getSku()); if (product.isProductVirtual()) { item.setProductVirtual(true); @@ -328,46 +308,46 @@ private void getPopulatedItem(final ShoppingCartItem item) throws Exception { Set cartAttributes = item.getAttributes(); Set productAttributes = product.getAttributes(); - List attributesList = new ArrayList();//attributes maintained - List removeAttributesList = new ArrayList();//attributes to remove - //DELETE ORPHEANS MANUALLY - if ( (productAttributes != null && productAttributes.size() > 0) || (cartAttributes != null && cartAttributes.size() > 0)) { - if(cartAttributes!=null) { - for (ShoppingCartAttributeItem attribute : cartAttributes) { - long attributeId = attribute.getProductAttributeId(); - boolean existingAttribute = false; - for (ProductAttribute productAttribute : productAttributes) { - - if (productAttribute.getId().equals(attributeId)) { - attribute.setProductAttribute(productAttribute); - attributesList.add(productAttribute); - existingAttribute = true; - break; - } - } - - if(!existingAttribute) { - removeAttributesList.add(attribute); - } - - } - } + List attributesList = new ArrayList();// attributes maintained + List removeAttributesList = new ArrayList();// attributes + // to remove + // DELETE ORPHEANS MANUALLY + if ((productAttributes != null && productAttributes.size() > 0) + || (cartAttributes != null && cartAttributes.size() > 0)) { + if (cartAttributes != null) { + for (ShoppingCartAttributeItem attribute : cartAttributes) { + long attributeId = attribute.getProductAttributeId(); + boolean existingAttribute = false; + for (ProductAttribute productAttribute : productAttributes) { + + if (productAttribute.getId().equals(attributeId)) { + attribute.setProductAttribute(productAttribute); + attributesList.add(productAttribute); + existingAttribute = true; + break; + } + } + + if (!existingAttribute) { + removeAttributesList.add(attribute); + } + + } + } } - //cleanup orphean item - if(CollectionUtils.isNotEmpty(removeAttributesList)) { - for(ShoppingCartAttributeItem attr : removeAttributesList) { + // cleanup orphean item + if (CollectionUtils.isNotEmpty(removeAttributesList)) { + for (ShoppingCartAttributeItem attr : removeAttributesList) { shoppingCartAttributeItemRepository.delete(attr); } } - //cleanup detached attributes - if(CollectionUtils.isEmpty(attributesList)) { + // cleanup detached attributes + if (CollectionUtils.isEmpty(attributesList)) { item.setAttributes(null); } - - // set item price FinalPrice price = pricingService.calculateProductPrice(product, attributesList); item.setItemPrice(price.getFinalPrice()); @@ -402,8 +382,6 @@ public List createShippingProduct(final ShoppingCart cart) thro } - - @Override public void removeShoppingCart(final ShoppingCart cart) throws ServiceException { shoppingCartRepository.delete(cart); @@ -412,7 +390,8 @@ public void removeShoppingCart(final ShoppingCart cart) throws ServiceException @Override public ShoppingCart mergeShoppingCarts(final ShoppingCart userShoppingModel, final ShoppingCart sessionCart, final MerchantStore store) throws Exception { - if (sessionCart.getCustomerId() != null && sessionCart.getCustomerId().equals(userShoppingModel.getCustomerId())) { + if (sessionCart.getCustomerId() != null + && sessionCart.getCustomerId().equals(userShoppingModel.getCustomerId())) { LOGGER.info("Session Shopping cart belongs to same logged in user"); if (CollectionUtils.isNotEmpty(userShoppingModel.getLineItems()) && CollectionUtils.isNotEmpty(sessionCart.getLineItems())) { @@ -465,37 +444,38 @@ private Set getShoppingCartItems(final ShoppingCart sessionCar if (CollectionUtils.isNotEmpty(sessionCart.getLineItems())) { shoppingCartItemsSet = new HashSet(); for (ShoppingCartItem shoppingCartItem : sessionCart.getLineItems()) { - Product product = productService.getById(shoppingCartItem.getProductId()); + Product product = productService.getBySku(shoppingCartItem.getSku(), store, store.getDefaultLanguage()); + //.getById(shoppingCartItem.getProductId()); if (product == null) { - throw new Exception("Item with id " + shoppingCartItem.getProductId() + " does not exist"); + throw new Exception("Item with sku " + shoppingCartItem.getSku() + " does not exist"); } if (product.getMerchantStore().getId().intValue() != store.getId().intValue()) { - throw new Exception("Item with id " + shoppingCartItem.getProductId() + throw new Exception("Item with sku " + shoppingCartItem.getSku() + " does not belong to merchant " + store.getId()); } - ShoppingCartItem item = populateShoppingCartItem(product); + ShoppingCartItem item = populateShoppingCartItem(product, store); item.setQuantity(shoppingCartItem.getQuantity()); item.setShoppingCart(cartModel); List cartAttributes = new ArrayList(); - if(shoppingCartItem != null && !CollectionUtils.isEmpty(shoppingCartItem.getAttributes())) { + if (shoppingCartItem != null && !CollectionUtils.isEmpty(shoppingCartItem.getAttributes())) { cartAttributes.addAll(shoppingCartItem.getAttributes()); if (CollectionUtils.isNotEmpty(cartAttributes)) { for (ShoppingCartAttributeItem shoppingCartAttributeItem : cartAttributes) { ProductAttribute productAttribute = productAttributeService .getById(shoppingCartAttributeItem.getId()); - if (productAttribute != null - && productAttribute.getProduct().getId().longValue() == product.getId().longValue()) { - + if (productAttribute != null && productAttribute.getProduct().getId().longValue() == product + .getId().longValue()) { + ShoppingCartAttributeItem attributeItem = new ShoppingCartAttributeItem(item, productAttribute); if (shoppingCartAttributeItem.getId() > 0) { attributeItem.setId(shoppingCartAttributeItem.getId()); } item.addAttributes(attributeItem); - + } } } @@ -512,27 +492,22 @@ private Set getShoppingCartItems(final ShoppingCart sessionCar @Transactional public void deleteShoppingCartItem(Long id) { - ShoppingCartItem item = shoppingCartItemRepository.findOne(id); - if(item != null) { - + if (item != null) { - if(item.getAttributes() != null) { + if (item.getAttributes() != null) { item.getAttributes().forEach(a -> shoppingCartAttributeItemRepository.deleteById(a.getId())); item.getAttributes().clear(); } - - //refresh + // refresh item = shoppingCartItemRepository.findOne(id); - //delete + // delete shoppingCartItemRepository.deleteById(id); - } - } } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java b/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java index 4ee4b78639..d4ce0d4489 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java @@ -18,11 +18,13 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; import com.salesmanager.core.business.constants.Constants; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.catalog.product.price.FinalPrice; import com.salesmanager.core.model.catalog.product.price.ProductPrice; import com.salesmanager.core.model.merchant.MerchantStore; @@ -501,8 +503,25 @@ private FinalPrice calculateFinalPrice(Product product) { FinalPrice finalPrice = null; List otherPrices = null; - - Set availabilities = product.getAvailabilities(); + /** + * Since 3.2.0 + * The rule is + * + * If product.instances contains exactly one instance + * If instance has availability we use availability from instance + * Otherwise we use price + */ + + Set availabilities = null; + if(!CollectionUtils.isEmpty(product.getInstances())) { + ProductInstance instance = product.getInstances().iterator().next(); + availabilities = instance.getAvailabilities(); + } + + if(CollectionUtils.isEmpty(availabilities)) { + availabilities = product.getAvailabilities(); + } + for(ProductAvailability availability : availabilities) { if(!StringUtils.isEmpty(availability.getRegion()) && availability.getRegion().equals(Constants.ALL_REGIONS)) {//TODO REL 2.1 accept a region Set prices = availability.getPrices(); diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/OrderProduct.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/OrderProduct.java index d1bbc03a53..2dce759c90 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/OrderProduct.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/OrderProduct.java @@ -11,5 +11,12 @@ public class OrderProduct extends Entity implements Serializable { * */ private static final long serialVersionUID = 1L; + private String sku; + public String getSku() { + return sku; + } + public void setSku(String sku) { + this.sku = sku; + } } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/Order.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/Order.java index 2bc8bed225..78e7f45269 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/Order.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/Order.java @@ -4,6 +4,7 @@ import com.salesmanager.shop.model.entity.Entity; +@Deprecated public class Order extends Entity implements Serializable { /** diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/PersistableOrder.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/PersistableOrder.java index e8f179c297..504ecd6aa4 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/PersistableOrder.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/PersistableOrder.java @@ -7,7 +7,7 @@ import com.salesmanager.shop.model.order.OrderEntity; import com.salesmanager.shop.model.order.PersistableOrderProduct; - +@Deprecated public class PersistableOrder extends OrderEntity implements Serializable { /** diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrder.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrder.java index f2631b5bbf..3e8b079aeb 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrder.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrder.java @@ -13,7 +13,7 @@ import java.io.Serializable; import java.util.List; - +@Deprecated public class ReadableOrder extends OrderEntity implements Serializable { /** diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrderList.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrderList.java index 1045723b5c..378ea62c8f 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrderList.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/order/v0/ReadableOrderList.java @@ -5,7 +5,7 @@ import com.salesmanager.shop.model.entity.ReadableList; - +@Deprecated public class ReadableOrderList extends ReadableList implements Serializable { /** diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/PersistableShoppingCartItem.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/PersistableShoppingCartItem.java index c3c7ec70f2..6d142c8f87 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/PersistableShoppingCartItem.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/PersistableShoppingCartItem.java @@ -16,10 +16,12 @@ public class PersistableShoppingCartItem implements Serializable { * */ private static final long serialVersionUID = 1L; - private Long product;//product id - private String sku; + private String product;// or product sku (instance or product) private int quantity; private String promoCode; + private List attributes; + + public String getPromoCode() { return promoCode; } @@ -32,24 +34,19 @@ public int getQuantity() { public void setQuantity(int quantity) { this.quantity = quantity; } - private List attributes; - public Long getProduct() { - return product; - } - public void setProduct(Long product) { - this.product = product; - } + public List getAttributes() { return attributes; } public void setAttributes(List attributes) { this.attributes = attributes; } - public String getSku() { - return sku; + public String getProduct() { + return product; } - public void setSku(String sku) { - this.sku = sku; + public void setProduct(String product) { + this.product = product; } + } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCart.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCart.java index c3717e45ae..b5fb25b7b8 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCart.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCart.java @@ -4,10 +4,11 @@ import java.util.ArrayList; import java.util.List; +import com.salesmanager.shop.model.catalog.product.product.instance.ReadableProductInstance; import com.salesmanager.shop.model.order.total.ReadableOrderTotal; /** - * Compatible with v1 + * Compatible with v1 + v2 * @author c.samson * */ @@ -29,6 +30,8 @@ public class ReadableShoppingCart extends ShoppingCartEntity { private Long order; private String promoCode; + private ReadableProductInstance variant; + List products = new ArrayList(); List totals; @@ -166,5 +169,17 @@ public void setPromoCode(String promoCode) { + public ReadableProductInstance getVariant() { + return variant; + } + + + + public void setVariant(ReadableProductInstance variant) { + this.variant = variant; + } + + + } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java index 54e7591263..d77a72a186 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ShoppingCartItem.java @@ -9,6 +9,12 @@ public class ShoppingCartItem extends ShopEntity implements Serializable { + public String getSku() { + return sku; + } + public void setSku(String sku) { + this.sku = sku; + } /** * */ @@ -18,8 +24,7 @@ public class ShoppingCartItem extends ShopEntity implements Serializable { private String image; private BigDecimal productPrice; private int quantity; - private long productId; - private String productCode;//sku + private String sku;//sku private String code;//shopping cart code private boolean productVirtual; @@ -68,18 +73,6 @@ public void setProductPrice(BigDecimal productPrice) { public BigDecimal getProductPrice() { return productPrice; } - public void setProductId(long productId) { - this.productId = productId; - } - public long getProductId() { - return productId; - } - public void setProductCode(String productCode) { - this.productCode = productCode; - } - public String getProductCode() { - return productCode; - } public void setImage(String image) { this.image = image; } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/order/OrderProductPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/order/OrderProductPopulator.java index b4fa3bcf06..8965b62a7b 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/order/OrderProductPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/order/OrderProductPopulator.java @@ -66,13 +66,13 @@ public OrderProduct populate(ShoppingCartItem source, OrderProduct target, try { - Product modelProduct = productService.getById(source.getProductId()); + Product modelProduct = productService.getBySku(source.getSku(), store, language); if(modelProduct==null) { - throw new ConversionException("Cannot get product with id (productId) " + source.getProductId()); + throw new ConversionException("Cannot get product with sku " + source.getSku()); } if(modelProduct.getMerchantStore().getId().intValue()!=store.getId().intValue()) { - throw new ConversionException("Invalid product id " + source.getProductId()); + throw new ConversionException("Invalid product with sku " + source.getSku()); } DigitalProduct digitalProduct = digitalProductService.getByProduct(store, modelProduct); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/order/ShoppingCartItemPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/order/ShoppingCartItemPopulator.java index 90d892a4be..7ba0058ee4 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/order/ShoppingCartItemPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/order/ShoppingCartItemPopulator.java @@ -14,6 +14,7 @@ import com.salesmanager.core.business.services.shoppingcart.ShoppingCartService; import com.salesmanager.core.business.utils.AbstractDataPopulator; import com.salesmanager.shop.model.order.PersistableOrderProduct; +import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; public class ShoppingCartItemPopulator extends AbstractDataPopulator { @@ -31,7 +32,11 @@ public ShoppingCartItem populate(PersistableOrderProduct source, /** TODO: Fix, Validate.notNull(productAttributeService, "Requires to set productAttributeService"); Validate.notNull(shoppingCartService, "Requires to set shoppingCartService"); - Product product = productService.getById(source.getProduct().getId()); + Product product = productService.getBySku(source.getSku(), store, language); + if(product==null ) { + throw new ResourceNotFoundException("No product found for sku [" + source.getSku() +"]"); + } + if(source.getAttributes()!=null) { for(com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attr : source.getAttributes()) { @@ -47,7 +52,7 @@ public ShoppingCartItem populate(PersistableOrderProduct source, /** TODO: Fix, } try { - return shoppingCartService.populateShoppingCartItem(product); + return shoppingCartService.populateShoppingCartItem(product, store); } catch (ServiceException e) { throw new ConversionException(e); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java index eb7608b58d..0b35f9cd67 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartDataPopulator.java @@ -102,10 +102,9 @@ public ShoppingCartData populate(final ShoppingCart shoppingCart, ShoppingCartItem shoppingCartItem = new ShoppingCartItem(); shoppingCartItem.setCode(cart.getCode()); - shoppingCartItem.setProductCode(item.getProduct().getSku()); + shoppingCartItem.setSku(item.getProduct().getSku()); shoppingCartItem.setProductVirtual(item.isProductVirtual()); - shoppingCartItem.setProductId(item.getProductId()); shoppingCartItem.setId(item.getId()); String itemName = item.getProduct().getProductDescription().getName(); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java index 30b002704d..7cef192c29 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/shoppingCart/ShoppingCartModelPopulator.java @@ -194,25 +194,30 @@ private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem MerchantStore store ) throws Exception { - //TODO - Product product = productService.getById( shoppingCartItem.getProductId() ); - if ( product == null ) - { - throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not exist" ); - } - if ( product.getMerchantStore().getId().intValue() != store.getId().intValue() ) - { - throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not belong to merchant " - + store.getId() ); - } + Product product = productService.getBySku(shoppingCartItem.getSku(), store, store.getDefaultLanguage()); + if ( product == null ) + { + throw new Exception( "Item with sku " + shoppingCartItem.getSku() + " does not exist" ); + } + + if ( product.getMerchantStore().getId().intValue() != store.getId().intValue() ) + { + throw new Exception( "Item with sku " + shoppingCartItem.getSku() + " does not belong to merchant " + + store.getId() ); + } + + + + com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = new com.salesmanager.core.model.shoppingcart.ShoppingCartItem( cart, product ); item.setQuantity( shoppingCartItem.getQuantity() ); item.setItemPrice( shoppingCartItem.getProductPrice() ); item.setShoppingCart( cart ); + item.setSku(shoppingCartItem.getSku()); // attributes List cartAttributes = shoppingCartItem.getShoppingCartAttributes(); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/order/OrderRESTController.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/order/OrderRESTController.java deleted file mode 100755 index 0eddbb0417..0000000000 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/order/OrderRESTController.java +++ /dev/null @@ -1,313 +0,0 @@ -package com.salesmanager.shop.store.api.v0.order; - -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService; -import com.salesmanager.core.business.services.catalog.product.file.DigitalProductService; -import com.salesmanager.core.business.services.customer.CustomerService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionService; -import com.salesmanager.core.business.services.customer.attribute.CustomerOptionValueService; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.order.OrderService; -import com.salesmanager.core.business.services.reference.country.CountryService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; -import com.salesmanager.core.business.services.user.GroupService; -import com.salesmanager.core.model.customer.Customer; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.order.Order; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.model.customer.PersistableCustomer; -import com.salesmanager.shop.model.order.v0.PersistableOrder; -import com.salesmanager.shop.model.order.v0.ReadableOrderList; -import com.salesmanager.shop.populator.customer.CustomerPopulator; -import com.salesmanager.shop.populator.order.PersistableOrderPopulator; -import com.salesmanager.shop.store.controller.order.facade.OrderFacade; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.*; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -@Controller -@RequestMapping("/services/private") -public class OrderRESTController { - - private static final Logger LOGGER = LoggerFactory.getLogger(OrderRESTController.class); - - - @Inject - private MerchantStoreService merchantStoreService; - - @Inject - private ProductService productService; - - @Inject - private ProductAttributeService productAttributeService; - - @Inject - private DigitalProductService digitalProductService; - - @Inject - private OrderFacade orderFacade; - - @Inject - private OrderService orderService; - - @Inject - private CustomerService customerService; - - @Inject - private LanguageService languageService; - - @Inject - private CustomerOptionService customerOptionService; - - @Inject - private ZoneService zoneService; - - @Inject - private CustomerOptionValueService customerOptionValueService; - - @Inject - private CountryService countryService; - - @Inject - private GroupService groupService; - - @Autowired - private CustomerPopulator customerPopulator; - - /** - * This method is for adding order to the system. Generally used for the purpose of migration only - * This method won't process any payment nor create transactions - * @param store - * @param order - * @param request - * @param response - * @return - * @throws Exception - * Use v1 methods - */ - @RequestMapping( value="/{store}/order", method=RequestMethod.POST) - @ResponseStatus(HttpStatus.CREATED) - @ResponseBody - @Deprecated - public PersistableOrder createOrder(@PathVariable final String store, @Valid @RequestBody PersistableOrder order, HttpServletRequest request, HttpServletResponse response) throws Exception { - MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); - if(merchantStore!=null) { - if(!merchantStore.getCode().equals(store)) { - merchantStore = null; - } - } - - if(merchantStore== null) { - merchantStore = merchantStoreService.getByCode(store); - } - - if(merchantStore==null) { - LOGGER.error("Merchant store is null for code " + store); - response.sendError(503, "Merchant store is null for code " + store); - return null; - } - - - PersistableCustomer cust = order.getCustomer(); - if(cust!=null) { - Customer customer = new Customer(); -/* CustomerPopulator populator = new CustomerPopulator(); - populator.setCountryService(countryService); - populator.setCustomerOptionService(customerOptionService); - populator.setCustomerOptionValueService(customerOptionValueService); - populator.setLanguageService(languageService); - populator.setZoneService(zoneService); - populator.setGroupService(groupService);*/ - customerPopulator.populate(cust, customer, merchantStore, merchantStore.getDefaultLanguage()); - customerService.save(customer); - cust.setId(customer.getId()); - } - - - Order modelOrder = new Order(); - PersistableOrderPopulator populator = new PersistableOrderPopulator(); - populator.setDigitalProductService(digitalProductService); - populator.setProductAttributeService(productAttributeService); - populator.setProductService(productService); - - populator.populate(order, modelOrder, merchantStore, merchantStore.getDefaultLanguage()); - - - orderService.save(modelOrder); - order.setId(modelOrder.getId()); - - return order; - } - - - /** - * Get a list of orders - * accept request parameter 'lang' [en,fr...] otherwise store dafault language - * accept request parameter 'start' start index for count - * accept request parameter 'max' maximum number count, otherwise returns all - * @param store - * @param order - * @param request - * @param response - * @return - * @throws Exception - */ - @RequestMapping( value="/{store}/orders/", method=RequestMethod.GET) - @ResponseStatus(HttpStatus.ACCEPTED) - @ResponseBody - public ReadableOrderList listOrders(@PathVariable final String store, HttpServletRequest request, HttpServletResponse response) throws Exception { - MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); - if(merchantStore!=null) { - if(!merchantStore.getCode().equals(store)) { - merchantStore = null; - } - } - - if(merchantStore== null) { - merchantStore = merchantStoreService.getByCode(store); - } - - if(merchantStore==null) { - LOGGER.error("Merchant store is null for code " + store); - response.sendError(503, "Merchant store is null for code " + store); - return null; - } - - //get additional request parameters for orders - String lang = request.getParameter(Constants.LANG); - String start = request.getParameter(Constants.START); - String max = request.getParameter(Constants.MAX); - - int startCount = 0; - int maxCount = 0; - - if(StringUtils.isBlank(lang)) { - lang = merchantStore.getDefaultLanguage().getCode(); - } - - - Language language = languageService.getByCode(lang); - - if(language==null) { - LOGGER.error("Language is null for code " + lang); - response.sendError(503, "Language is null for code " + lang); - return null; - } - - try { - startCount = Integer.parseInt(start); - } catch (Exception e) { - LOGGER.info("Invalid value for start " + start); - } - - try { - maxCount = Integer.parseInt(max); - } catch (Exception e) { - LOGGER.info("Invalid value for max " + max); - } - - - - ReadableOrderList returnList = orderFacade.getReadableOrderList(merchantStore, startCount, maxCount, language); - - return returnList; - } - - /** - * Get a list of orders for a given customer - * accept request parameter 'lang' [en,fr...] otherwise store dafault language - * accept request parameter 'start' start index for count - * accept request parameter 'max' maximum number count, otherwise returns all - * @param store - * @param order - * @param request - * @param response - * @return - * @throws Exception - */ - @RequestMapping( value="/{store}/orders/customer/{id}", method=RequestMethod.GET) - @ResponseStatus(HttpStatus.ACCEPTED) - @ResponseBody - public ReadableOrderList listOrders(@PathVariable final String store, @PathVariable final Long id, HttpServletRequest request, HttpServletResponse response) throws Exception { - MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); - if(merchantStore!=null) { - if(!merchantStore.getCode().equals(store)) { - merchantStore = null; - } - } - - if(merchantStore== null) { - merchantStore = merchantStoreService.getByCode(store); - } - - if(merchantStore==null) { - LOGGER.error("Merchant store is null for code " + store); - response.sendError(503, "Merchant store is null for code " + store); - return null; - } - - //get additional request parameters for orders - String lang = request.getParameter(Constants.LANG); - String start = request.getParameter(Constants.START); - String max = request.getParameter(Constants.MAX); - - int startCount = 0; - int maxCount = 0; - - if(StringUtils.isBlank(lang)) { - lang = merchantStore.getDefaultLanguage().getCode(); - } - - - Language language = languageService.getByCode(lang); - - if(language==null) { - LOGGER.error("Language is null for code " + lang); - response.sendError(503, "Language is null for code " + lang); - return null; - } - - try { - startCount = Integer.parseInt(start); - } catch (Exception e) { - LOGGER.info("Invalid value for start " + start); - } - - try { - maxCount = Integer.parseInt(max); - } catch (Exception e) { - LOGGER.info("Invalid value for max " + max); - } - - Customer customer = customerService.getById(id); - - if(customer==null) { - LOGGER.error("Customer is null for id " + id); - response.sendError(503, "Customer is null for id " + id); - return null; - } - - if(customer.getMerchantStore().getId().intValue()!=merchantStore.getId().intValue()) { - LOGGER.error("Customer is null for id " + id + " and store id " + store); - response.sendError(503, "Customer is null for id " + id + " and store id " + store); - return null; - } - - ReadableOrderList returnList = orderFacade.getReadableOrderList(merchantStore, startCount, maxCount, language); - - return returnList; - } - -} diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java index fc46e941b4..7c300f2571 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/shoppingCart/ShoppingCartApi.java @@ -283,16 +283,17 @@ public ResponseEntity modifyCart( } - @DeleteMapping(value = "/cart/{code}/product/{id}", produces = { APPLICATION_JSON_VALUE }) + @DeleteMapping(value = "/cart/{code}/product/{sku}", produces = { APPLICATION_JSON_VALUE }) @ApiOperation(httpMethod = "DELETE", value = "Remove a product from a specific cart", notes = "If body set to true returns remaining cart in body, empty cart gives empty body. If body set to false no body ", produces = "application/json", response = ReadableShoppingCart.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en"), @ApiImplicitParam(name = "body", dataType = "boolean", defaultValue = "false"), }) public ResponseEntity deleteCartItem(@PathVariable("code") String cartCode, - @PathVariable("id") Long itemId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, + @PathVariable("sku") String sku, + @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, @RequestParam(defaultValue = "false") boolean body) throws Exception { - ReadableShoppingCart updatedCart = shoppingCartFacade.removeShoppingCartItem(cartCode, itemId, merchantStore, + ReadableShoppingCart updatedCart = shoppingCartFacade.removeShoppingCartItem(cartCode, sku, merchantStore, language, body); if (body) { return new ResponseEntity<>(updatedCart, HttpStatus.OK); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java index ae3259cfb1..60fbf4bd00 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/customer/facade/CustomerFacadeImpl.java @@ -212,7 +212,7 @@ public ShoppingCart mergeCart(final Customer customerModel, final String session LOG.debug("Starting merge cart process"); if (customerModel != null) { - ShoppingCart customerCart = shoppingCartService.getShoppingCart(customerModel); + ShoppingCart customerCart = shoppingCartService.getShoppingCart(customerModel, store); if (StringUtils.isNotBlank(sessionShoppingCartId)) { ShoppingCart sessionShoppingCart = shoppingCartService.getByCode(sessionShoppingCartId, store); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java index 41d4502878..7326ac03da 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java @@ -392,7 +392,7 @@ private Order processOrderModel(ShopOrder order, Customer customer, Transaction * Before processing order quantity of item must be > 0 */ - Product product = productService.getById(item.getProductId()); + Product product = productService.getBySku(item.getSku(), store, language); if (product == null) { throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java index 55f03f5f80..378292c6e4 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacade.java @@ -46,15 +46,9 @@ public interface ShoppingCartFacade { * @return * @throws Exception */ - //public ShoppingCartData getShoppingCartData(final Customer customer,final MerchantStore store,final String shoppingCartId, Language language) throws Exception; - //public ShoppingCartData getShoppingCartData(final ShoppingCart shoppingCart, Language language) throws Exception; - //public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language lnguage) throws Exception; - //public ShoppingCartData removeCartItem(final Long itemID, final String cartId,final MerchantStore store,final Language language ) throws Exception; - //public ShoppingCartData updateCartItem(final Long itemID, final String cartId, final long quantity,final MerchantStore store,Language language ) throws Exception; public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception; - //ShoppingCartData updateCartItems(Optional promoCode, List shoppingCartItems, - // MerchantStore store, Language language) throws Exception; + public ShoppingCart getShoppingCartModel(final String shoppingCartCode, MerchantStore store) throws Exception; public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Exception; public ShoppingCart getShoppingCartModel(final Customer customer, MerchantStore store) throws Exception; @@ -121,7 +115,7 @@ ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore s /** * Removes a shopping cart item * @param cartCode - * @param productId + * @param sku * @param merchant * @param language * @param returnCart @@ -129,7 +123,7 @@ ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore s * @throws Exception */ @Nullable - ReadableShoppingCart removeShoppingCartItem(String cartCode, Long productId, MerchantStore merchant, Language language, boolean returnCart) throws Exception; + ReadableShoppingCart removeShoppingCartItem(String cartCode, String sku, MerchantStore merchant, Language language, boolean returnCart) throws Exception; /** * Add product to ShoppingCart diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java index 46c3b9e4dc..391f122564 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java @@ -41,6 +41,7 @@ import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.catalog.product.price.FinalPrice; import com.salesmanager.core.model.customer.Customer; import com.salesmanager.core.model.merchant.MerchantStore; @@ -66,269 +67,262 @@ * @version 3.2.0 * @since 1.0 */ -@Service( value = "shoppingCartFacade" ) -public class ShoppingCartFacadeImpl - implements ShoppingCartFacade -{ +@Service(value = "shoppingCartFacade") +public class ShoppingCartFacadeImpl implements ShoppingCartFacade { + private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartFacadeImpl.class); - private static final Logger LOG = LoggerFactory.getLogger(ShoppingCartFacadeImpl.class); - - @Inject - private ShoppingCartService shoppingCartService; + @Inject + private ShoppingCartService shoppingCartService; - @Inject - private ShoppingCartCalculationService shoppingCartCalculationService; + @Inject + private ShoppingCartCalculationService shoppingCartCalculationService; - @Inject - private ProductPriceUtils productPriceUtils; + @Inject + private ProductPriceUtils productPriceUtils; - @Inject - private ProductService productService; + @Inject + private ProductService productService; - @Inject - private PricingService pricingService; + @Inject + private PricingService pricingService; - @Inject - private ProductAttributeService productAttributeService; + @Inject + private ProductAttributeService productAttributeService; @Inject @Qualifier("img") private ImageFilePath imageUtils; - + @Autowired private ReadableShoppingCartMapper readableShoppingCartMapper; - public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception { - ShoppingCart cart = shoppingCartService.getById(id, store); - if(cart!=null) { - shoppingCartService.deleteCart(cart); - } - } - - @Override - public void deleteShoppingCart(final String code, final MerchantStore store) throws Exception { - ShoppingCart cart = shoppingCartService.getByCode(code, store); - if(cart!=null) { - shoppingCartService.deleteCart(cart); - } - } - - //@Override - //REMOVE - public ShoppingCartData addItemsToShoppingCart( final ShoppingCartData shoppingCartData, - final ShoppingCartItem item, - final MerchantStore store, - final Language language, - final Customer customer ) - throws Exception - { - - ShoppingCart cartModel = null; - - /** - * Sometimes a user logs in and a shopping cart is present in db (shoppingCartData - * but ui has no cookie with shopping cart code so the cart code will have - * to be added to the item in order to process add to cart normally - */ - if(shoppingCartData != null && StringUtils.isBlank(item.getCode())) { - item.setCode(shoppingCartData.getCode()); - } - - - if ( !StringUtils.isBlank( item.getCode() ) ) - { - // get it from the db - cartModel = getShoppingCartModel( item.getCode(), store ); - if ( cartModel == null ) - { - cartModel = createCartModel( shoppingCartData.getCode(), store,customer ); - } - - } - - if ( cartModel == null ) - { - - final String shoppingCartCode = - StringUtils.isNotBlank( shoppingCartData.getCode() ) ? shoppingCartData.getCode() : null; - cartModel = createCartModel( shoppingCartCode, store,customer ); - - } - com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem = - createCartItem( cartModel, item, store ); - - - boolean duplicateFound = false; - if(CollectionUtils.isEmpty(item.getShoppingCartAttributes())) {//increment quantity - //get duplicate item from the cart - Set cartModelItems = cartModel.getLineItems(); - for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) { - if(cartItem.getProduct().getId().longValue()==shoppingCartItem.getProduct().getId().longValue()) { - if(CollectionUtils.isEmpty(cartItem.getAttributes())) { - if(!duplicateFound) { - if(!shoppingCartItem.isProductVirtual()) { - cartItem.setQuantity(cartItem.getQuantity() + shoppingCartItem.getQuantity()); - } - duplicateFound = true; - break; - } - } - } - } - } - - if(!duplicateFound) { - cartModel.getLineItems().add( shoppingCartItem ); - } - - /** Update cart in database with line items **/ - shoppingCartService.saveOrUpdate( cartModel ); - - //refresh cart - cartModel = shoppingCartService.getById(cartModel.getId(), store); - - shoppingCartCalculationService.calculate( cartModel, store, language ); - - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - - - return shoppingCartDataPopulator.populate( cartModel, store, language ); - } - - private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem( final ShoppingCart cartModel, - final ShoppingCartItem shoppingCartItem, - final MerchantStore store ) - throws Exception - { - - Product product = productService.getById( shoppingCartItem.getProductId() ); - - if ( product == null ) - { - throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not exist" ); - } - - if ( product.getMerchantStore().getId().intValue() != store.getId().intValue() ) - { - throw new Exception( "Item with id " + shoppingCartItem.getProductId() + " does not belong to merchant " - + store.getId() ); - } + public void deleteShoppingCart(final Long id, final MerchantStore store) throws Exception { + ShoppingCart cart = shoppingCartService.getById(id, store); + if (cart != null) { + shoppingCartService.deleteCart(cart); + } + } - /** - * Check if product quantity is 0 - * Check if product is available - * Check if date available <= now - */ + @Override + public void deleteShoppingCart(final String code, final MerchantStore store) throws Exception { + ShoppingCart cart = shoppingCartService.getByCode(code, store); + if (cart != null) { + shoppingCartService.deleteCart(cart); + } + } - Set availabilities = product.getAvailabilities(); - if(availabilities == null) { + // @Override + // REMOVE + public ShoppingCartData addItemsToShoppingCart(final ShoppingCartData shoppingCartData, final ShoppingCartItem item, + final MerchantStore store, final Language language, final Customer customer) throws Exception { - throw new Exception( "Item with id " + product.getId() + " is not properly configured" ); + ShoppingCart cartModel = null; - } + /** + * Sometimes a user logs in and a shopping cart is present in db + * (shoppingCartData but ui has no cookie with shopping cart code so the cart + * code will have to be added to the item in order to process add to cart + * normally + */ + if (shoppingCartData != null && StringUtils.isBlank(item.getCode())) { + item.setCode(shoppingCartData.getCode()); + } - for(ProductAvailability availability : availabilities) { - if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() ==0) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } - } + if (!StringUtils.isBlank(item.getCode())) { + // get it from the db + cartModel = getShoppingCartModel(item.getCode(), store); + if (cartModel == null) { + cartModel = createCartModel(shoppingCartData.getCode(), store, customer); + } - if(!product.isAvailable()) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } + } - if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } + if (cartModel == null) { + final String shoppingCartCode = StringUtils.isNotBlank(shoppingCartData.getCode()) + ? shoppingCartData.getCode() + : null; + cartModel = createCartModel(shoppingCartCode, store, customer); - com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = - shoppingCartService.populateShoppingCartItem( product ); + } + com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem = createCartItem(cartModel, item, + store); + + boolean duplicateFound = false; + if (CollectionUtils.isEmpty(item.getShoppingCartAttributes())) {// increment quantity + // get duplicate item from the cart + Set cartModelItems = cartModel.getLineItems(); + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) { + if (cartItem.getProduct().getId().longValue() == shoppingCartItem.getProduct().getId().longValue()) { + if (CollectionUtils.isEmpty(cartItem.getAttributes())) { + if (!duplicateFound) { + if (!shoppingCartItem.isProductVirtual()) { + cartItem.setQuantity(cartItem.getQuantity() + shoppingCartItem.getQuantity()); + } + duplicateFound = true; + break; + } + } + } + } + } - item.setQuantity( shoppingCartItem.getQuantity() ); - item.setShoppingCart( cartModel ); + if (!duplicateFound) { + cartModel.getLineItems().add(shoppingCartItem); + } - // attributes - List cartAttributes = shoppingCartItem.getShoppingCartAttributes(); - if ( !CollectionUtils.isEmpty( cartAttributes ) ) - { - for ( ShoppingCartAttribute attribute : cartAttributes ) - { - ProductAttribute productAttribute = productAttributeService.getById( attribute.getAttributeId() ); - if ( productAttribute != null - && productAttribute.getProduct().getId().longValue() == product.getId().longValue() ) - { - com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = - new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( item, - productAttribute ); + /** Update cart in database with line items **/ + shoppingCartService.saveOrUpdate(cartModel); - item.addAttributes( attributeItem ); - } - } - } - return item; + // refresh cart + cartModel = shoppingCartService.getById(cartModel.getId(), store); - } + shoppingCartCalculationService.calculate(cartModel, store, language); + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); - //KEEP - private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(ShoppingCart cartModel, - PersistableShoppingCartItem shoppingCartItem, MerchantStore store) throws Exception { + return shoppingCartDataPopulator.populate(cartModel, store, language); + } + + private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(final ShoppingCart cartModel, + final ShoppingCartItem shoppingCartItem, final MerchantStore store) throws Exception { - //USE Product or ProductAvailability from SKU - Product product = productService.getById(shoppingCartItem.getProduct()); + Product product = productService.getBySku(shoppingCartItem.getSku(), store, store.getDefaultLanguage()); if (product == null) { - throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not exist"); + throw new Exception("Item with sku " + shoppingCartItem.getSku() + " does not exist"); } if (product.getMerchantStore().getId().intValue() != store.getId().intValue()) { - throw new ResourceNotFoundException("Item with id " + shoppingCartItem.getProduct() + " does not belong to merchant " - + store.getId()); + throw new Exception( + "Item with sku " + shoppingCartItem.getSku() + " does not belong to merchant " + store.getId()); } /** - * Check if product quantity is 0 - * Check if product is available - * Check if date available <= now + * Check if product quantity is 0 Check if product is available Check if date + * available <= now */ - Set availabilities = product.getAvailabilities(); - if(availabilities == null) { + Set availabilities = product.getAvailabilities(); + if (availabilities == null) { + + throw new Exception("Item with id " + product.getId() + " is not properly configured"); + + } + + for (ProductAvailability availability : availabilities) { + if (availability.getProductQuantity() == null || availability.getProductQuantity().intValue() == 0) { + throw new Exception("Item with id " + product.getId() + " is not available"); + } + } + + if (!product.isAvailable()) { + throw new Exception("Item with id " + product.getId() + " is not available"); + } + + if (!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) { + throw new Exception("Item with id " + product.getId() + " is not available"); + } + + com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService + .populateShoppingCartItem(product, store); + + item.setQuantity(shoppingCartItem.getQuantity()); + item.setShoppingCart(cartModel); + + // attributes + List cartAttributes = shoppingCartItem.getShoppingCartAttributes(); + if (!CollectionUtils.isEmpty(cartAttributes)) { + for (ShoppingCartAttribute attribute : cartAttributes) { + ProductAttribute productAttribute = productAttributeService.getById(attribute.getAttributeId()); + if (productAttribute != null + && productAttribute.getProduct().getId().longValue() == product.getId().longValue()) { + com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( + item, productAttribute); - throw new Exception( "Item with id " + product.getId() + " is not properly configured" ); + item.addAttributes(attributeItem); + } + } + } + return item; + + } + + // KEEP -- ENTRY + private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem(ShoppingCart cartModel, + PersistableShoppingCartItem shoppingCartItem, MerchantStore store) throws Exception { + + // USE Product sku + Product product = null; + + product = productService.getBySku(shoppingCartItem.getProduct(), store, store.getDefaultLanguage());// todo use + // language + // from api + // request + + if (product == null) { + throw new ResourceNotFoundException( + "Product with sku " + shoppingCartItem.getProduct() + " does not exist"); + } + + if (product.getMerchantStore().getId().intValue() != store.getId().intValue()) { + throw new ResourceNotFoundException( + "Item with id " + shoppingCartItem.getProduct() + " does not belong to merchant " + store.getId()); + } + + if (!product.isAvailable()) { + throw new Exception("Product with sku " + product.getSku() + " is not available"); + } + + if (!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) { + throw new Exception("Item with sku " + product.getSku() + " is not available"); + } - } + Set availabilities = product.getAvailabilities(); - for(ProductAvailability availability : availabilities) { - if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() ==0) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } - } + ProductInstance instance = null; + if (CollectionUtils.isNotEmpty(product.getInstances())) { + instance = product.getInstances().iterator().next(); + availabilities = instance.getAvailabilities(); + } - if(!product.isAvailable()) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } + if (CollectionUtils.isEmpty(availabilities)) { + throw new Exception( + "Item with id " + product.getId() + " is not properly configured. It contains no availability"); + } - if(!DateUtil.dateBeforeEqualsDate(product.getDateAvailable(), new Date())) { - throw new Exception( "Item with id " + product.getId() + " is not available"); - } + for (ProductAvailability availability : availabilities) { + if (availability.getProductQuantity() == null || availability.getProductQuantity().intValue() == 0) { + throw new Exception("Product with id " + product.getId() + " is not available"); + } + } + /** + * Check if product quantity is 0 Check if product is available Check if date + * available <= now + */ + // use a mapper com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService - .populateShoppingCartItem(product); + .populateShoppingCartItem(product, store); item.setQuantity(shoppingCartItem.getQuantity()); item.setShoppingCart(cartModel); + item.setSku(product.getSku()); + + if (instance != null) { + item.setProductInstance(instance.getId()); + } - //set attributes - List attributes = shoppingCartItem.getAttributes(); + // set attributes + List attributes = shoppingCartItem + .getAttributes(); if (!CollectionUtils.isEmpty(attributes)) { - for(com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) { + for (com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) { ProductAttribute productAttribute = productAttributeService.getById(attribute.getId()); @@ -344,432 +338,384 @@ private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem } return item; + } + + // used for api + private List createCartItems(ShoppingCart cartModel, + List shoppingCartItems, MerchantStore store) throws Exception { + + List productSkus = shoppingCartItems.stream().map(s -> s.getProduct()).collect(Collectors.toList()); + + List products = productSkus.stream().map(p -> this.fetchProduct(p, store, store.getDefaultLanguage())) + .collect(Collectors.toList()); + + if (products == null || products.size() != shoppingCartItems.size()) { + LOG.warn("----------------------- Items with in id-list " + productSkus + " does not exist"); + throw new ResourceNotFoundException("Item with skus " + productSkus + " does not exist"); + } + + List wrongStoreProducts = products.stream().filter(p -> p.getMerchantStore().getId() != store.getId()) + .collect(Collectors.toList()); + if (wrongStoreProducts.size() > 0) { + throw new ResourceNotFoundException("One or more of the items with id's " + + wrongStoreProducts.stream().map(s -> Long.valueOf(s.getId())).collect(Collectors.toList()) + + " does not belong to merchant " + store.getId()); + } + + List items = new ArrayList<>(); + + for (Product p : products) { + com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService + .populateShoppingCartItem(p, store); + Optional oShoppingCartItem = shoppingCartItems.stream() + .filter(i -> i.getProduct().equals(p.getSku())).findFirst(); + if (!oShoppingCartItem.isPresent()) { + // Should never happen if not something is updated in realtime or user has item + // in local storage and add it long time after to cart! + LOG.warn("Missing shoppingCartItem for product " + p.getSku() + " ( " + p.getId() + " )"); + continue; + } + PersistableShoppingCartItem shoppingCartItem = oShoppingCartItem.get(); + item.setQuantity(shoppingCartItem.getQuantity()); + item.setShoppingCart(cartModel); + + /** + * Check if product is available Check if product quantity is 0 Check if date + * available <= now + */ + if (shoppingCartItem.getQuantity() > 0 && !p.isAvailable()) { + throw new Exception("Item with id " + p.getId() + " is not available"); + } + + Set availabilities = p.getAvailabilities(); + if (availabilities == null) { + throw new Exception("Item with id " + p.getId() + " is not properly configured"); + } + + for (ProductAvailability availability : availabilities) { + if (shoppingCartItem.getQuantity() > 0 && availability.getProductQuantity() == null || availability.getProductQuantity().intValue() == 0) { + throw new Exception("Item with id " + p.getId() + " is not available"); + } + } + + if (!DateUtil.dateBeforeEqualsDate(p.getDateAvailable(), new Date())) { + throw new Exception("Item with id " + p.getId() + " is not available"); + } + // end qty & availablility checks + + // set attributes + List attributes = shoppingCartItem + .getAttributes(); + if (!CollectionUtils.isEmpty(attributes)) { + for (com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) { + + ProductAttribute productAttribute = productAttributeService.getById(attribute.getId()); + + if (productAttribute != null + && productAttribute.getProduct().getId().longValue() == p.getId().longValue()) { + + com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( + item, productAttribute); + + item.addAttributes(attributeItem); + } + } + } + items.add(item); + } + + return items; + } + + private Product fetchProduct(String sku, MerchantStore store, Language language) { + return productService.getBySku(sku, store, language); + } + + @Override + public ShoppingCart createCartModel(final String shoppingCartCode, final MerchantStore store, + final Customer customer) throws Exception { + final Long CustomerId = customer != null ? customer.getId() : null; + ShoppingCart cartModel = new ShoppingCart(); + if (StringUtils.isNotBlank(shoppingCartCode)) { + cartModel.setShoppingCartCode(shoppingCartCode); + } else { + cartModel.setShoppingCartCode(uniqueShoppingCartCode()); + } + cartModel.setMerchantStore(store); + if (CustomerId != null) { + cartModel.setCustomerId(CustomerId); + } + shoppingCartService.create(cartModel); + return cartModel; } - //used for api - private List createCartItems(ShoppingCart cartModel, - List shoppingCartItems, - MerchantStore store) throws Exception { - - List productIds = shoppingCartItems.stream().map(s -> Long.valueOf(s.getProduct())).collect(Collectors.toList()); - - List products = productService.getProductsByIds(productIds); - - if (products == null || products.size() != shoppingCartItems.size()) { - LOG.warn("----------------------- Items with in id-list " + productIds + " does not exist"); - throw new ResourceNotFoundException("Item with id " + productIds + " does not exist"); - } - - List wrongStoreProducts = products.stream().filter(p -> p.getMerchantStore().getId() != store.getId()).collect(Collectors.toList()); - if (wrongStoreProducts.size() > 0) { - throw new ResourceNotFoundException("One or more of the items with id's " + wrongStoreProducts.stream().map(s -> Long.valueOf(s.getId())).collect(Collectors.toList()) + " does not belong to merchant " - + store.getId()); - } - - List items = new ArrayList<>(); - - for (Product p: products) { - com.salesmanager.core.model.shoppingcart.ShoppingCartItem item = shoppingCartService.populateShoppingCartItem(p); - Optional oShoppingCartItem = shoppingCartItems.stream().filter(i -> i.getProduct() == p.getId()).findFirst(); - if(!oShoppingCartItem.isPresent()) { - // Should never happen if not something is updated in realtime or user has item in local storage and add it long time after to cart! - LOG.warn("Missing shoppingCartItem for product " + p.getSku() + " ( " + p.getId() + " )"); - continue; - } - PersistableShoppingCartItem shoppingCartItem = oShoppingCartItem.get(); - item.setQuantity(shoppingCartItem.getQuantity()); - item.setShoppingCart(cartModel); - - /** - * Check if product is available - * Check if product quantity is 0 - * Check if date available <= now - */ - if(!p.isAvailable()) { - throw new Exception( "Item with id " + p.getId() + " is not available"); - } - - Set availabilities = p.getAvailabilities(); - if(availabilities == null) { - throw new Exception( "Item with id " + p.getId() + " is not properly configured" ); - } - - for(ProductAvailability availability : availabilities) { - if(availability.getProductQuantity() == null || availability.getProductQuantity().intValue() ==0) { - throw new Exception( "Item with id " + p.getId() + " is not available"); - } - } - - if(!DateUtil.dateBeforeEqualsDate(p.getDateAvailable(), new Date())) { - throw new Exception( "Item with id " + p.getId() + " is not available"); - } - // end qty & availablility checks - - //set attributes - List attributes = shoppingCartItem.getAttributes(); - if (!CollectionUtils.isEmpty(attributes)) { - for(com.salesmanager.shop.model.catalog.product.attribute.ProductAttribute attribute : attributes) { - - ProductAttribute productAttribute = productAttributeService.getById(attribute.getId()); - - if (productAttribute != null - && productAttribute.getProduct().getId().longValue() == p.getId().longValue()) { - - com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem attributeItem = new com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem( - item, productAttribute); - - item.addAttributes(attributeItem); - } - } - } - items.add(item); - } - - return items; - } - - - @Override - public ShoppingCart createCartModel( final String shoppingCartCode, final MerchantStore store,final Customer customer ) - throws Exception - { - final Long CustomerId = customer != null ? customer.getId() : null; - ShoppingCart cartModel = new ShoppingCart(); - if ( StringUtils.isNotBlank( shoppingCartCode ) ) - { - cartModel.setShoppingCartCode( shoppingCartCode ); - } - else - { - cartModel.setShoppingCartCode( uniqueShoppingCartCode() ); - } - - cartModel.setMerchantStore( store ); - if ( CustomerId != null ) - { - cartModel.setCustomerId( CustomerId ); - } - shoppingCartService.create( cartModel ); - return cartModel; - } - - - - - - private com.salesmanager.core.model.shoppingcart.ShoppingCartItem getEntryToUpdate( final long entryId, - final ShoppingCart cartModel ) - { - if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) ) - { - for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() ) - { - if ( shoppingCartItem.getId().longValue() == entryId ) - { - LOG.info( "Found line item for given entry id: " + entryId ); - return shoppingCartItem; - - } - } - } - LOG.info( "Unable to find any entry for given Id: " + entryId ); - return null; - } - - private Object getKeyValue( final String key ) - { - ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); - return reqAttr.getRequest().getAttribute( key ); - } - - //@Override - //DELETE - public ShoppingCartData getShoppingCartData(final Customer customer, final MerchantStore store, - final String shoppingCartId, Language language) - throws Exception - { - - ShoppingCart cart = null; - try - { - if ( customer != null ) - { - LOG.info( "Reteriving customer shopping cart..." ); - cart = shoppingCartService.getShoppingCart( customer ); - - } - - else - { - if ( StringUtils.isNotBlank( shoppingCartId ) && cart == null ) - { - cart = shoppingCartService.getByCode( shoppingCartId, store ); - } - - } - - } - catch ( ServiceException ex ) - { - LOG.error( "Error while retriving cart from customer", ex ); - } - catch( NoResultException nre) { - //nothing - } - - if ( cart == null ) - { - return null; - } - - //if cart has been completed return null - if(cart.getOrderId() != null && cart.getOrderId().longValue() > 0) { - if ( StringUtils.isNotBlank( shoppingCartId ) && !(shoppingCartId.equals(cart.getShoppingCartCode()))) - { - cart = shoppingCartService.getByCode( shoppingCartId, store ); - } else { - return null; - } - } - - LOG.info( "Cart model found." ); - - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - - MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE ); - - ShoppingCartData shoppingCartData = shoppingCartDataPopulator.populate( cart, merchantStore, language ); - - - return shoppingCartData; - - } - - //@Override - public ShoppingCartData getShoppingCartData( ShoppingCart shoppingCartModel, Language language) - throws Exception - { - - Validate.notNull(shoppingCartModel, "Shopping Cart cannot be null"); - - - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - //Language language = (Language) getKeyValue( Constants.LANGUAGE ); - MerchantStore merchantStore = (MerchantStore) getKeyValue( Constants.MERCHANT_STORE ); - return shoppingCartDataPopulator.populate( shoppingCartModel, merchantStore, language ); - } - - //@Override - //DELETE - public ShoppingCartData removeCartItem( final Long itemID, final String cartId ,final MerchantStore store,final Language language ) - throws Exception - { - if ( StringUtils.isNotBlank( cartId ) ) - { - - ShoppingCart cartModel = getCartModel( cartId,store ); - if ( cartModel != null ) - { - if ( CollectionUtils.isNotEmpty( cartModel.getLineItems() ) ) - { - Set shoppingCartItemSet = - new HashSet(); - for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel.getLineItems() ) - { - if(shoppingCartItem.getId().longValue() == itemID.longValue() ) - { - shoppingCartService.deleteShoppingCartItem(itemID); - } else { - shoppingCartItemSet.add(shoppingCartItem); - } - } - - cartModel.setLineItems(shoppingCartItemSet); - - - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - return shoppingCartDataPopulator.populate( cartModel, store, language ); - - - } - } - } - return null; - } - - //@Override - //DELETE - public ShoppingCartData updateCartItem( final Long itemID, final String cartId, final long newQuantity,final MerchantStore store, final Language language ) - throws Exception - { - if ( newQuantity < 1 ) - { - throw new CartModificationException( "Quantity must not be less than one" ); - } - if ( StringUtils.isNotBlank( cartId ) ) - { - ShoppingCart cartModel = getCartModel( cartId,store ); - if ( cartModel != null ) - { - com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate = - getEntryToUpdate( itemID.longValue(), cartModel ); - - if ( entryToUpdate == null ) - { - throw new CartModificationException( "Unknown entry number." ); - } - - entryToUpdate.getProduct(); - - LOG.info( "Updating cart entry quantity to" + newQuantity ); - entryToUpdate.setQuantity( (int) newQuantity ); - List productAttributes = new ArrayList(); - productAttributes.addAll( entryToUpdate.getProduct().getAttributes() ); - final FinalPrice finalPrice = - productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes ); - entryToUpdate.setItemPrice( finalPrice.getFinalPrice() ); - shoppingCartService.saveOrUpdate( cartModel ); - - LOG.info( "Cart entry updated with desired quantity" ); - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - return shoppingCartDataPopulator.populate( cartModel, store, language ); - - } - } - return null; - } - - - //TODO promoCode request parameter - //@Override - //DELETE - public ShoppingCartData updateCartItems( Optional promoCode, final List shoppingCartItems, final MerchantStore store, final Language language ) - throws Exception - { - - Validate.notEmpty(shoppingCartItems,"shoppingCartItems null or empty"); - ShoppingCart cartModel = null; - Set cartItems = new HashSet(); - for(ShoppingCartItem item : shoppingCartItems) { - - if(item.getQuantity()<1) { - throw new CartModificationException( "Quantity must not be less than one" ); - } - - if(cartModel==null) { - cartModel = getCartModel( item.getCode(), store ); - } - - com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate = - getEntryToUpdate( item.getId(), cartModel ); - - if ( entryToUpdate == null ) { - throw new CartModificationException( "Unknown entry number." ); - } - - entryToUpdate.getProduct(); - - LOG.info( "Updating cart entry quantity to" + item.getQuantity() ); - entryToUpdate.setQuantity( (int) item.getQuantity() ); - - List productAttributes = new ArrayList(); - productAttributes.addAll( entryToUpdate.getProduct().getAttributes() ); - - final FinalPrice finalPrice = - productPriceUtils.getFinalProductPrice( entryToUpdate.getProduct(), productAttributes ); - entryToUpdate.setItemPrice( finalPrice.getFinalPrice() ); - - - cartItems.add(entryToUpdate); - - } - - cartModel.setPromoCode(null); - if(promoCode.isPresent()) { - cartModel.setPromoCode(promoCode.get()); - cartModel.setPromoAdded(new Date()); - } - - cartModel.setLineItems(cartItems); - shoppingCartService.saveOrUpdate( cartModel ); - - - LOG.info( "Cart entry updated with desired quantity" ); - ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); - shoppingCartDataPopulator.setShoppingCartCalculationService( shoppingCartCalculationService ); - shoppingCartDataPopulator.setPricingService( pricingService ); - shoppingCartDataPopulator.setimageUtils(imageUtils); - return shoppingCartDataPopulator.populate( cartModel, store, language ); - - } - - - private ShoppingCart getCartModel( final String cartId,final MerchantStore store ) - { - if ( StringUtils.isNotBlank( cartId ) ) - { - try - { - return shoppingCartService.getByCode( cartId, store ); - } - catch ( ServiceException e ) - { - LOG.error( "unable to find any cart asscoiated with this Id: " + cartId ); - LOG.error( "error while fetching cart model...", e ); - return null; - } - catch( NoResultException nre) { - //nothing - } - - } - return null; - } + private com.salesmanager.core.model.shoppingcart.ShoppingCartItem getEntryToUpdate(final long entryId, + final ShoppingCart cartModel) { + if (CollectionUtils.isNotEmpty(cartModel.getLineItems())) { + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel + .getLineItems()) { + if (shoppingCartItem.getId().longValue() == entryId) { + LOG.info("Found line item for given entry id: " + entryId); + return shoppingCartItem; - //@Override - //DELETE + } + } + } + LOG.info("Unable to find any entry for given Id: " + entryId); + return null; + } + + private Object getKeyValue(final String key) { + ServletRequestAttributes reqAttr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes(); + return reqAttr.getRequest().getAttribute(key); + } + + // @Override + // DELETE + public ShoppingCartData getShoppingCartData(final Customer customer, final MerchantStore store, + final String shoppingCartId, Language language) throws Exception { + + ShoppingCart cart = null; + try { + if (customer != null) { + LOG.info("Reteriving customer shopping cart..."); + cart = shoppingCartService.getShoppingCart(customer, store); + + } + + else { + if (StringUtils.isNotBlank(shoppingCartId) && cart == null) { + cart = shoppingCartService.getByCode(shoppingCartId, store); + } + + } + + } catch (ServiceException ex) { + LOG.error("Error while retriving cart from customer", ex); + } catch (NoResultException nre) { + // nothing + } + + if (cart == null) { + return null; + } + + // if cart has been completed return null + if (cart.getOrderId() != null && cart.getOrderId().longValue() > 0) { + if (StringUtils.isNotBlank(shoppingCartId) && !(shoppingCartId.equals(cart.getShoppingCartCode()))) { + cart = shoppingCartService.getByCode(shoppingCartId, store); + } else { + return null; + } + } + + LOG.info("Cart model found."); + + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); + + MerchantStore merchantStore = (MerchantStore) getKeyValue(Constants.MERCHANT_STORE); + + ShoppingCartData shoppingCartData = shoppingCartDataPopulator.populate(cart, merchantStore, language); + + return shoppingCartData; + + } + + // @Override + public ShoppingCartData getShoppingCartData(ShoppingCart shoppingCartModel, Language language) throws Exception { + + Validate.notNull(shoppingCartModel, "Shopping Cart cannot be null"); + + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); + // Language language = (Language) getKeyValue( Constants.LANGUAGE ); + MerchantStore merchantStore = (MerchantStore) getKeyValue(Constants.MERCHANT_STORE); + return shoppingCartDataPopulator.populate(shoppingCartModel, merchantStore, language); + } + + // @Override + // DELETE + public ShoppingCartData removeCartItem(final Long itemID, final String cartId, final MerchantStore store, + final Language language) throws Exception { + if (StringUtils.isNotBlank(cartId)) { + + ShoppingCart cartModel = getCartModel(cartId, store); + if (cartModel != null) { + if (CollectionUtils.isNotEmpty(cartModel.getLineItems())) { + Set shoppingCartItemSet = new HashSet(); + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cartModel + .getLineItems()) { + if (shoppingCartItem.getId().longValue() == itemID.longValue()) { + shoppingCartService.deleteShoppingCartItem(itemID); + } else { + shoppingCartItemSet.add(shoppingCartItem); + } + } + + cartModel.setLineItems(shoppingCartItemSet); + + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); + return shoppingCartDataPopulator.populate(cartModel, store, language); + + } + } + } + return null; + } + + // @Override + // DELETE + public ShoppingCartData updateCartItem(final Long itemID, final String cartId, final long newQuantity, + final MerchantStore store, final Language language) throws Exception { + if (newQuantity < 1) { + throw new CartModificationException("Quantity must not be less than one"); + } + if (StringUtils.isNotBlank(cartId)) { + ShoppingCart cartModel = getCartModel(cartId, store); + if (cartModel != null) { + com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate = getEntryToUpdate( + itemID.longValue(), cartModel); + + if (entryToUpdate == null) { + throw new CartModificationException("Unknown entry number."); + } + + entryToUpdate.getProduct(); + + LOG.info("Updating cart entry quantity to" + newQuantity); + entryToUpdate.setQuantity((int) newQuantity); + List productAttributes = new ArrayList(); + productAttributes.addAll(entryToUpdate.getProduct().getAttributes()); + final FinalPrice finalPrice = productPriceUtils.getFinalProductPrice(entryToUpdate.getProduct(), + productAttributes); + entryToUpdate.setItemPrice(finalPrice.getFinalPrice()); + shoppingCartService.saveOrUpdate(cartModel); + + LOG.info("Cart entry updated with desired quantity"); + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); + return shoppingCartDataPopulator.populate(cartModel, store, language); + + } + } + return null; + } + + // TODO promoCode request parameter + // @Override + // DELETE + public ShoppingCartData updateCartItems(Optional promoCode, final List shoppingCartItems, + final MerchantStore store, final Language language) throws Exception { + + Validate.notEmpty(shoppingCartItems, "shoppingCartItems null or empty"); + ShoppingCart cartModel = null; + Set cartItems = new HashSet(); + for (ShoppingCartItem item : shoppingCartItems) { + + if (item.getQuantity() < 1) { + throw new CartModificationException("Quantity must not be less than one"); + } + + if (cartModel == null) { + cartModel = getCartModel(item.getCode(), store); + } + + com.salesmanager.core.model.shoppingcart.ShoppingCartItem entryToUpdate = getEntryToUpdate(item.getId(), + cartModel); + + if (entryToUpdate == null) { + throw new CartModificationException("Unknown entry number."); + } + + entryToUpdate.getProduct(); + + LOG.info("Updating cart entry quantity to" + item.getQuantity()); + entryToUpdate.setQuantity((int) item.getQuantity()); + + List productAttributes = new ArrayList(); + productAttributes.addAll(entryToUpdate.getProduct().getAttributes()); + + final FinalPrice finalPrice = productPriceUtils.getFinalProductPrice(entryToUpdate.getProduct(), + productAttributes); + entryToUpdate.setItemPrice(finalPrice.getFinalPrice()); + + cartItems.add(entryToUpdate); + + } + + cartModel.setPromoCode(null); + if (promoCode.isPresent()) { + cartModel.setPromoCode(promoCode.get()); + cartModel.setPromoAdded(new Date()); + } + + cartModel.setLineItems(cartItems); + shoppingCartService.saveOrUpdate(cartModel); + + LOG.info("Cart entry updated with desired quantity"); + ShoppingCartDataPopulator shoppingCartDataPopulator = new ShoppingCartDataPopulator(); + shoppingCartDataPopulator.setShoppingCartCalculationService(shoppingCartCalculationService); + shoppingCartDataPopulator.setPricingService(pricingService); + shoppingCartDataPopulator.setimageUtils(imageUtils); + return shoppingCartDataPopulator.populate(cartModel, store, language); + + } + + private ShoppingCart getCartModel(final String cartId, final MerchantStore store) { + if (StringUtils.isNotBlank(cartId)) { + try { + return shoppingCartService.getByCode(cartId, store); + } catch (ServiceException e) { + LOG.error("unable to find any cart asscoiated with this Id: " + cartId); + LOG.error("error while fetching cart model...", e); + return null; + } catch (NoResultException nre) { + // nothing + } + + } + return null; + } + + // @Override + // DELETE public ShoppingCartData getShoppingCartData(String code, MerchantStore store, Language language) { try { - ShoppingCart cartModel = shoppingCartService.getByCode( code, store ); - if(cartModel!=null) { + ShoppingCart cartModel = shoppingCartService.getByCode(code, store); + if (cartModel != null) { ShoppingCartData cart = getShoppingCartData(cartModel, language); return cart; } - } catch( NoResultException nre) { - //nothing + } catch (NoResultException nre) { + // nothing - } catch(Exception e) { - LOG.error("Cannot retrieve cart code " + code,e); + } catch (Exception e) { + LOG.error("Cannot retrieve cart code " + code, e); } - return null; } @Override - public ShoppingCart getShoppingCartModel(String shoppingCartCode, - MerchantStore store) throws Exception { - return shoppingCartService.getByCode( shoppingCartCode, store ); + public ShoppingCart getShoppingCartModel(String shoppingCartCode, MerchantStore store) throws Exception { + return shoppingCartService.getByCode(shoppingCartCode, store); } @Override - public ShoppingCart getShoppingCartModel(Customer customer, - MerchantStore store) throws Exception { - return shoppingCartService.getShoppingCart(customer); + public ShoppingCart getShoppingCartModel(Customer customer, MerchantStore store) throws Exception { + return shoppingCartService.getShoppingCart(customer, store); } @Override @@ -781,366 +727,352 @@ public void saveOrUpdateShoppingCart(ShoppingCart cart) throws Exception { @Override public ReadableShoppingCart getCart(Customer customer, MerchantStore store, Language language) throws Exception { - Validate.notNull(customer,"Customer cannot be null"); - Validate.notNull(customer.getId(),"Customer.id cannot be null or empty"); + Validate.notNull(customer, "Customer cannot be null"); + Validate.notNull(customer.getId(), "Customer.id cannot be null or empty"); - //Check if customer has an existing shopping cart - ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer); + // Check if customer has an existing shopping cart + ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer, store); - if(cartModel == null) { + if (cartModel == null) { return null; } - shoppingCartCalculationService.calculate( cartModel, store, language ); - - ReadableShoppingCart readableCart = new ReadableShoppingCart(); - readableCart = readableShoppingCartMapper.convert(cartModel, store, language); + shoppingCartCalculationService.calculate(cartModel, store, language); + ReadableShoppingCart readableCart = new ReadableShoppingCart(); + readableCart = readableShoppingCartMapper.convert(cartModel, store, language); return readableCart; } @Override - //KEEP ** ENTRY POINT ** - public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore store, - Language language) { + // KEEP ** ENTRY POINT ** + public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, MerchantStore store, Language language) { - Validate.notNull(item,"PersistableShoppingCartItem cannot be null"); + Validate.notNull(item, "PersistableShoppingCartItem cannot be null"); - //if cart does not exist create a new one + // if cart does not exist create a new one ShoppingCart cartModel = new ShoppingCart(); cartModel.setMerchantStore(store); cartModel.setShoppingCartCode(uniqueShoppingCartCode()); - - if(!StringUtils.isBlank(item.getPromoCode())) { + + if (!StringUtils.isBlank(item.getPromoCode())) { cartModel.setPromoCode(item.getPromoCode()); cartModel.setPromoAdded(new Date()); } - try { - return readableShoppingCart(cartModel,item,store,language); + return readableShoppingCart(cartModel, item, store, language); } catch (Exception e) { - if(e instanceof ResourceNotFoundException) { - throw (ResourceNotFoundException)e; + if (e instanceof ResourceNotFoundException) { + throw (ResourceNotFoundException) e; } else { throw new ServiceRuntimeException(e); } } } + @Override + // KEEP + public @Nullable ReadableShoppingCart removeShoppingCartItem(String cartCode, String sku, + MerchantStore merchant, Language language, boolean returnCart) throws Exception { + Validate.notNull(cartCode, "Shopping cart code must not be null"); + Validate.notNull(sku, "product sku must not be null"); + Validate.notNull(merchant, "MerchantStore must not be null"); + + // get cart + ShoppingCart cart = getCartModel(cartCode, merchant); + + if (cart == null) { + throw new ResourceNotFoundException("Cart code [ " + cartCode + " ] not found"); + } + Set items = new HashSet(); + com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemToDelete = null; + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cart.getLineItems()) { + if (shoppingCartItem.getProduct().getSku().equals(sku)) { + // get cart item + itemToDelete = getEntryToUpdate(shoppingCartItem.getId(), cart); - @Override - //KEEP - public @Nullable ReadableShoppingCart removeShoppingCartItem(String cartCode, Long productId, - MerchantStore merchant, Language language, boolean returnCart) throws Exception { - Validate.notNull(cartCode, "Shopping cart code must not be null"); - Validate.notNull(productId, "product id must not be null"); - Validate.notNull(merchant, "MerchantStore must not be null"); - - - //get cart - ShoppingCart cart = getCartModel(cartCode, merchant); - - if(cart == null) { - throw new ResourceNotFoundException("Cart code [ " + cartCode + " ] not found"); - } - - Set items = new HashSet(); - com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemToDelete = null; - for ( com.salesmanager.core.model.shoppingcart.ShoppingCartItem shoppingCartItem : cart.getLineItems() ) - { - if ( shoppingCartItem.getProduct().getId().longValue() == productId.longValue() ) - { - //get cart item - itemToDelete = - getEntryToUpdate( shoppingCartItem.getId(), cart ); - - - //break; - - } else { - items.add(shoppingCartItem); - } - } - //delete item - if(itemToDelete!=null) { - shoppingCartService.deleteShoppingCartItem(itemToDelete.getId()); - } - - //remaining items - if(items.size()>0) { - cart.setLineItems(items); - } else { - cart.getLineItems().clear(); - } - - shoppingCartService.saveOrUpdate(cart);//update cart with remaining items - if(items.size()>0 & returnCart) { - return this.getByCode(cartCode, merchant, language); - } - return null; - } + // break; - private ReadableShoppingCart readableShoppingCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store, - Language language) throws Exception { + } else { + items.add(shoppingCartItem); + } + } + // delete item + if (itemToDelete != null) { + shoppingCartService.deleteShoppingCartItem(itemToDelete.getId()); + } + + // remaining items + if (items.size() > 0) { + cart.setLineItems(items); + } else { + cart.getLineItems().clear(); + } + + shoppingCartService.saveOrUpdate(cart);// update cart with remaining items + if (items.size() > 0 & returnCart) { + return this.getByCode(cartCode, merchant, language); + } + return null; + } + // KEEP + private ReadableShoppingCart readableShoppingCart(ShoppingCart cartModel, PersistableShoppingCartItem item, + MerchantStore store, Language language) throws Exception { com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store); - //need to check if the item is already in the cart - boolean duplicateFound = false; - //only if item has no attributes - if(CollectionUtils.isEmpty(item.getAttributes())) {//increment quantity - //get duplicate item from the cart - Set cartModelItems = cartModel.getLineItems(); - for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) { - if(cartItem.getProduct().getId().longValue()==item.getProduct().longValue()) { - if(CollectionUtils.isEmpty(cartItem.getAttributes())) { - if(!duplicateFound) { - if(!itemModel.isProductVirtual()) { - cartItem.setQuantity(cartItem.getQuantity() + item.getQuantity()); - } - duplicateFound = true; - break; - } - } - } - } - } - - if(!duplicateFound) { - cartModel.getLineItems().add( itemModel ); - } - - saveShoppingCart( cartModel ); - - //refresh cart - cartModel = shoppingCartService.getById(cartModel.getId(), store); - - shoppingCartCalculationService.calculate( cartModel, store, language ); - return readableShoppingCartMapper.convert(cartModel, store, language); + // need to check if the item is already in the cart + boolean duplicateFound = false; + // only if item has no attributes + if (CollectionUtils.isEmpty(item.getAttributes())) {// increment quantity + // get duplicate item from the cart + Set cartModelItems = cartModel.getLineItems(); + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem cartItem : cartModelItems) { + if (cartItem.getProduct().getSku().equals(item.getProduct())) { + if (CollectionUtils.isEmpty(cartItem.getAttributes())) { + if (!duplicateFound) { + if (!itemModel.isProductVirtual()) { + cartItem.setQuantity(cartItem.getQuantity() + item.getQuantity()); + } + duplicateFound = true; + break; + } + } + } + } + } + + if (!duplicateFound) { + cartModel.getLineItems().add(itemModel); + } + + saveShoppingCart(cartModel); + + // refresh cart + cartModel = shoppingCartService.getById(cartModel.getId(), store); + + shoppingCartCalculationService.calculate(cartModel, store, language); + return readableShoppingCartMapper.convert(cartModel, store, language); } - + @Override - //KEEP + // KEEP public ReadableShoppingCart readableCart(ShoppingCart cart, MerchantStore store, Language language) { - return readableShoppingCartMapper.convert(cart, store, language); - + return readableShoppingCartMapper.convert(cart, store, language); } + private ReadableShoppingCart modifyCart(ShoppingCart cartModel, PersistableShoppingCartItem item, + MerchantStore store, Language language) throws Exception { - private ReadableShoppingCart modifyCart(ShoppingCart cartModel, PersistableShoppingCartItem item, MerchantStore store, - Language language) throws Exception { + com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store); + boolean itemModified = false; + // check if existing product + Set items = cartModel.getLineItems(); + if (!CollectionUtils.isEmpty(items)) { + Set newItems = new HashSet(); + Set removeItems = new HashSet(); + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem anItem : items) {// take care of existing + // product + if (itemModel.getProduct().getId().longValue() == anItem.getProduct().getId()) { + if (item.getQuantity() == 0) { + // left aside item to be removed + // don't add it to new list of item + removeItems.add(anItem); + } else { + // new quantity + anItem.setQuantity(item.getQuantity()); + newItems.add(anItem); + } + itemModified = true; + } else { + newItems.add(anItem); + } + } - com.salesmanager.core.model.shoppingcart.ShoppingCartItem itemModel = createCartItem(cartModel, item, store); + if (!removeItems.isEmpty()) { + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem emptyItem : removeItems) { + shoppingCartService.deleteShoppingCartItem(emptyItem.getId()); + } - boolean itemModified = false; - //check if existing product - Set items = cartModel.getLineItems(); - if(!CollectionUtils.isEmpty(items)) { - Set newItems = new HashSet(); - Set removeItems = new HashSet(); - for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem anItem : items) {//take care of existing product - if(itemModel.getProduct().getId().longValue() == anItem.getProduct().getId()) { - if(item.getQuantity()==0) { - //left aside item to be removed - //don't add it to new list of item - removeItems.add(anItem); - } else { - //new quantity - anItem.setQuantity(item.getQuantity()); - newItems.add(anItem); - } - itemModified = true; - } else { - newItems.add(anItem); - } - } - - if(!removeItems.isEmpty()) { - for(com.salesmanager.core.model.shoppingcart.ShoppingCartItem emptyItem : removeItems) { - shoppingCartService.deleteShoppingCartItem(emptyItem.getId()); - } - - } - - if(!itemModified) { - newItems.add(itemModel); - } - - if(newItems.isEmpty()) { - newItems = null; - } - - cartModel.setLineItems(newItems); - } else { - //new item - if(item.getQuantity() > 0) { - cartModel.getLineItems().add( itemModel ); - } - } - - //if cart items are null just return cart with no items - - //promo code added to the cart but no promo cart exists - if(!StringUtils.isBlank(item.getPromoCode()) && StringUtils.isBlank(cartModel.getPromoCode())) { + } + + if (!itemModified) { + newItems.add(itemModel); + } + + if (newItems.isEmpty()) { + newItems = null; + } + + cartModel.setLineItems(newItems); + } else { + // new item + if (item.getQuantity() > 0) { + cartModel.getLineItems().add(itemModel); + } + } + + // if cart items are null just return cart with no items + + // promo code added to the cart but no promo cart exists + if (!StringUtils.isBlank(item.getPromoCode()) && StringUtils.isBlank(cartModel.getPromoCode())) { cartModel.setPromoCode(item.getPromoCode()); cartModel.setPromoAdded(new Date()); } - saveShoppingCart( cartModel ); - - //refresh cart - cartModel = shoppingCartService.getById(cartModel.getId(), store); + saveShoppingCart(cartModel); - if(cartModel==null) { - return null; - } + // refresh cart + cartModel = shoppingCartService.getById(cartModel.getId(), store); - shoppingCartCalculationService.calculate( cartModel, store, language ); + if (cartModel == null) { + return null; + } + shoppingCartCalculationService.calculate(cartModel, store, language); - ReadableShoppingCart readableCart = new ReadableShoppingCart(); - readableCart = readableShoppingCartMapper.convert(cartModel, store, language); + ReadableShoppingCart readableCart = new ReadableShoppingCart(); + readableCart = readableShoppingCartMapper.convert(cartModel, store, language); return readableCart; } + /** + * Update cart based on the Items coming in with cartItems, Items not in + * incoming will not be affected, Items with Qty set to 0 will be removed from + * cart + * + * @param cartModel + * @param cartItems + * @param store + * @param language + * @return + * @throws Exception + */ + // KEEP + private ReadableShoppingCart modifyCartMulti(ShoppingCart cartModel, List cartItems, + MerchantStore store, Language language) throws Exception { + + int itemUpdatedCnt = 0; + List inCartItemList = createCartItems(cartModel, + cartItems, store); + + Set existingItems = cartModel.getLineItems(); + // loop over incoming items since they drive changes + for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem newItemValue : inCartItemList) { + + // check that item exist in persisted cart + Optional oOldItem = existingItems.stream() + .filter(i -> i.getSku().equals(newItemValue.getSku()) + + ).findFirst(); + + if (oOldItem.isPresent()) { + // update of existing cartItem + com.salesmanager.core.model.shoppingcart.ShoppingCartItem oldCartItem = oOldItem.get(); + if (oldCartItem.getQuantity().intValue() == newItemValue.getQuantity()) { + // this is unchanged + continue; + } + if (newItemValue.getQuantity() == 0) { + // remove from cart + shoppingCartService.deleteShoppingCartItem(oldCartItem.getId()); + cartModel.getLineItems().remove(oldCartItem); + ++itemUpdatedCnt; + continue; + } + // update qty + oldCartItem.setQuantity(newItemValue.getQuantity()); + ++itemUpdatedCnt; + } else { + // addition of new item + cartModel.getLineItems().add(newItemValue); + ++itemUpdatedCnt; + } + } + // at the moment we expect that some change have been done + saveShoppingCart(cartModel); + + // refresh cart + cartModel = shoppingCartService.getById(cartModel.getId(), store); + + if (cartModel == null) { + return null; + } + + shoppingCartCalculationService.calculate(cartModel, store, language); - /** - * Update cart based on the Items coming in with cartItems, - * Items not in incoming will not be affected, - * Items with Qty set to 0 will be removed from cart - * - * @param cartModel - * @param cartItems - * @param store - * @param language - * @return - * @throws Exception - */ - //KEEP - private ReadableShoppingCart modifyCartMulti(ShoppingCart cartModel, List cartItems, MerchantStore store, - Language language) throws Exception { - - - List inCartItemList = createCartItems(cartModel, cartItems, store); - - int itemUpdatedCnt = 0; - - Set existingItems = cartModel.getLineItems(); - // loop over incoming items since they drive changes - for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem newItemValue : inCartItemList) { - - // check that item exist in persisted cart - Optional oOldItem = - existingItems.stream().filter(i -> i.getProductId().intValue() == newItemValue.getProductId().intValue()).findFirst(); - - if (oOldItem.isPresent()) { - // update of existing cartItem - com.salesmanager.core.model.shoppingcart.ShoppingCartItem oldCartItem = oOldItem.get(); - if (oldCartItem.getQuantity().intValue() == newItemValue.getQuantity()) { - // this is unchanged - continue; - } - if (newItemValue.getQuantity() == 0) { - // remove from cart - shoppingCartService.deleteShoppingCartItem(oldCartItem.getId()); - cartModel.getLineItems().remove(oldCartItem); - ++itemUpdatedCnt; - continue; - } - // update qty - oldCartItem.setQuantity(newItemValue.getQuantity()); - ++itemUpdatedCnt; - } else { - // addition of new item - cartModel.getLineItems().add(newItemValue); - ++itemUpdatedCnt; - } - } - // at the moment we expect that some change have been done - saveShoppingCart(cartModel); - - //refresh cart - cartModel = shoppingCartService.getById(cartModel.getId(), store); - - if (cartModel == null) { - return null; - } - - - shoppingCartCalculationService.calculate(cartModel, store, language); - - return readableShoppingCartMapper.convert(cartModel, store, language); - - - } + return readableShoppingCartMapper.convert(cartModel, store, language); + + } @Override - //KEEP + // KEEP public ReadableShoppingCart addToCart(Customer customer, PersistableShoppingCartItem item, MerchantStore store, Language language) throws Exception { - Validate.notNull(customer,"Customer cannot be null"); - Validate.notNull(customer.getId(),"Customer.id cannot be null or empty"); + Validate.notNull(customer, "Customer cannot be null"); + Validate.notNull(customer.getId(), "Customer.id cannot be null or empty"); - ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer); + ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer, store); - //if cart does not exist create a new one - if(cartModel==null) { + // if cart does not exist create a new one + if (cartModel == null) { cartModel = new ShoppingCart(); cartModel.setCustomerId(customer.getId()); cartModel.setMerchantStore(store); cartModel.setShoppingCartCode(uniqueShoppingCartCode()); } - return readableShoppingCart(cartModel,item,store,language); + return readableShoppingCart(cartModel, item, store, language); } - @Override - //KEEP - public ReadableShoppingCart modifyCart(String cartCode, PersistableShoppingCartItem item, MerchantStore store, - Language language) throws Exception { - - Validate.notNull(cartCode, "String cart code cannot be null"); - Validate.notNull(item, "PersistableShoppingCartItem cannot be null"); + @Override + // KEEP + public ReadableShoppingCart modifyCart(String cartCode, PersistableShoppingCartItem item, MerchantStore store, + Language language) throws Exception { - ShoppingCart cartModel = getCartModel(cartCode, store); - if (cartModel == null) { - throw new ResourceNotFoundException("Cart code [" + cartCode + "] not found"); - } + Validate.notNull(cartCode, "String cart code cannot be null"); + Validate.notNull(item, "PersistableShoppingCartItem cannot be null"); - return modifyCart(cartModel, item, store, language); - } + ShoppingCart cartModel = getCartModel(cartCode, store); + if (cartModel == null) { + throw new ResourceNotFoundException("Cart code [" + cartCode + "] not found"); + } - @Override - //KEEP - public ReadableShoppingCart modifyCartMulti(String cartCode, List items, MerchantStore store, Language language) throws Exception { - Validate.notNull(cartCode, "String cart code cannot be null"); - Validate.notNull(items, "PersistableShoppingCartItem cannot be null"); + return modifyCart(cartModel, item, store, language); + } - ShoppingCart cartModel = this.getCartModel(cartCode, store); - if (cartModel == null) { - throw new IllegalArgumentException("Cart code not valid"); - } + @Override + // KEEP + public ReadableShoppingCart modifyCartMulti(String cartCode, List items, + MerchantStore store, Language language) throws Exception { + Validate.notNull(cartCode, "String cart code cannot be null"); + Validate.notNull(items, "PersistableShoppingCartItem cannot be null"); + + ShoppingCart cartModel = this.getCartModel(cartCode, store); + if (cartModel == null) { + throw new IllegalArgumentException("Cart code not valid"); + } - return modifyCartMulti(cartModel, items, store, language); - } + return modifyCartMulti(cartModel, items, store, language); + } - private void saveShoppingCart(ShoppingCart shoppingCart) throws Exception { + private void saveShoppingCart(ShoppingCart shoppingCart) throws Exception { shoppingCartService.save(shoppingCart); } private String uniqueShoppingCartCode() { - return UUID.randomUUID().toString().replaceAll( "-", "" ); + return UUID.randomUUID().toString().replaceAll("-", ""); } @Override @@ -1150,9 +1082,9 @@ public ReadableShoppingCart getById(Long shoppingCartId, MerchantStore store, La ReadableShoppingCart readableCart = null; - if(cart != null) { + if (cart != null) { - readableCart = readableShoppingCartMapper.convert(cart, store, language); + readableCart = readableShoppingCartMapper.convert(cart, store, language); } @@ -1165,33 +1097,30 @@ public ShoppingCart getShoppingCartModel(Long id, MerchantStore store) throws Ex } @Override - //KEEP + // KEEP public ReadableShoppingCart getByCode(String code, MerchantStore store, Language language) throws Exception { ShoppingCart cart = shoppingCartService.getByCode(code, store); ReadableShoppingCart readableCart = null; - if(cart != null) { - - - readableCart = readableShoppingCartMapper.convert(cart, store, language); - - - - if(!StringUtils.isBlank(cart.getPromoCode())) { - Date promoDateAdded = cart.getPromoAdded();//promo valid 1 day - if(promoDateAdded == null) { - promoDateAdded = new Date(); - } - Instant instant = promoDateAdded.toInstant(); - ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault()); - LocalDate date = zdt.toLocalDate(); - //date added < date + 1 day - LocalDate tomorrow = LocalDate.now().plusDays(1); - if(date.isBefore(tomorrow)) { - readableCart.setPromoCode(cart.getPromoCode()); - } - } + if (cart != null) { + + readableCart = readableShoppingCartMapper.convert(cart, store, language); + + if (!StringUtils.isBlank(cart.getPromoCode())) { + Date promoDateAdded = cart.getPromoAdded();// promo valid 1 day + if (promoDateAdded == null) { + promoDateAdded = new Date(); + } + Instant instant = promoDateAdded.toInstant(); + ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault()); + LocalDate date = zdt.toLocalDate(); + // date added < date + 1 day + LocalDate tomorrow = LocalDate.now().plusDays(1); + if (date.isBefore(tomorrow)) { + readableCart.setPromoCode(cart.getPromoCode()); + } + } } return readableCart; @@ -1201,8 +1130,9 @@ public ReadableShoppingCart getByCode(String code, MerchantStore store, Language @Override public void setOrderId(String code, Long orderId, MerchantStore store) throws Exception { ShoppingCart cart = this.getShoppingCartModel(code, store); - if(cart == null) { - LOG.warn("Shopping cart with code [" + code + "] not found, expected to find a cart to set order id [" + orderId + "]"); + if (cart == null) { + LOG.warn("Shopping cart with code [" + code + "] not found, expected to find a cart to set order id [" + + orderId + "]"); } else { cart.setOrderId(orderId); } @@ -1213,18 +1143,16 @@ public void setOrderId(String code, Long orderId, MerchantStore store) throws Ex @Override public ReadableShoppingCart modifyCart(String cartCode, String promo, MerchantStore store, Language language) throws Exception { - + ShoppingCart cart = shoppingCartService.getByCode(cartCode, store); cart.setPromoCode(promo); cart.setPromoAdded(new Date()); - + shoppingCartService.save(cart); - return readableShoppingCartMapper.convert(cart, store, language); + return readableShoppingCartMapper.convert(cart, store, language); } - - } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/shoppingCart/ShoppingCartFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/shoppingCart/ShoppingCartFacadeImpl.java index 5a75638507..534c59c508 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/shoppingCart/ShoppingCartFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/shoppingCart/ShoppingCartFacadeImpl.java @@ -48,7 +48,7 @@ public ReadableShoppingCart get(Optional cart, Long customerId, Merchant throw new ResourceNotFoundException("No Customer found for id [" + customerId + "]"); } - ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer); + ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer, store); if(cart.isPresent()) { cartModel = customerFacade.mergeCart(customer, cart.get(), store, language); diff --git a/sm-shop/src/test/java/com/salesmanager/test/shop/common/ServicesTestSupport.java b/sm-shop/src/test/java/com/salesmanager/test/shop/common/ServicesTestSupport.java index 5c96c5f7ad..379243c950 100755 --- a/sm-shop/src/test/java/com/salesmanager/test/shop/common/ServicesTestSupport.java +++ b/sm-shop/src/test/java/com/salesmanager/test/shop/common/ServicesTestSupport.java @@ -204,7 +204,7 @@ protected ReadableShoppingCart sampleCart() { assertNotNull(product); PersistableShoppingCartItem cartItem = new PersistableShoppingCartItem(); - cartItem.setProduct(product.getId()); + cartItem.setProduct(product.getSku()); cartItem.setQuantity(1); final HttpEntity cartEntity = new HttpEntity<>(cartItem, getHeader()); diff --git a/sm-shop/src/test/java/com/salesmanager/test/shop/integration/cart/ShoppingCartAPIIntegrationTest.java b/sm-shop/src/test/java/com/salesmanager/test/shop/integration/cart/ShoppingCartAPIIntegrationTest.java index e2ed6b5cc8..7773f18630 100755 --- a/sm-shop/src/test/java/com/salesmanager/test/shop/integration/cart/ShoppingCartAPIIntegrationTest.java +++ b/sm-shop/src/test/java/com/salesmanager/test/shop/integration/cart/ShoppingCartAPIIntegrationTest.java @@ -42,7 +42,7 @@ public class ShoppingCartAPIIntegrationTest extends ServicesTestSupport { /** - * Add an Item & Create cart, whould give HTTP 201 & 1 qty + * Add an Item & Create cart, would give HTTP 201 & 1 qty * * @throws Exception */ @@ -55,7 +55,7 @@ public void addToCart() throws Exception { data.getProducts().add(product); PersistableShoppingCartItem cartItem = new PersistableShoppingCartItem(); - cartItem.setProduct(product.getId()); + cartItem.setProduct(product.getSku()); cartItem.setQuantity(1); final HttpEntity cartEntity = new HttpEntity<>(cartItem, getHeader()); @@ -83,7 +83,7 @@ public void addSecondToCart() throws Exception { data.getProducts().add(product); PersistableShoppingCartItem cartItem = new PersistableShoppingCartItem(); - cartItem.setProduct(product.getId()); + cartItem.setProduct(product.getSku()); cartItem.setQuantity(1); final HttpEntity cartEntity = new HttpEntity<>(cartItem, getHeader()); @@ -111,7 +111,7 @@ public void addToWrongToCartId() throws Exception { data.getProducts().add(product); PersistableShoppingCartItem cartItem = new PersistableShoppingCartItem(); - cartItem.setProduct(product.getId()); + cartItem.setProduct(product.getSku()); cartItem.setQuantity(1); final HttpEntity cartEntity = new HttpEntity<>(cartItem, getHeader()); @@ -122,8 +122,10 @@ public void addToWrongToCartId() throws Exception { assertNotNull(response); assertThat(response.getStatusCode(), is(NOT_FOUND)); + data.getProducts().remove(product); } + /** * Update cart items with qty 2 (1) on existing items & adding new item with qty 1 which gives result 2x2+1 = 5 * @@ -134,18 +136,15 @@ public void addToWrongToCartId() throws Exception { public void updateMultiWCartId() throws Exception { PersistableShoppingCartItem cartItem1 = new PersistableShoppingCartItem(); - cartItem1.setProduct(data.getProducts().get(0).getId()); + cartItem1.setProduct(data.getProducts().get(0).getSku()); cartItem1.setQuantity(2); PersistableShoppingCartItem cartItem2 = new PersistableShoppingCartItem(); - cartItem2.setProduct(data.getProducts().get(1).getId()); + cartItem2.setProduct(data.getProducts().get(1).getSku()); cartItem2.setQuantity(2); - PersistableShoppingCartItem cartItem3 = new PersistableShoppingCartItem(); - cartItem3.setProduct(data.getProducts().get(2).getId()); - cartItem3.setQuantity(1); - PersistableShoppingCartItem[] productsQtyUpdates = {cartItem1, cartItem2, cartItem3}; + PersistableShoppingCartItem[] productsQtyUpdates = {cartItem1, cartItem2}; final HttpEntity cartEntity = new HttpEntity<>(productsQtyUpdates, getHeader()); @@ -157,7 +156,7 @@ public void updateMultiWCartId() throws Exception { assertNotNull(response); assertThat(response.getStatusCode(), is(CREATED)); - assertEquals(5, response.getBody().getQuantity()); + assertEquals(4, response.getBody().getQuantity()); } /** @@ -170,7 +169,7 @@ public void updateMultiWCartId() throws Exception { public void updateMultiWZeroOnOneProd() throws Exception { PersistableShoppingCartItem cartItem1 = new PersistableShoppingCartItem(); - cartItem1.setProduct(data.getProducts().get(0).getId()); + cartItem1.setProduct(data.getProducts().get(0).getSku()); cartItem1.setQuantity(0); PersistableShoppingCartItem[] productsQtyUpdates = {cartItem1}; @@ -185,7 +184,7 @@ public void updateMultiWZeroOnOneProd() throws Exception { assertNotNull(response); assertThat(response.getStatusCode(), is(CREATED)); - assertEquals(3, response.getBody().getQuantity()); + assertEquals(2, response.getBody().getQuantity()); } /** @@ -218,14 +217,13 @@ public void deleteCartItem() throws Exception { public void deleteCartItemWithBody() throws Exception { final ResponseEntity response = - testRestTemplate.exchange(String.format("/api/v1/cart/" + data.getCartId() + "/product/" + String.valueOf(data.getProducts().get(1).getId()) + "?body=true"), + testRestTemplate.exchange(String.format("/api/v1/cart/" + data.getCartId() + "/product/" + String.valueOf(data.getProducts().get(1).getSku()) + "?body=true"), HttpMethod.DELETE, null, ReadableShoppingCart.class); assertNotNull(response); assertThat(response.getStatusCode(), is(OK)); - assertEquals(1, response.getBody().getQuantity()); } } From 0aa308ac062de1d712eeb1bfeed005fd2b5436ef Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Tue, 7 Jun 2022 22:05:17 -0400 Subject: [PATCH 04/15] add to cart refactoring --- .../core/business/exception/ServiceException.java | 2 +- .../core/business/utils/ProductPriceUtils.java | 14 ++++++++++---- .../shop/store/api/v1/product/ProductPriceApi.java | 2 +- .../store/api/v1/user/ResetUserPasswordApi.java | 4 ++-- .../facade/ShoppingCartFacadeImpl.java | 4 ++-- .../facade/product/ProductInventoryFacadeImpl.java | 11 +++++++++++ 6 files changed, 27 insertions(+), 10 deletions(-) diff --git a/sm-core-model/src/main/java/com/salesmanager/core/business/exception/ServiceException.java b/sm-core-model/src/main/java/com/salesmanager/core/business/exception/ServiceException.java index 388d4991e5..2452c45c5e 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/business/exception/ServiceException.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/business/exception/ServiceException.java @@ -9,7 +9,7 @@ public class ServiceException extends Exception { private int exceptionType = 0;//regular error - + public final static int EXCEPTION_ERROR = 500; public final static int EXCEPTION_VALIDATION = 99; public final static int EXCEPTION_PAYMENT_DECLINED = 100; diff --git a/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java b/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java index d4ce0d4489..82c346fb0b 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/utils/ProductPriceUtils.java @@ -21,6 +21,7 @@ import org.springframework.util.CollectionUtils; import com.salesmanager.core.business.constants.Constants; +import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; @@ -87,7 +88,7 @@ public BigDecimal getPrice(MerchantStore store, Product product, Locale locale) * @return FinalPrice */ //Pricer - public FinalPrice getFinalProductPrice(Product product, List attributes) { + public FinalPrice getFinalProductPrice(Product product, List attributes) throws ServiceException { FinalPrice finalPrice = calculateFinalPrice(product); @@ -136,7 +137,7 @@ public FinalPrice getFinalProductPrice(Product product, List a * @return */ //Pricer - public FinalPrice getFinalPrice(Product product) { + public FinalPrice getFinalPrice(Product product) throws ServiceException { FinalPrice finalPrice = calculateFinalPrice(product); @@ -165,7 +166,7 @@ public FinalPrice getFinalPrice(Product product) { } } - finalPrice.setStringPrice(this.getStringAmount(finalPrice.getFinalPrice())); + finalPrice.setStringPrice(getStringAmount(finalPrice.getFinalPrice())); return finalPrice; } @@ -498,7 +499,7 @@ private boolean matchPositiveInteger(String amount) { return matcher.matches(); } - private FinalPrice calculateFinalPrice(Product product) { + private FinalPrice calculateFinalPrice(Product product) throws ServiceException { FinalPrice finalPrice = null; List otherPrices = null; @@ -539,6 +540,7 @@ private FinalPrice calculateFinalPrice(Product product) { } } } + if(finalPrice!=null) { @@ -549,6 +551,10 @@ private FinalPrice calculateFinalPrice(Product product) { } } + if(finalPrice == null) { + throw new ServiceException(ServiceException.EXCEPTION_ERROR, "No inventory available to calculate the price. Availability should contain at least a region set to *"); + } + return finalPrice; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductPriceApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductPriceApi.java index 522c31c381..642076c48d 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductPriceApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductPriceApi.java @@ -27,7 +27,7 @@ @Controller @RequestMapping("/api/v1") -@Api(tags = { "Product Product price api" }) +@Api(tags = { "Product price api" }) @SwaggerDefinition(tags = { @Tag(name = "Product price management", description = "Edit price and discount") }) public class ProductPriceApi { diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/ResetUserPasswordApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/ResetUserPasswordApi.java index decff4b47a..4f57e6ff83 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/ResetUserPasswordApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/user/ResetUserPasswordApi.java @@ -35,7 +35,7 @@ @RestController @RequestMapping(value = "/api/v1") -@Api(tags = { "User password reset resource (Customer password reset Api)" }) +@Api(tags = { "User password reset resource (User password reset Api)" }) @SwaggerDefinition(tags = { @Tag(name = "User password reset resource", description = "User password reset") }) public class ResetUserPasswordApi { @@ -79,7 +79,7 @@ public void passwordResetRequest( */ @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/user/{store}/reset/{token}" }, produces = MediaType.APPLICATION_JSON_VALUE) - @ApiOperation(httpMethod = "GET", value = "Validate customer password reset token", notes = "", response = Void.class) + @ApiOperation(httpMethod = "GET", value = "Validate user password reset token", notes = "", response = Void.class) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) public void passwordResetVerify(@PathVariable String store, @PathVariable String token, diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java index 391f122564..2958a33783 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/shoppingCart/facade/ShoppingCartFacadeImpl.java @@ -263,7 +263,6 @@ private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem // language // from api // request - if (product == null) { throw new ResourceNotFoundException( "Product with sku " + shoppingCartItem.getProduct() + " does not exist"); @@ -295,6 +294,7 @@ private com.salesmanager.core.model.shoppingcart.ShoppingCartItem createCartItem "Item with id " + product.getId() + " is not properly configured. It contains no availability"); } + //todo filter sku and store for (ProductAvailability availability : availabilities) { if (availability.getProductQuantity() == null || availability.getProductQuantity().intValue() == 0) { throw new Exception("Product with id " + product.getId() + " is not available"); @@ -768,7 +768,7 @@ public ReadableShoppingCart addToCart(PersistableShoppingCartItem item, Merchant if (e instanceof ResourceNotFoundException) { throw (ResourceNotFoundException) e; } else { - throw new ServiceRuntimeException(e); + throw new ServiceRuntimeException(e.getMessage(),e); } } } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInventoryFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInventoryFacadeImpl.java index 2a3f26135c..24c8ba6472 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInventoryFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInventoryFacadeImpl.java @@ -9,9 +9,11 @@ import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.business.services.catalog.product.availability.ProductAvailabilityService; +import com.salesmanager.core.business.services.catalog.product.instance.ProductInstanceService; import com.salesmanager.core.business.services.merchant.MerchantStoreService; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.mapper.inventory.PersistableInventoryMapper; @@ -38,6 +40,9 @@ public class ProductInventoryFacadeImpl implements ProductInventoryFacade { @Autowired private ProductService productService; + + @Autowired + private ProductInstanceService productInstanceService; @Autowired private MerchantStoreService merchantStoreService; @@ -148,6 +153,12 @@ private ProductAvailability getProductAvailabilityToSave(PersistableInventory in ProductAvailability availability = productInventoryMapper.convert(inventory, store, store.getDefaultLanguage()); availability.setProduct(product); availability.setMerchantStore(store); + if(inventory.getInstance() != null) { + Optional instance = productInstanceService.getById(productId, store); + if(instance.isPresent()) { + availability.setProductInstance(instance.get()); + } + } return availability; } From 9c0cc72d9e571ef1e07d16bab3ccc7c51599fc30 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Sat, 11 Jun 2022 21:21:34 -0400 Subject: [PATCH 05/15] product instance group --- .../product/instance/ProductInstance.java | 7 ++++- .../instance/ProductInstanceGroup.java | 15 ++++++----- .../instance/ProductInstanceImage.java | 6 ++++- .../ProductInstanceGroupServiceImpl.java | 2 +- .../ReadableProductInstanceGroup.java | 1 - .../facade/ProductInstanceGroupFacade.java | 4 +-- .../store/api/exception/RestErrorHandler.java | 14 +++++++--- .../v2/product/ProductInstanceGroupApi.java | 13 +++++---- .../ProductInstanceGroupFacadeImpl.java | 27 +++++++++---------- .../resources/spring/shopizer-controllers.xml | 1 + 10 files changed, 55 insertions(+), 35 deletions(-) diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java index f6018bdab6..c4fc8d0005 100644 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstance.java @@ -44,10 +44,15 @@ public class ProductInstance extends SalesManagerEntity i @Id @Column(name = "PRODUCT_INSTANCE_ID", unique = true, nullable = false) - @TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRODUCT_SEQ_NEXT_VAL") + @TableGenerator(name = "TABLE_GEN", + table = "SM_SEQUENCER", + pkColumnName = "SEQ_NAME", + valueColumnName = "SEQ_COUNT", + pkColumnValue = "PRODUCT_INST_SEQ_NEXT_VAL") @GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN") private Long id; + @Embedded private AuditSection auditSection = new AuditSection(); diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java index 816baa611b..aaadd1ae76 100644 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java @@ -23,17 +23,14 @@ import com.salesmanager.core.model.generic.SalesManagerEntity; import com.salesmanager.core.model.merchant.MerchantStore; - -@Entity -@EntityListeners(value = AuditListener.class) -@Table(name="PRODUCT_INSTANCE_GROUP") /** * Extra properties on a group of instances * @author carlsamson * */ - - +@Entity +@EntityListeners(value = AuditListener.class) +@Table(name="PRODUCT_INSTANCE_GROUP") public class ProductInstanceGroup extends SalesManagerEntity { private static final long serialVersionUID = 1L; @@ -41,7 +38,10 @@ public class ProductInstanceGroup extends SalesManagerEntity images = new ArrayList(); @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH }, mappedBy = "productInstanceGroup") + //@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="productInstanceGroup") private Set productInstances = new HashSet(); @ManyToOne(fetch = FetchType.LAZY) diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceImage.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceImage.java index c1b5bb62ac..6ed53ecb89 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceImage.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceImage.java @@ -33,7 +33,11 @@ public void setProductInstanceGroup(ProductInstanceGroup productInstanceGroup) { @Id @Column(name = "PRODUCT_INST_IMAGE_ID") - @TableGenerator(name = "TABLE_GEN", table = "SM_SEQUENCER", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "PRD_VAR_IMG_SEQ_NEXT_VAL") + @TableGenerator(name = "TABLE_GEN", + table = "SM_SEQUENCER", + pkColumnName = "SEQ_NAME", + valueColumnName = "SEQ_COUNT", + pkColumnValue = "PRD_INST_IMG_SEQ_NEXT_VAL") @GeneratedValue(strategy = GenerationType.TABLE, generator = "TABLE_GEN") private Long id; diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/instance/ProductInstanceGroupServiceImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/instance/ProductInstanceGroupServiceImpl.java index 95df392652..2fceb5deba 100644 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/instance/ProductInstanceGroupServiceImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/instance/ProductInstanceGroupServiceImpl.java @@ -58,7 +58,7 @@ public void saveOrUpdate(ProductInstanceGroup entity) throws ServiceException { if(entity.getId()!=null && entity.getId()>0) { super.update(entity); } else { - super.save(entity); + super.saveAndFlush(entity); } } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instanceGroup/ReadableProductInstanceGroup.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instanceGroup/ReadableProductInstanceGroup.java index d15bd80771..a5e4584cef 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instanceGroup/ReadableProductInstanceGroup.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instanceGroup/ReadableProductInstanceGroup.java @@ -12,7 +12,6 @@ public class ReadableProductInstanceGroup extends ProductInstanceGroup { List images = new ArrayList(); - private List productInstances = new ArrayList(); public List getProductInstances() { return productInstances; diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductInstanceGroupFacade.java b/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductInstanceGroupFacade.java index 764cca8629..abcd411268 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductInstanceGroupFacade.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductInstanceGroupFacade.java @@ -16,9 +16,9 @@ public interface ProductInstanceGroupFacade { void delete(Long productInstance, Long productId, MerchantStore store); ReadableEntityList list(Long productId, MerchantStore store, Language language, int page, int count); - void addImage(MultipartFile image, Long productOptionGroupId, + void addImage(MultipartFile image, Long instanceGroupId, MerchantStore store, Language language); - void removeImage(Long imageId, Long productOptionGroupId, MerchantStore store); + void removeImage(Long imageId, Long instanceGroupId, MerchantStore store); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java index fc6c79aeee..054ea331d0 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/exception/RestErrorHandler.java @@ -3,6 +3,7 @@ import java.util.Objects; import java.util.Optional; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.Ordered; @@ -44,8 +45,12 @@ public class RestErrorHandler { @ResponseStatus(HttpStatus.BAD_REQUEST) public @ResponseBody ErrorEntity handleServiceException(ServiceRuntimeException exception) { log.error(exception.getErrorMessage(), exception); - ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode(), exception.getErrorMessage(), - exception.getLocalizedMessage()); + Throwable rootCause = exception.getCause(); + while (rootCause.getCause() != null && rootCause.getCause() != rootCause) { + rootCause = rootCause.getCause(); + } + ErrorEntity errorEntity = createErrorEntity(exception.getErrorCode()!=null?exception.getErrorCode():"500", exception.getErrorMessage(), + rootCause.getMessage()); return errorEntity; } @@ -97,7 +102,10 @@ private ErrorEntity createErrorEntity(String errorCode, String message, String d Optional.ofNullable(errorCode) .ifPresent(errorEntity::setErrorCode); - String resultMessage = message != null ? message : detailMessage; + String resultMessage = (message != null && detailMessage !=null) ? new StringBuilder().append(message).append(", ").append(detailMessage).toString() : detailMessage; + if(StringUtils.isBlank(resultMessage)) { + resultMessage = message; + } Optional.ofNullable(resultMessage) .ifPresent(errorEntity::setMessage); return errorEntity; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductInstanceGroupApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductInstanceGroupApi.java index 7bdc2ab937..979899600e 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductInstanceGroupApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v2/product/ProductInstanceGroupApi.java @@ -58,7 +58,8 @@ public class ProductInstanceGroupApi { @PostMapping(value = { "/private/product/productInstanceGroup" }) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") }) - public @ResponseBody Entity create(@Valid @RequestBody PersistableProductInstanceGroup instanceGroup, + public @ResponseBody Entity create( + @Valid @RequestBody PersistableProductInstanceGroup instanceGroup, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); @@ -79,7 +80,8 @@ public class ProductInstanceGroupApi { @PutMapping(value = { "/private/product/productInstanceGroup/{id}" }) @ApiOperation(httpMethod = "PUT", value = "Update product instance group", notes = "", produces = "application/json", response = Void.class) public @ResponseBody void update(@PathVariable Long id, - @Valid @RequestBody PersistableProductInstanceGroup instance, @ApiIgnore MerchantStore merchantStore, + @Valid @RequestBody PersistableProductInstanceGroup instance, + @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); @@ -96,7 +98,8 @@ public class ProductInstanceGroupApi { @ResponseStatus(HttpStatus.OK) @GetMapping(value = { "/private/product/productInstanceGroup/{id}" }) @ApiOperation(httpMethod = "GET", value = "Get product instance group", notes = "", produces = "application/json", response = Void.class) - public @ResponseBody ReadableProductInstanceGroup get(@PathVariable Long id, @ApiIgnore MerchantStore merchantStore, + public @ResponseBody ReadableProductInstanceGroup get( + @PathVariable Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); @@ -157,7 +160,7 @@ public class ProductInstanceGroupApi { MediaType.MULTIPART_FORM_DATA_VALUE }, method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) - public void uploadImage(@PathVariable Long id, @RequestParam(value = "file", required = true) MultipartFile file, + public void addImage(@PathVariable Long id, @RequestParam(value = "file", required = true) MultipartFile file, @RequestParam(value = "order", required = false, defaultValue = "0") Integer position, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { @@ -177,7 +180,7 @@ public void uploadImage(@PathVariable Long id, @RequestParam(value = "file", req @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/private/product/productInstanceGroup/{id}/image/{imageId}" }, method = RequestMethod.DELETE) - public void deleteImage(@PathVariable Long id, @PathVariable Long imageId, @ApiIgnore MerchantStore merchantStore, + public void removeImage(@PathVariable Long id, @PathVariable Long imageId, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) { String authenticatedUser = userFacade.authenticatedUser(); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java index eb08cd0cf2..af4609b495 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java @@ -95,9 +95,7 @@ public void update(Long productInstanceGroup, PersistableProductInstanceGroup in @Override public void delete(Long productInstanceGroup, Long productId, MerchantStore store) { - - ProductInstanceGroup group = this.group(productInstanceGroup, store); if(group == null) { @@ -115,8 +113,6 @@ public void delete(Long productInstanceGroup, Long productId, MerchantStore stor instance.setProductInstanceGroup(null); productInstanceService.save(instance); } - - //now delete productInstanceGroupService.delete(group); @@ -133,12 +129,9 @@ public ReadableEntityList list(Long productId, Mer Page groups = productInstanceGroupService.getByProductId(store, productId, language, page, count); - - List readableInstances = groups.stream() .map(rp -> this.readableProductInstanceGroupMapper.convert(rp, store, language)).collect(Collectors.toList()); - return createReadableList(groups, readableInstances); } @@ -154,22 +147,25 @@ private ProductInstanceGroup group(Long productOptionGroupId,MerchantStore store } @Override - public void addImage(MultipartFile image, Long productOptionGroupId, + public void addImage(MultipartFile image, Long instanceGroupId, MerchantStore store, Language language) { - Validate.notNull(productOptionGroupId,"productOptionGroupId must not be null"); + Validate.notNull(instanceGroupId,"productInstanceGroupId must not be null"); Validate.notNull(image,"Image must not be null"); Validate.notNull(store,"MerchantStore must not be null"); //get option group - ProductInstanceGroup group = this.group(productOptionGroupId, store); + ProductInstanceGroup group = this.group(instanceGroupId, store); + ProductInstanceImage instanceImage = new ProductInstanceImage(); try { + String path = new StringBuilder().append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append("group").append(Constants.SLASH).append(instanceGroupId).toString(); - ProductInstanceImage instanceImage = new ProductInstanceImage(); - instanceImage.setProductImage(image.getOriginalFilename()); + + + instanceImage.setProductImage(path + Constants.SLASH + image.getOriginalFilename()); instanceImage.setProductInstanceGroup(group); String imageName = image.getOriginalFilename(); InputStream inputStream = image.getInputStream(); @@ -177,14 +173,17 @@ public void addImage(MultipartFile image, Long productOptionGroupId, cmsContentImage.setFileName(imageName); cmsContentImage.setMimeType(image.getContentType()); cmsContentImage.setFile(inputStream); - cmsContentImage.setPath(Constants.SLASH + store.getCode() + Constants.SLASH + productOptionGroupId); + cmsContentImage.setPath(Constants.SLASH + store.getCode() + Constants.SLASH + instanceGroupId); cmsContentImage.setFileContentType(FileContentType.INSTANCE); contentService.addContentFile(store.getCode(), cmsContentImage); + + productInstanceGroupService.saveOrUpdate(group); + group.getImages().add(instanceImage); - productInstanceGroupService.save(group); + productInstanceGroupService.saveOrUpdate(group); } catch (Exception e) { throw new ServiceRuntimeException("Exception while adding instance group image", e); } diff --git a/sm-shop/src/main/resources/spring/shopizer-controllers.xml b/sm-shop/src/main/resources/spring/shopizer-controllers.xml index a3fb79b73b..b950df2cf6 100755 --- a/sm-shop/src/main/resources/spring/shopizer-controllers.xml +++ b/sm-shop/src/main/resources/spring/shopizer-controllers.xml @@ -38,6 +38,7 @@ image/jpeg image/gif image/png + image/webp From 9df13cdbc4730eb7b4a385a7a8a3268e8c68764d Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Sun, 12 Jun 2022 17:49:21 -0400 Subject: [PATCH 06/15] product instance group image --- .../instance/ProductInstanceGroup.java | 1 - .../product/ProductRepositoryImpl.java | 2 +- .../product/inventory/ReadableInventory.java | 11 +++--- .../ReadableProductInstanceGroupMapper.java | 36 ++++++++++++++----- .../inventory/PersistableInventoryMapper.java | 14 ++++++++ .../inventory/ReadableInventoryMapper.java | 2 ++ .../api/v1/product/ProductInventoryApi.java | 36 +------------------ .../ProductInstanceGroupFacadeImpl.java | 11 +++--- 8 files changed, 55 insertions(+), 58 deletions(-) diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java index aaadd1ae76..b3e400661e 100644 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/instance/ProductInstanceGroup.java @@ -50,7 +50,6 @@ public class ProductInstanceGroup extends SalesManagerEntity images = new ArrayList(); @OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH }, mappedBy = "productInstanceGroup") - //@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="productInstanceGroup") private Set productInstances = new HashSet(); @ManyToOne(fetch = FetchType.LAZY) diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java index 4ade7aed0b..300dd4d212 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java @@ -60,7 +60,7 @@ public Product getProductWithOnlyMerchantStoreById(Long productId) { } catch (NoResultException ignored) { return null; } - } + } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/inventory/ReadableInventory.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/inventory/ReadableInventory.java index 365c7d1392..5ea94ffa82 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/inventory/ReadableInventory.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/inventory/ReadableInventory.java @@ -15,7 +15,7 @@ public class ReadableInventory extends InventoryEntity { private String creationDate; private ReadableMerchantStore store; - private ReadableProductInstance instance; + private String sku; private List prices = new ArrayList(); public ReadableMerchantStore getStore() { @@ -42,12 +42,13 @@ public void setCreationDate(String creationDate) { this.creationDate = creationDate; } - public ReadableProductInstance getInstance() { - return instance; + public String getSku() { + return sku; } - public void setInstance(ReadableProductInstance instance) { - this.instance = instance; + public void setSku(String sku) { + this.sku = sku; } + } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceGroupMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceGroupMapper.java index 1440116f9e..a6017b66ef 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceGroupMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceGroupMapper.java @@ -1,5 +1,10 @@ package com.salesmanager.shop.mapper.catalog.product; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -58,7 +63,14 @@ public ReadableProductInstanceGroup merge(ProductInstanceGroup source, ReadableP //image id should be unique in the list - destination.setImages(source.getImages().stream().map(i -> this.image(i, store, language)).collect(Collectors.toList())); + Map finalList = new HashMap(); + + List originalList = source.getImages().stream() + .map(i -> this.image(finalList, i, store, language)) + .collect(Collectors.toList()); + + + destination.setImages(new ArrayList(finalList.values())); return destination; } @@ -68,15 +80,21 @@ private ReadableProductInstance instance(ProductInstance instance, MerchantStore return readableProductInstanceMapper.convert(instance, store, language); } - private ReadableImage image(ProductInstanceImage img, MerchantStore store, Language language) { - - ReadableImage readable = new ReadableImage(); - readable.setId(img.getId()); - readable.setImageName(img.getProductImage()); - readable.setImageUrl(imageUtils.buildCustomTypeImageUtils(store, img.getProductImage(), FileContentType.INSTANCE)); - //readable.setDefaultImage(false); - + private ReadableImage image(Map finalList , ProductInstanceImage img, MerchantStore store, Language language) { + ReadableImage readable = null; + if(!finalList.containsKey(img.getId())) { + readable = new ReadableImage(); + readable.setId(img.getId()); + readable.setImageName(img.getProductImage()); + readable.setImageUrl(imageUtils.buildCustomTypeImageUtils(store, img.getProductImage(), FileContentType.INSTANCE)); + readable.setDefaultImage(img.isDefaultImage()); + finalList.put(img.getId(), readable); + + } return readable; + } } + + diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java index 62841afc92..4ba0918f80 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java @@ -19,8 +19,10 @@ import com.salesmanager.core.business.constants.Constants; import com.salesmanager.core.business.exception.ConversionException; import com.salesmanager.core.business.exception.ServiceException; +import com.salesmanager.core.business.services.catalog.product.ProductService; import com.salesmanager.core.business.services.catalog.product.instance.ProductInstanceService; import com.salesmanager.core.business.services.reference.language.LanguageService; +import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.catalog.product.price.ProductPrice; @@ -42,6 +44,9 @@ public class PersistableInventoryMapper implements Mapper 0) { + Product product =productService.findOne(source.getId(), store); + if(product == null) { + throw new ResourceNotFoundException("Product with id [" + source.getId() + "] not found for store [" + store.getCode() + "]"); + } + destination.setSku(product.getSku()); + } if (source.getInstance() != null && source.getInstance() > 0) { Optional instance = productInstanceService.getById(source.getInstance(), store); if(instance.get() == null) { throw new ResourceNotFoundException("ProductInstance with id [" + source.getInstance() + "] not found for store [" + store.getCode() + "]"); } + destination.setSku(instance.get().getSku()); destination.setProductInstance(instance.get()); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/ReadableInventoryMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/ReadableInventoryMapper.java index 47d5e4e6c7..8491d73114 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/ReadableInventoryMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/ReadableInventoryMapper.java @@ -84,6 +84,8 @@ public ReadableInventory merge(ProductAvailability source, ReadableInventory des List prices = prices(source, store, language); destination.setPrices(prices); + destination.setSku(source.getSku()); + //not necessary when getting an inventory //if(source.getProductInstance() != null) { // destination.setInstance(readableProductInstanceMapper.convert(source.getProductInstance(), store, language)); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductInventoryApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductInventoryApi.java index 7477df8579..037a12e2eb 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductInventoryApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductInventoryApi.java @@ -104,41 +104,7 @@ public void delete( } - /* - * @ResponseStatus(HttpStatus.OK) - * - * @RequestMapping( value = {"/private/product/{id}/inventory"}, method = - * RequestMethod.GET) - * - * @ApiImplicitParams({ - * - * @ApiImplicitParam(name = "store", dataType = "String", defaultValue = - * "DEFAULT"), - * - * @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) - * public @ResponseBody ReadableEntityList get( - * - * @PathVariable Long id, - * - * @ApiIgnore MerchantStore merchantStore, - * - * @ApiIgnore Language language, - * - * @RequestParam(value = "child", required = false) String child, - * - * @RequestParam(value = "page", required = false, defaultValue="0") Integer - * page, - * - * @RequestParam(value = "count", required = false, defaultValue="10") Integer - * count) { - * - * - * return productInventoryFacade.getInventory(id, merchantStore, child, - * language, page, count); - * - * } - */ - + @ResponseStatus(HttpStatus.OK) @RequestMapping( value = {"/private/product/{id}/inventory/{inventoryId}"}, diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java index af4609b495..e2e7dd4a7d 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductInstanceGroupFacadeImpl.java @@ -161,11 +161,11 @@ public void addImage(MultipartFile image, Long instanceGroupId, try { - String path = new StringBuilder().append(Constants.SLASH).append(store.getCode()).append(Constants.SLASH).append("group").append(Constants.SLASH).append(instanceGroupId).toString(); + String path = new StringBuilder().append("group").append(Constants.SLASH).append(instanceGroupId).toString(); - instanceImage.setProductImage(path + Constants.SLASH + image.getOriginalFilename()); + instanceImage.setProductImage(image.getOriginalFilename()); instanceImage.setProductInstanceGroup(group); String imageName = image.getOriginalFilename(); InputStream inputStream = image.getInputStream(); @@ -173,16 +173,13 @@ public void addImage(MultipartFile image, Long instanceGroupId, cmsContentImage.setFileName(imageName); cmsContentImage.setMimeType(image.getContentType()); cmsContentImage.setFile(inputStream); - cmsContentImage.setPath(Constants.SLASH + store.getCode() + Constants.SLASH + instanceGroupId); + cmsContentImage.setPath(path); cmsContentImage.setFileContentType(FileContentType.INSTANCE); contentService.addContentFile(store.getCode(), cmsContentImage); - - productInstanceGroupService.saveOrUpdate(group); - + group.getImages().add(instanceImage); - productInstanceGroupService.saveOrUpdate(group); } catch (Exception e) { throw new ServiceRuntimeException("Exception while adding instance group image", e); From 8b6f2d3578cab99995f0bf0320bf1857a90d2253 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Mon, 13 Jun 2022 20:29:20 -0400 Subject: [PATCH 07/15] Upgrade version 3.2.0 --- pom.xml | 11 ++++---- sm-core-model/pom.xml | 2 +- sm-core-modules/pom.xml | 2 +- sm-core/pom.xml | 2 +- sm-core/test | 0 sm-core/test.txt | 0 sm-shop-model/pom.xml | 2 +- sm-shop/pom.xml | 2 +- .../v1/customer/AuthenticateCustomerApi.java | 27 ------------------- 9 files changed, 10 insertions(+), 38 deletions(-) delete mode 100644 sm-core/test delete mode 100644 sm-core/test.txt diff --git a/pom.xml b/pom.xml index 512343ce2f..9d413d7266 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,7 @@ com.shopizer shopizer pom - 3.0.2 + 3.2.0 shopizer http://ww.shopizer.com @@ -97,22 +97,22 @@ com.shopizer sm-core - 3.0.2 + 3.2.0 com.shopizer sm-core-model - 3.0.2 + 3.2.0 com.shopizer sm-core-modules - 3.0.2 + 3.2.0 com.shopizer sm-shop-model - 3.0.2 + 3.2.0 @@ -181,7 +181,6 @@ ${shopizer.search.version} - mysql mysql-connector-java diff --git a/sm-core-model/pom.xml b/sm-core-model/pom.xml index b6b0a6f0a5..2c9db8cd72 100755 --- a/sm-core-model/pom.xml +++ b/sm-core-model/pom.xml @@ -5,7 +5,7 @@ com.shopizer shopizer - 3.0.2 + 3.2.0 diff --git a/sm-core-modules/pom.xml b/sm-core-modules/pom.xml index 9665a1e2a6..51107aad10 100755 --- a/sm-core-modules/pom.xml +++ b/sm-core-modules/pom.xml @@ -8,7 +8,7 @@ com.shopizer shopizer - 3.0.2 + 3.2.0 diff --git a/sm-core/pom.xml b/sm-core/pom.xml index 5e734f4def..7c03cc8c3b 100755 --- a/sm-core/pom.xml +++ b/sm-core/pom.xml @@ -7,7 +7,7 @@ com.shopizer shopizer - 3.0.2 + 3.2.0 sm-core diff --git a/sm-core/test b/sm-core/test deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/sm-core/test.txt b/sm-core/test.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/sm-shop-model/pom.xml b/sm-shop-model/pom.xml index 54ca1eabe8..7bc79320d2 100755 --- a/sm-shop-model/pom.xml +++ b/sm-shop-model/pom.xml @@ -5,7 +5,7 @@ com.shopizer shopizer - 3.0.2 + 3.2.0 sm-shop-model diff --git a/sm-shop/pom.xml b/sm-shop/pom.xml index b35aea753d..a41fb71c71 100644 --- a/sm-shop/pom.xml +++ b/sm-shop/pom.xml @@ -8,7 +8,7 @@ com.shopizer shopizer - 3.0.2 + 3.2.0 sm-shop diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/customer/AuthenticateCustomerApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/customer/AuthenticateCustomerApi.java index 0ec55859e5..42cb2f5259 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/customer/AuthenticateCustomerApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/customer/AuthenticateCustomerApi.java @@ -210,33 +210,6 @@ public ResponseEntity refreshToken(HttpServletRequest request) { } } - @RequestMapping(value = "/private/customer/password", method = RequestMethod.PUT, produces ={ "application/json" }) - @ApiOperation(httpMethod = "PUT", value = "Change customer password", notes = "Change password request object is {\"username\":\"test@email.com\"}",response = ResponseEntity.class) - public ResponseEntity setPassword( - @RequestBody @Valid AuthenticationRequest authenticationRequest, - @ApiIgnore MerchantStore merchantStore, - @ApiIgnore Language language) { - - - String authenticatedUser = userFacade.authenticatedUser(); - if (authenticatedUser == null) { - throw new UnauthorizedException(); - } - - userFacade.authorizedGroup(authenticatedUser, Stream.of(Constants.GROUP_SUPERADMIN, Constants.GROUP_ADMIN, Constants.GROUP_ADMIN_RETAIL).collect(Collectors.toList())); - - - Customer customer = customerFacade.getCustomerByUserName(authenticationRequest.getUsername(), merchantStore); - - if(customer == null){ - return ResponseEntity.notFound().build(); - } - - - customerFacade.changePassword(customer, authenticationRequest.getPassword()); - return ResponseEntity.ok(Void.class); - - } @RequestMapping(value = "/auth/customer/password", method = RequestMethod.POST, produces ={ "application/json" }) From f202440a262d99e5a297647dbfaec4587f45dc56 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Mon, 13 Jun 2022 20:38:25 -0400 Subject: [PATCH 08/15] upgrade spring boot 2.5.12 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 9d413d7266..65a6eeb122 100644 --- a/pom.xml +++ b/pom.xml @@ -22,7 +22,7 @@ org.springframework.boot spring-boot-starter-parent - 2.5.5 + 2.5.12 From a4b7518e16fe70d33b995843f06649fadb386de3 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Tue, 14 Jun 2022 20:18:50 -0400 Subject: [PATCH 09/15] ProductInstance to support single variant --- ...er.java => IndexProductEventListener.java} | 4 ++-- .../events/products/PublishProductAspect.java | 1 + .../instance/PersistableProductInstance.java | 1 - .../PersistableProductInstanceMapper.java | 23 +++++++++++++++---- .../ReadableProductInstanceMapper.java | 5 ++-- 5 files changed, 24 insertions(+), 10 deletions(-) rename sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/{ProductCreationEventListener.java => IndexProductEventListener.java} (69%) diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/IndexProductEventListener.java similarity index 69% rename from sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java rename to sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/IndexProductEventListener.java index c9105cdacf..4524f98bea 100644 --- a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/ProductCreationEventListener.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/IndexProductEventListener.java @@ -4,12 +4,12 @@ import org.springframework.stereotype.Component; /** - * Index product + * Index product in opensearch if it is confugured to do so ! * @author carlsamson * */ @Component -public class ProductCreationEventListener implements ApplicationListener { +public class IndexProductEventListener implements ApplicationListener { @Override public void onApplicationEvent(ProductEvent event) { diff --git a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java index 60b89a9485..fdce19a960 100644 --- a/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/configuration/events/products/PublishProductAspect.java @@ -20,6 +20,7 @@ public class PublishProductAspect { private ApplicationEventPublisher eventPublisher; + @Autowired public void setEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instance/PersistableProductInstance.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instance/PersistableProductInstance.java index 35e2131d2b..52d3fd64be 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instance/PersistableProductInstance.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/product/instance/PersistableProductInstance.java @@ -9,7 +9,6 @@ public class PersistableProductInstance extends ProductInstance { @NotNull private Long variant; - @NotNull private Long variantValue; public Long getVariant() { diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java index 13dcf0a31f..f9bcc5b5bb 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/PersistableProductInstanceMapper.java @@ -46,21 +46,34 @@ public ProductInstance merge(PersistableProductInstance source, ProductInstance Long productVariantValue = source.getVariantValue(); Optional variant = productVariationService.getById(store, productVariant); - Optional variantValue = productVariationService.getById(store, productVariantValue); + Optional variantValue = null; + if(productVariantValue != null) { + variantValue = productVariationService.getById(store, productVariantValue); + if(variantValue.isEmpty()) { + throw new ResourceNotFoundException("ProductVariant [" + productVariantValue + "] + not found for store [" + store.getCode() + "]"); + } + + } + if(variant.isEmpty()) { throw new ResourceNotFoundException("ProductVariant [" + productVariant + "] + not found for store [" + store.getCode() + "]"); } destination.setVariant(variant.get()); + - if(variantValue.isEmpty()) { - throw new ResourceNotFoundException("ProductVariant [" + productVariantValue + "] + not found for store [" + store.getCode() + "]"); + if(productVariantValue != null) { + destination.setVariantValue(variantValue.get()); } - destination.setVariantValue(variantValue.get()); + StringBuilder instanceCode = new StringBuilder(); + instanceCode.append(variant.get().getCode()); + if(productVariantValue != null && variantValue.get()!=null) { + instanceCode.append(":").append(variantValue.get().getCode()); + } - destination.setCode(variant.get().getCode() + ":" + variantValue.get().getCode()); + destination.setCode(instanceCode.toString()); destination.setAvailable(source.isAvailable()); destination.setDefaultSelection(source.isDefaultSelection()); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceMapper.java index b144998f1b..c8b7e808ed 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/product/ReadableProductInstanceMapper.java @@ -15,7 +15,6 @@ import org.springframework.stereotype.Component; import com.salesmanager.core.model.catalog.product.Product; -import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.catalog.product.instance.ProductInstanceImage; import com.salesmanager.core.model.content.FileContentType; @@ -83,7 +82,9 @@ public ReadableProductInstance merge(ProductInstance source, ReadableProductInst //destination.setStore(null); destination.setStore(store.getCode()); destination.setVariant(readableProductVariationMapper.convert(source.getVariant(), store, language)); - destination.setVariantValue(readableProductVariationMapper.convert(source.getVariantValue(), store, language)); + if(source.getVariantValue() != null) { + destination.setVariantValue(readableProductVariationMapper.convert(source.getVariantValue(), store, language)); + } if(source.getProductInstanceGroup() != null) { Set nameSet = new HashSet<>(); From 82c005d80f28d10620c9448dd7fa480afc80d87a Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Wed, 15 Jun 2022 21:29:24 -0400 Subject: [PATCH 10/15] Readable shopping cart --- .../ReadableShoppingCartItem.java | 18 +++++++ .../cart/ReadableShoppingCartMapper.java | 53 ++++++++++++++++++- .../shop/store/api/v1/search/SearchApi.java | 6 +-- .../search/facade/SearchFacadeImpl.java | 22 ++++++-- 4 files changed, 88 insertions(+), 11 deletions(-) diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java index d7f061940c..2e4b508d9a 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/shoppingcart/ReadableShoppingCartItem.java @@ -6,6 +6,7 @@ import java.util.List; import com.salesmanager.shop.model.catalog.product.ReadableMinimalProduct; +import com.salesmanager.shop.model.catalog.product.variation.ReadableProductVariation; /** * compatible with v1 version @@ -22,6 +23,10 @@ public class ReadableShoppingCartItem extends ReadableMinimalProduct implements private String displaySubTotal; private List cartItemattributes = new ArrayList(); + private ReadableProductVariation variant = null; + private ReadableProductVariation variantValue = null; + + public BigDecimal getSubTotal() { return subTotal; @@ -41,6 +46,19 @@ public List getCartItemattributes() { public void setCartItemattributes(List cartItemattributes) { this.cartItemattributes = cartItemattributes; } + public ReadableProductVariation getVariant() { + return variant; + } + public void setVariant(ReadableProductVariation variant) { + this.variant = variant; + } + public ReadableProductVariation getVariantValue() { + return variantValue; + } + public void setVariantValue(ReadableProductVariation variantValue) { + this.variantValue = variantValue; + } + diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java index 4bb1814569..6591830954 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/cart/ReadableShoppingCartMapper.java @@ -7,8 +7,11 @@ import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Date; +import java.util.HashSet; import java.util.List; +import java.util.Optional; import java.util.Set; +import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -22,12 +25,16 @@ import com.salesmanager.core.business.constants.Constants; import com.salesmanager.core.business.services.catalog.product.PricingService; import com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService; +import com.salesmanager.core.business.services.catalog.product.instance.ProductInstanceService; import com.salesmanager.core.business.services.shoppingcart.ShoppingCartCalculationService; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; import com.salesmanager.core.model.catalog.product.attribute.ProductOption; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; +import com.salesmanager.core.model.catalog.product.instance.ProductInstanceImage; +import com.salesmanager.core.model.content.FileContentType; import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.order.OrderSummary; import com.salesmanager.core.model.order.OrderTotalSummary; @@ -35,6 +42,8 @@ import com.salesmanager.core.model.shoppingcart.ShoppingCart; import com.salesmanager.shop.mapper.Mapper; import com.salesmanager.shop.mapper.catalog.ReadableMinimalProductMapper; +import com.salesmanager.shop.mapper.catalog.ReadableProductVariationMapper; +import com.salesmanager.shop.model.catalog.product.ReadableImage; import com.salesmanager.shop.model.order.total.ReadableOrderTotal; import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart; import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartAttribute; @@ -42,6 +51,7 @@ import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartAttributeOptionValue; import com.salesmanager.shop.model.shoppingcart.ReadableShoppingCartItem; import com.salesmanager.shop.store.api.exception.ConversionRuntimeException; +import com.salesmanager.shop.store.api.exception.ServiceRuntimeException; import com.salesmanager.shop.utils.ImageFilePath; @Component @@ -57,9 +67,15 @@ public class ReadableShoppingCartMapper implements Mapper productInstance = productInstanceService.getById(item.getProductInstance(), store); + if(productInstance.isEmpty()) { + throw new ConversionRuntimeException("An error occured during shopping cart [" + source.getShoppingCartCode() + "] conversion, productInstance [" + item.getProductInstance() + "] not found"); + } + shoppingCartItem.setVariant(readableProductVariationMapper.convert(productInstance.get().getVariant(), store, language)); + if(productInstance.get().getVariantValue() != null) { + shoppingCartItem.setVariantValue(readableProductVariationMapper.convert(productInstance.get().getVariantValue(), store, language)); + } + + if(productInstance.get().getProductInstanceGroup() != null) { + Set nameSet = new HashSet<>(); + List instanceImages = productInstance.get().getProductInstanceGroup().getImages() + .stream().map(i -> this.image(i, store, language)) + .filter(e -> nameSet.add(e.getImageUrl())) + .collect(Collectors.toList()); + shoppingCartItem.setImages(instanceImages); + } + } + + + shoppingCartItem.setPrice(item.getItemPrice()); shoppingCartItem.setFinalPrice(pricingService.getDisplayAmount(item.getItemPrice(), store)); @@ -251,5 +298,7 @@ public ReadableShoppingCart merge(ShoppingCart source, ReadableShoppingCart dest return destination; } + + } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/search/SearchApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/search/SearchApi.java index 67e7b3191c..22fbc2fd1e 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/search/SearchApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/search/SearchApi.java @@ -51,8 +51,7 @@ public class SearchApi { public @ResponseBody SearchProductList search( @RequestBody SearchProductRequest searchRequest, @ApiIgnore MerchantStore merchantStore, - @ApiIgnore Language language, - HttpServletRequest request) { + @ApiIgnore Language language) { return searchFacade.search(merchantStore, language, searchRequest); } @@ -64,8 +63,7 @@ public class SearchApi { public @ResponseBody ValueList autocomplete( @RequestBody SearchProductRequest searchRequest, @ApiIgnore MerchantStore merchantStore, - @ApiIgnore Language language, - HttpServletRequest request) { + @ApiIgnore Language language) { return searchFacade.autocompleteRequest(searchRequest.getQuery(), merchantStore, language); } } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/search/facade/SearchFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/search/facade/SearchFacadeImpl.java index 013b061516..2b669faa7c 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/search/facade/SearchFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/search/facade/SearchFacadeImpl.java @@ -1,5 +1,6 @@ package com.salesmanager.shop.store.controller.search.facade; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @@ -217,11 +218,22 @@ public ValueList autocompleteRequest(String word, MerchantStore store, Language } private SearchKeywords getSearchKeywords(AutoCompleteRequest req, String word) { - try { + //try { LOGGER.debug("Search auto comlete " + word); - return searchService.searchForKeywords(req.getCollectionName(), word, AUTOCOMPLETE_ENTRIES_COUNT); - } catch (ServiceException e) { - throw new ServiceRuntimeException(e); - } + SearchKeywords kw = new SearchKeywords(); + List list = new ArrayList(); + list.add("Product name 1"); + list.add("An item of name 2"); + list.add("Gizmo of name 3"); + list.add("What happened to name 4"); + list.add("Cool product"); + list.add("Product easy to sell"); + list.add("Why no results ?"); + kw.setKeywords(list); + return kw; + //return searchService.searchForKeywords(req.getCollectionName(), word, AUTOCOMPLETE_ENTRIES_COUNT); + //} catch (ServiceException e) { + // throw new ServiceRuntimeException(e); + //} } } From 7c0b94ddae3e32a25b9fa28eea18dcfb16d6f02a Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Mon, 20 Jun 2022 20:36:53 -0400 Subject: [PATCH 11/15] variants grouped with options --- .../catalog/product/attribute/Optionable.java | 11 + .../product/attribute/ProductAttribute.java | 2 +- .../product/variation/ProductVariation.java | 3 +- .../attribute/ReadableProductOption.java | 8 +- .../api/ReadableProductAttributeEntity.java | 6 +- ...y.java => ReadableProductOptionValue.java} | 2 +- .../api/ReadableProductOptionValueFull.java | 2 +- .../api/ReadableProductOptionValueList.java | 6 +- .../product/facade/ProductOptionFacade.java | 6 +- .../ReadableProductAttributeMapper.java | 4 +- .../mapper/catalog/ReadableProductMapper.java | 412 ++++++++++++++---- .../ReadableProductOptionValueMapper.java | 14 +- .../catalog/ReadableProductPopulator.java | 4 +- .../ShoppingCategoryRESTController.java | 139 ------ .../v1/product/ProductAttributeOptionApi.java | 8 +- .../store/facade/StoreFacadeImpl.java | 2 - .../facade/product/ProductFacadeV2Impl.java | 2 +- .../product/ProductOptionFacadeImpl.java | 10 +- 18 files changed, 369 insertions(+), 272 deletions(-) create mode 100644 sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/Optionable.java rename sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/{ReadableProductOptionValueEntity.java => ReadableProductOptionValue.java} (88%) delete mode 100755 sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/category/ShoppingCategoryRESTController.java diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/Optionable.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/Optionable.java new file mode 100644 index 0000000000..f2d19d1aee --- /dev/null +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/Optionable.java @@ -0,0 +1,11 @@ +package com.salesmanager.core.model.catalog.product.attribute; + +public interface Optionable { + + ProductOption getProductOption(); + void setProductOption(ProductOption option); + + ProductOptionValue getProductOptionValue(); + void setProductOptionValue(ProductOptionValue optionValue); + +} diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductAttribute.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductAttribute.java index eee7024dfb..06c72276d5 100755 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductAttribute.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/attribute/ProductAttribute.java @@ -36,7 +36,7 @@ * */ -public class ProductAttribute extends SalesManagerEntity { +public class ProductAttribute extends SalesManagerEntity implements Optionable { private static final long serialVersionUID = 1L; @Id diff --git a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/variation/ProductVariation.java b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/variation/ProductVariation.java index a232286915..52dbad4883 100644 --- a/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/variation/ProductVariation.java +++ b/sm-core-model/src/main/java/com/salesmanager/core/model/catalog/product/variation/ProductVariation.java @@ -15,6 +15,7 @@ import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotEmpty; +import com.salesmanager.core.model.catalog.product.attribute.Optionable; import com.salesmanager.core.model.catalog.product.attribute.ProductOption; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue; import com.salesmanager.core.model.common.audit.AuditListener; @@ -37,7 +38,7 @@ @EntityListeners(value = AuditListener.class) @Table(name = "PRODUCT_VARIATION", uniqueConstraints= @UniqueConstraint(columnNames = {"MERCHANT_ID", "PRODUCT_OPTION_ID", "OPTION_VALUE_ID"})) -public class ProductVariation extends SalesManagerEntity implements Auditable { +public class ProductVariation extends SalesManagerEntity implements Optionable, Auditable { /** * diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java index 58526184f1..7741ee6cf8 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java @@ -3,7 +3,7 @@ import java.util.ArrayList; import java.util.List; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; public class ReadableProductOption extends ProductPropertyOption { @@ -14,7 +14,7 @@ public class ReadableProductOption extends ProductPropertyOption { private String name; private String lang; - private List optionValues = new ArrayList(); + private List optionValues = new ArrayList(); public String getName() { @@ -33,11 +33,11 @@ public void setLang(String lang) { this.lang = lang; } - public List getOptionValues() { + public List getOptionValues() { return optionValues; } - public void setOptionValues(List optionValues) { + public void setOptionValues(List optionValues) { this.optionValues = optionValues; } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductAttributeEntity.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductAttributeEntity.java index 8f34dbaaaf..ed60eff875 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductAttributeEntity.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductAttributeEntity.java @@ -12,7 +12,7 @@ public class ReadableProductAttributeEntity extends ProductAttributeEntity { private String productAttributeUnformattedPrice; private ReadableProductOptionEntity option; - private ReadableProductOptionValueEntity optionValue; + private ReadableProductOptionValue optionValue; public String getProductAttributeWeight() { return productAttributeWeight; } @@ -31,10 +31,10 @@ public ReadableProductOptionEntity getOption() { public void setOption(ReadableProductOptionEntity option) { this.option = option; } - public ReadableProductOptionValueEntity getOptionValue() { + public ReadableProductOptionValue getOptionValue() { return optionValue; } - public void setOptionValue(ReadableProductOptionValueEntity optionValue) { + public void setOptionValue(ReadableProductOptionValue optionValue) { this.optionValue = optionValue; } public String getProductAttributeUnformattedPrice() { diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueEntity.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValue.java similarity index 88% rename from sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueEntity.java rename to sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValue.java index 47324ca869..9434d0ff05 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueEntity.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValue.java @@ -4,7 +4,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription; -public class ReadableProductOptionValueEntity extends ProductOptionValueEntity { +public class ReadableProductOptionValue extends ProductOptionValueEntity { /** * diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueFull.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueFull.java index 6136188be4..a1fafb3218 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueFull.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueFull.java @@ -5,7 +5,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription; -public class ReadableProductOptionValueFull extends ReadableProductOptionValueEntity { +public class ReadableProductOptionValueFull extends ReadableProductOptionValue { /** * diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueList.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueList.java index 8adaa4eca0..49a47b814a 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueList.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/api/ReadableProductOptionValueList.java @@ -11,11 +11,11 @@ public class ReadableProductOptionValueList extends ReadableList { * */ private static final long serialVersionUID = 1L; - List optionValues = new ArrayList(); - public List getOptionValues() { + List optionValues = new ArrayList(); + public List getOptionValues() { return optionValues; } - public void setOptionValues(List optionValues) { + public void setOptionValues(List optionValues) { this.optionValues = optionValues; } diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionFacade.java b/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionFacade.java index eb49016a1a..c6e9031029 100644 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionFacade.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/store/controller/product/facade/ProductOptionFacade.java @@ -13,7 +13,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeList; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionList; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueList; import com.salesmanager.shop.model.entity.CodeEntity; @@ -25,11 +25,11 @@ public interface ProductOptionFacade { ReadableProductOptionEntity getOption(Long optionId, MerchantStore store, Language language); - ReadableProductOptionValueEntity getOptionValue(Long optionValueId, MerchantStore store, Language language); + ReadableProductOptionValue getOptionValue(Long optionValueId, MerchantStore store, Language language); ReadableProductOptionEntity saveOption(PersistableProductOptionEntity option, MerchantStore store, Language language); - ReadableProductOptionValueEntity saveOptionValue(PersistableProductOptionValue optionValue, MerchantStore store, Language language); + ReadableProductOptionValue saveOptionValue(PersistableProductOptionValue optionValue, MerchantStore store, Language language); List createAttributes(List attributes, Long productId, MerchantStore store); void updateAttributes(List attributes, Long productId, MerchantStore store); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductAttributeMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductAttributeMapper.java index d7d89bf602..64fa2ab02f 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductAttributeMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductAttributeMapper.java @@ -11,7 +11,7 @@ import com.salesmanager.shop.mapper.Mapper; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionEntity; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.store.api.exception.ConversionRuntimeException; @Component @@ -64,7 +64,7 @@ public ReadableProductAttributeEntity merge(ProductAttribute source, ReadablePro } if(source.getProductOptionValue()!=null) { - ReadableProductOptionValueEntity optionValue = readableProductOptionValueMapper.convert(source.getProductOptionValue(), store, language); + ReadableProductOptionValue optionValue = readableProductOptionValueMapper.convert(source.getProductOptionValue(), store, language); attr.setOptionValue(optionValue); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java index 841d33c49b..483e8a3e10 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java @@ -2,9 +2,9 @@ import java.util.ArrayList; import java.util.List; -import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.TreeMap; import java.util.stream.Collectors; import org.apache.commons.collections4.CollectionUtils; @@ -14,16 +14,20 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; +import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.catalog.product.PricingService; import com.salesmanager.core.model.catalog.category.Category; import com.salesmanager.core.model.catalog.product.Product; +import com.salesmanager.core.model.catalog.product.attribute.Optionable; import com.salesmanager.core.model.catalog.product.attribute.ProductAttribute; +import com.salesmanager.core.model.catalog.product.attribute.ProductOption; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue; import com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; import com.salesmanager.core.model.catalog.product.description.ProductDescription; import com.salesmanager.core.model.catalog.product.image.ProductImage; +import com.salesmanager.core.model.catalog.product.instance.ProductInstance; import com.salesmanager.core.model.catalog.product.price.FinalPrice; import com.salesmanager.core.model.catalog.product.price.ProductPrice; import com.salesmanager.core.model.catalog.product.price.ProductPriceDescription; @@ -42,7 +46,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductOption; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductProperty; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductPropertyValue; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.product.instance.ReadableProductInstance; import com.salesmanager.shop.model.catalog.product.type.ReadableProductType; import com.salesmanager.shop.model.references.DimensionUnitOfMeasure; @@ -70,7 +74,7 @@ public class ReadableProductMapper implements Mapper { @Autowired private ReadableProductTypeMapper readableProductTypeMapper; - + @Autowired private ReadableProductInstanceMapper readableProductInstanceMapper; @@ -92,6 +96,10 @@ public ReadableProduct merge(Product source, ReadableProduct destination, Mercha Validate.notNull(source, "Product cannot be null"); Validate.notNull(destination, "Product destination cannot be null"); + // read only product values + // will contain options + TreeMap selectableOptions = new TreeMap(); + destination.setSku(source.getSku()); destination.setRefSku(source.getRefSku()); destination.setId(source.getId()); @@ -106,133 +114,212 @@ public ReadableProduct merge(Product source, ReadableProduct destination, Mercha break; } } + } + destination.setId(source.getId()); + destination.setAvailable(source.isAvailable()); + destination.setProductShipeable(source.isProductShipeable()); - destination.setId(source.getId()); - destination.setAvailable(source.isAvailable()); - destination.setProductShipeable(source.isProductShipeable()); - - ProductSpecification specifications = new ProductSpecification(); - specifications.setHeight(source.getProductHeight()); - specifications.setLength(source.getProductLength()); - specifications.setWeight(source.getProductWeight()); - specifications.setWidth(source.getProductWidth()); - destination.setProductSpecifications(specifications); - - destination.setPreOrder(source.isPreOrder()); - destination.setRefSku(source.getRefSku()); - destination.setSortOrder(source.getSortOrder()); - - if (source.getType() != null) { - ReadableProductType readableType = readableProductTypeMapper.convert(source.getType(), store, language); - destination.setType(readableType); - } + destination.setPreOrder(source.isPreOrder()); + destination.setRefSku(source.getRefSku()); + destination.setSortOrder(source.getSortOrder()); - if (source.getDateAvailable() != null) { - destination.setDateAvailable(DateUtil.formatDate(source.getDateAvailable())); - } + if (source.getType() != null) { + ReadableProductType readableType = readableProductTypeMapper.convert(source.getType(), store, language); + destination.setType(readableType); + } - if (source.getAuditSection() != null) { - destination.setCreationDate(DateUtil.formatDate(source.getAuditSection().getDateCreated())); - } + if (source.getDateAvailable() != null) { + destination.setDateAvailable(DateUtil.formatDate(source.getDateAvailable())); + } - destination.setProductVirtual(source.getProductVirtual()); + if (source.getAuditSection() != null) { + destination.setCreationDate(DateUtil.formatDate(source.getAuditSection().getDateCreated())); + } - if (source.getProductReviewCount() != null) { - destination.setRatingCount(source.getProductReviewCount().intValue()); - } + destination.setProductVirtual(source.getProductVirtual()); - if (source.getManufacturer() != null) { - ReadableManufacturer manufacturer = readableManufacturerMapper.convert(source.getManufacturer(), store, - language); - destination.setManufacturer(manufacturer); - } + if (source.getProductReviewCount() != null) { + destination.setRatingCount(source.getProductReviewCount().intValue()); + } - // images - Set images = source.getImages(); - if (CollectionUtils.isNotEmpty(images)) { + if (source.getManufacturer() != null) { + ReadableManufacturer manufacturer = readableManufacturerMapper.convert(source.getManufacturer(), store, + language); + destination.setManufacturer(manufacturer); + } - List imageList = images.stream().map(i -> this.convertImage(source, i, store)) - .collect(Collectors.toList()); - destination.setImages(imageList); - } + // images + Set images = source.getImages(); + if (CollectionUtils.isNotEmpty(images)) { - // read only product values - if (!CollectionUtils.isEmpty(source.getAttributes())) { + List imageList = images.stream().map(i -> this.convertImage(source, i, store)) + .collect(Collectors.toList()); + destination.setImages(imageList); + } - Set attributes = source.getAttributes(); + if (!CollectionUtils.isEmpty(source.getAttributes())) { - // split read only and options - // Map readOnlyAttributes = null; - Map properties = null; - Map selectableOptions = null; + Set attributes = source.getAttributes(); - if (!CollectionUtils.isEmpty(attributes)) { + if (!CollectionUtils.isEmpty(attributes)) { - for (ProductAttribute attribute : attributes) { - ReadableProductOption opt = null; - ReadableProductAttribute attr = null; - ReadableProductProperty property = null; - ReadableProductPropertyValue propertyValue = null; - ReadableProductOptionValueEntity optValue = new ReadableProductOptionValueEntity(); - ReadableProductAttributeValue attrValue = new ReadableProductAttributeValue(); + for (ProductAttribute attribute : attributes) { + ReadableProductOption opt = null; + ReadableProductAttribute attr = null; + ReadableProductProperty property = null; + ReadableProductPropertyValue propertyValue = null; + ReadableProductAttributeValue attrValue = new ReadableProductAttributeValue(); - ProductOptionValue optionValue = attribute.getProductOptionValue(); + ProductOptionValue optionValue = attribute.getProductOptionValue(); - // we need to set readonly attributes only - if (attribute.getAttributeDisplayOnly()) {// read only attribute = property + // we need to set readonly attributes only + if (attribute.getAttributeDisplayOnly()) {// read only attribute = property - property = createProperty(attribute, language); + property = createProperty(attribute, language); - ReadableProductOption readableOption = new ReadableProductOption(); // that is the property - ReadableProductPropertyValue readableOptionValue = new ReadableProductPropertyValue(); + ReadableProductOption readableOption = new ReadableProductOption(); // that is the property + ReadableProductPropertyValue readableOptionValue = new ReadableProductPropertyValue(); - readableOption.setCode(attribute.getProductOption().getCode()); - readableOption.setId(attribute.getProductOption().getId()); + readableOption.setCode(attribute.getProductOption().getCode()); + readableOption.setId(attribute.getProductOption().getId()); - Set podescriptions = attribute.getProductOption() - .getDescriptions(); - if (podescriptions != null && podescriptions.size() > 0) { - for (ProductOptionDescription optionDescription : podescriptions) { - if (optionDescription.getLanguage().getCode().equals(language.getCode())) { - readableOption.setName(optionDescription.getName()); - } + Set podescriptions = attribute.getProductOption().getDescriptions(); + if (podescriptions != null && podescriptions.size() > 0) { + for (ProductOptionDescription optionDescription : podescriptions) { + if (optionDescription.getLanguage().getCode().equals(language.getCode())) { + readableOption.setName(optionDescription.getName()); } } + } - property.setProperty(readableOption); + property.setProperty(readableOption); - Set povdescriptions = attribute.getProductOptionValue() - .getDescriptions(); - readableOptionValue.setId(attribute.getProductOptionValue().getId()); - if (povdescriptions != null && povdescriptions.size() > 0) { - for (ProductOptionValueDescription optionValueDescription : povdescriptions) { - if (optionValueDescription.getLanguage().getCode().equals(language.getCode())) { - readableOptionValue.setName(optionValueDescription.getName()); - } + Set povdescriptions = attribute.getProductOptionValue() + .getDescriptions(); + readableOptionValue.setId(attribute.getProductOptionValue().getId()); + if (povdescriptions != null && povdescriptions.size() > 0) { + for (ProductOptionValueDescription optionValueDescription : povdescriptions) { + if (optionValueDescription.getLanguage().getCode().equals(language.getCode())) { + readableOptionValue.setName(optionValueDescription.getName()); } } + } + + property.setPropertyValue(readableOptionValue); + destination.getProperties().add(property); - property.setPropertyValue(readableOptionValue); + } else {// selectable option - destination.getProperties().add(property); + /** + * Returns a list of ReadableProductOptions + * + * name lang type code List ReadableProductOptionValueEntity name description + * image order default + */ + if (selectableOptions == null) { + selectableOptions = new TreeMap(); + } + opt = selectableOptions.get(attribute.getProductOption().getId()); + if (opt == null) { + opt = createOption(attribute.getProductOption(), language); + } + if (opt != null) { + selectableOptions.put(attribute.getProductOption().getId(), opt); + } + + ReadableProductOptionValue optValue = new ReadableProductOptionValue(); + + optValue.setDefaultValue(attribute.getAttributeDefault()); + // optValue.setId(attribute.getProductOptionValue().getId()); + optValue.setId(attribute.getId()); + optValue.setCode(attribute.getProductOptionValue().getCode()); + + com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription valueDescription = new com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription(); + valueDescription.setLanguage(language.getCode()); + // optValue.setLang(language.getCode()); + if (attribute.getProductAttributePrice() != null + && attribute.getProductAttributePrice().doubleValue() > 0) { + String formatedPrice = null; + try { + formatedPrice = pricingService.getDisplayAmount(attribute.getProductAttributePrice(), + store); + optValue.setPrice(formatedPrice); + } catch (ServiceException e) { + throw new ConversionRuntimeException( + "Error converting product option, an exception occured with pricingService", e); + } + } + + if (!StringUtils.isBlank(attribute.getProductOptionValue().getProductOptionValueImage())) { + optValue.setImage(imageUtils.buildProductPropertyImageUtils(store, + attribute.getProductOptionValue().getProductOptionValueImage())); + } + optValue.setSortOrder(0); + if (attribute.getProductOptionSortOrder() != null) { + optValue.setSortOrder(attribute.getProductOptionSortOrder().intValue()); } - if (selectableOptions != null) { - List options = new ArrayList( - selectableOptions.values()); - destination.setOptions(options); + List podescriptions = optionValue.getDescriptionsSettoList(); + ProductOptionValueDescription podescription = null; + if (podescriptions != null && podescriptions.size() > 0) { + podescription = podescriptions.get(0); + if (podescriptions.size() > 1) { + for (ProductOptionValueDescription optionValueDescription : podescriptions) { + if (optionValueDescription.getLanguage().getId().intValue() == language.getId() + .intValue()) { + podescription = optionValueDescription; + break; + } + } + } } + valueDescription.setName(podescription.getName()); + valueDescription.setDescription(podescription.getDescription()); + optValue.setDescription(valueDescription); + if (opt != null) { + opt.getOptionValues().add(optValue); + } } + } } + } - - //variants - if(!CollectionUtils.isEmpty(source.getInstances())) { - List instances = source.getInstances().stream().map(i -> readableProductInstanceMapper.convert(i, store, language)).collect(Collectors.toList()); + + // variants + if (!CollectionUtils.isEmpty(source.getInstances())) + + { + List instances = source.getInstances().stream() + .map(i -> readableProductInstanceMapper.convert(i, store, language)).collect(Collectors.toList()); destination.setVariants(instances); + + /** + * variants options list variation color + */ + + /** + * Returns a list of ReadableProductOptions + * + * name lang type code List ReadableProductOptionValueEntity name description + * image order default + */ + + /** + * Create options from instance Create a list of option values + */ + + for (ProductInstance instance : source.getInstances()) { + this.instanceToOption(selectableOptions, instance, store, language); + } + + } + + if (selectableOptions != null) { + List options = new ArrayList(selectableOptions.values()); + destination.setOptions(options); } // availability @@ -432,4 +519,143 @@ private ReadableProductProperty createProperty(ProductAttribute productAttribute } + private Optional optionValue(ProductOptionValue optionValue, MerchantStore store, + Language language) { + + if (optionValue == null) { + return Optional.empty(); + } + + ReadableProductOptionValue optValue = new ReadableProductOptionValue(); + + com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription valueDescription = new com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescription(); + valueDescription.setLanguage(language.getCode()); + + if (!StringUtils.isBlank(optionValue.getProductOptionValueImage())) { + optValue.setImage( + imageUtils.buildProductPropertyImageUtils(store, optionValue.getProductOptionValueImage())); + } + optValue.setSortOrder(0); + + if (optionValue.getProductOptionValueSortOrder() != null) { + optValue.setSortOrder(optionValue.getProductOptionValueSortOrder().intValue()); + } + + optValue.setCode(optionValue.getCode()); + + List podescriptions = optionValue.getDescriptionsSettoList(); + ProductOptionValueDescription podescription = null; + if (podescriptions != null && podescriptions.size() > 0) { + podescription = podescriptions.get(0); + if (podescriptions.size() > 1) { + for (ProductOptionValueDescription optionValueDescription : podescriptions) { + if (optionValueDescription.getLanguage().getId().intValue() == language.getId().intValue()) { + podescription = optionValueDescription; + break; + } + } + } + } + valueDescription.setName(podescription.getName()); + valueDescription.setDescription(podescription.getDescription()); + optValue.setDescription(valueDescription); + + return Optional.of(optValue); + + } + + private void instanceToOption(TreeMap selectableOptions, ProductInstance instance, + MerchantStore store, Language language) { + + + ReadableProductOption option = this.option(selectableOptions, instance.getVariant().getProductOption(), language); + + + // take care of option value + Optional optionOptionValue = this + .optionValue(instance.getVariant().getProductOptionValue(), store, language); + + if (optionOptionValue.isPresent()) { + optionOptionValue.get().setId(instance.getId()); + if (instance.isDefaultSelection()) { + optionOptionValue.get().setDefaultValue(true); + } + addOptionValue(option, optionOptionValue.get()); + + } + + if (instance.getVariantValue() != null) { + ReadableProductOption optionValue = this.option(selectableOptions, instance.getVariantValue().getProductOption(), language); + + // take care of option value + Optional optionValueOptionValue = this + .optionValue(instance.getVariantValue().getProductOptionValue(), store, language); + + + if (optionValueOptionValue.isPresent()) { + optionValueOptionValue.get().setId(instance.getId()); + if (instance.isDefaultSelection()) { + optionValueOptionValue.get().setDefaultValue(true); + } + addOptionValue(optionValue, optionValueOptionValue.get()); + } + + } + + } + + private void addOptionValue(ReadableProductOption option, ReadableProductOptionValue optionValue) { + + ReadableProductOptionValue find = option.getOptionValues().stream() + .filter(optValue -> optValue.getCode()==optionValue.getCode()) + .findAny() + .orElse(null); + + if(find == null) { + option.getOptionValues().add(optionValue); + } + } + + private ReadableProductOption option(TreeMap selectableOptions, ProductOption option, Language language) { + if(selectableOptions.containsKey(option.getId())) { + return selectableOptions.get(option.getId()); + } + + ReadableProductOption readable = this.createOption(option, language); + selectableOptions.put(readable.getId(), readable); + return readable; + } + + private ReadableProductOption createOption(ProductOption opt, Language language) { + + ReadableProductOption option = new ReadableProductOption(); + option.setId(opt.getId());// attribute of the option + option.setType(opt.getProductOptionType()); + option.setCode(opt.getCode()); + List descriptions = opt.getDescriptionsSettoList(); + ProductOptionDescription description = null; + if (descriptions != null && descriptions.size() > 0) { + description = descriptions.get(0); + if (descriptions.size() > 1) { + for (ProductOptionDescription optionDescription : descriptions) { + if (optionDescription.getLanguage().getCode().equals(language.getCode())) { + description = optionDescription; + break; + } + } + } + } + + if (description == null) { + return null; + } + + option.setLang(language.getCode()); + option.setName(description.getName()); + option.setCode(opt.getCode()); + + return option; + + } + } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductOptionValueMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductOptionValueMapper.java index 48f5772483..6cacc78c1d 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductOptionValueMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductOptionValueMapper.java @@ -14,21 +14,21 @@ import com.salesmanager.core.model.merchant.MerchantStore; import com.salesmanager.core.model.reference.language.Language; import com.salesmanager.shop.mapper.Mapper; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueFull; import com.salesmanager.shop.utils.ImageFilePath; @Component -public class ReadableProductOptionValueMapper implements Mapper { +public class ReadableProductOptionValueMapper implements Mapper { @Autowired @Qualifier("img") private ImageFilePath imageUtils; @Override - public ReadableProductOptionValueEntity merge(ProductOptionValue source, ReadableProductOptionValueEntity destination, + public ReadableProductOptionValue merge(ProductOptionValue source, ReadableProductOptionValue destination, MerchantStore store, Language language) { - ReadableProductOptionValueEntity readableProductOptionValue = new ReadableProductOptionValueEntity(); + ReadableProductOptionValue readableProductOptionValue = new ReadableProductOptionValue(); if(language == null) { readableProductOptionValue = new ReadableProductOptionValueFull(); List descriptions = new ArrayList(); @@ -38,7 +38,7 @@ public ReadableProductOptionValueEntity merge(ProductOptionValue source, Readabl } ((ReadableProductOptionValueFull)readableProductOptionValue).setDescriptions(descriptions); } else { - readableProductOptionValue = new ReadableProductOptionValueEntity(); + readableProductOptionValue = new ReadableProductOptionValue(); if(!CollectionUtils.isEmpty(source.getDescriptions())) { for(ProductOptionValueDescription desc : source.getDescriptions()) { if(desc != null && desc.getLanguage()!= null && desc.getLanguage().getId() == language.getId()) { @@ -76,8 +76,8 @@ com.salesmanager.shop.model.catalog.product.attribute.ProductOptionValueDescript @Override -public ReadableProductOptionValueEntity convert(ProductOptionValue source, MerchantStore store, Language language) { - ReadableProductOptionValueEntity destination = new ReadableProductOptionValueEntity(); +public ReadableProductOptionValue convert(ProductOptionValue source, MerchantStore store, Language language) { + ReadableProductOptionValue destination = new ReadableProductOptionValue(); return merge(source, destination, store, language); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/populator/catalog/ReadableProductPopulator.java b/sm-shop/src/main/java/com/salesmanager/shop/populator/catalog/ReadableProductPopulator.java index c35464734a..267c81ebe0 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/populator/catalog/ReadableProductPopulator.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/populator/catalog/ReadableProductPopulator.java @@ -45,7 +45,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductOption; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductProperty; import com.salesmanager.shop.model.catalog.product.attribute.ReadableProductPropertyValue; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.type.ProductTypeDescription; import com.salesmanager.shop.model.catalog.product.type.ReadableProductType; import com.salesmanager.shop.utils.DateUtil; @@ -282,7 +282,7 @@ public ReadableProduct populate(Product source, ReadableProductAttribute attr = null; ReadableProductProperty property = null; ReadableProductPropertyValue propertyValue = null; - ReadableProductOptionValueEntity optValue = new ReadableProductOptionValueEntity(); + ReadableProductOptionValue optValue = new ReadableProductOptionValue(); ReadableProductAttributeValue attrValue = new ReadableProductAttributeValue(); ProductOptionValue optionValue = attribute.getProductOptionValue(); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/category/ShoppingCategoryRESTController.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/category/ShoppingCategoryRESTController.java deleted file mode 100755 index ac0b1402af..0000000000 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v0/category/ShoppingCategoryRESTController.java +++ /dev/null @@ -1,139 +0,0 @@ -package com.salesmanager.shop.store.api.v0.category; - - -import java.util.Map; - -import javax.inject.Inject; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.validation.Valid; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; - -import com.salesmanager.core.business.services.catalog.category.CategoryService; -import com.salesmanager.core.business.services.catalog.product.ProductService; -import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.model.merchant.MerchantStore; -import com.salesmanager.core.model.reference.language.Language; -import com.salesmanager.shop.constants.Constants; -import com.salesmanager.shop.model.catalog.category.PersistableCategory; -import com.salesmanager.shop.model.catalog.category.ReadableCategory; -import com.salesmanager.shop.store.controller.category.facade.CategoryFacade; -import com.salesmanager.shop.utils.LanguageUtils; - -/** - * Rest services for category management - * @author Carl Samson - * - */ -@Controller -@RequestMapping("/services") -public class ShoppingCategoryRESTController { - - - @Inject - private MerchantStoreService merchantStoreService; - - @Inject - private LanguageUtils languageUtils; - - @Inject - private CategoryFacade categoryFacade; - - - - private static final Logger LOGGER = LoggerFactory.getLogger(ShoppingCategoryRESTController.class); - - - - @RequestMapping( value="/public/{store}/category/{id}", method=RequestMethod.GET) - @ResponseBody - public ReadableCategory getCategory(@PathVariable final String store, @PathVariable Long id, HttpServletRequest request, HttpServletResponse response) { - - - try { - - /** default routine **/ - - MerchantStore merchantStore = (MerchantStore)request.getAttribute(Constants.MERCHANT_STORE); - if(merchantStore!=null) { - if(!merchantStore.getCode().equals(store)) { - merchantStore = null; - } - } - - if(merchantStore== null) { - merchantStore = merchantStoreService.getByCode(store); - } - - if(merchantStore==null) { - LOGGER.error("Merchant store is null for code " + store); - response.sendError(503, "Merchant store is null for code " + store); - return null; - } - - - Language language = languageUtils.getRequestLanguage(request, response); - - /** - Language language = merchantStore.getDefaultLanguage(); - - Map langs = languageService.getLanguagesMap(); - - - if(!StringUtils.isBlank(request.getParameter(Constants.LANG))) { - String lang = request.getParameter(Constants.LANG); - if(lang!=null) { - language = langs.get(language); - } - } - - if(language==null) { - language = merchantStore.getDefaultLanguage(); - } - **/ - - - /** end default routine **/ - - - ReadableCategory category = categoryFacade.getById(merchantStore, id, language); - - if(category==null) { - response.sendError(503, "Invalid category id"); - return null; - } - - - return category; - - } catch (Exception e) { - LOGGER.error("Error while saving category",e); - try { - response.sendError(503, "Error while saving category " + e.getMessage()); - } catch (Exception ignore) { - } - return null; - } - } - - - - - - - - - -} diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductAttributeOptionApi.java b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductAttributeOptionApi.java index d171a23d6b..1815ce6049 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductAttributeOptionApi.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/api/v1/product/ProductAttributeOptionApi.java @@ -30,7 +30,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeList; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionList; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueList; import com.salesmanager.shop.model.entity.CodeEntity; import com.salesmanager.shop.model.entity.Entity; @@ -95,7 +95,7 @@ public ResponseEntity optionValueExists(@RequestParam(value = "cod @RequestMapping(value = { "/private/product/option/value" }, method = RequestMethod.POST) @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) - public @ResponseBody ReadableProductOptionValueEntity createOptionValue( + public @ResponseBody ReadableProductOptionValue createOptionValue( @Valid @RequestBody PersistableProductOptionValue optionValue, //@RequestParam(name = "file", required = false) MultipartFile file, @ApiIgnore MerchantStore merchantStore, @@ -103,7 +103,7 @@ public ResponseEntity optionValueExists(@RequestParam(value = "cod HttpServletRequest request, HttpServletResponse response) { - ReadableProductOptionValueEntity entity = productOptionFacade.saveOptionValue( optionValue, + ReadableProductOptionValue entity = productOptionFacade.saveOptionValue( optionValue, merchantStore, language); return entity; @@ -157,7 +157,7 @@ public ReadableProductOptionEntity getOption(@PathVariable Long id, @ApiIgnore M @ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") }) @ResponseBody - public ReadableProductOptionValueEntity getOptionValue(@PathVariable Long id, @ApiIgnore MerchantStore merchantStore, + public ReadableProductOptionValue getOptionValue(@PathVariable Long id, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) { return productOptionFacade.getOptionValue(id, merchantStore, language); diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/store/facade/StoreFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/store/facade/StoreFacadeImpl.java index d7b8763b61..9834139d6a 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/store/facade/StoreFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/store/facade/StoreFacadeImpl.java @@ -23,9 +23,7 @@ import com.salesmanager.core.business.exception.ServiceException; import com.salesmanager.core.business.services.content.ContentService; import com.salesmanager.core.business.services.merchant.MerchantStoreService; -import com.salesmanager.core.business.services.reference.country.CountryService; import com.salesmanager.core.business.services.reference.language.LanguageService; -import com.salesmanager.core.business.services.reference.zone.ZoneService; import com.salesmanager.core.business.services.system.MerchantConfigurationService; import com.salesmanager.core.constants.MeasureUnit; import com.salesmanager.core.model.common.GenericEntityList; diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java index eabd3ef6f4..870f158fb2 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductFacadeV2Impl.java @@ -275,7 +275,7 @@ public ReadableProductPrice getProductPrice(Long id, ProductPriceRequest priceRe //change default availability with sku (instance availability) List availabilityList = productAvailabilityService.getBySku(priceRequest.getSku(), store); if(CollectionUtils.isNotEmpty(availabilityList)) { - model.setAvailabilities(new HashSet(availabilityList)); + model.setAvailabilities(new HashSet(availabilityList)); } } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionFacadeImpl.java index 0d0263695e..d10ce0e331 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/product/ProductOptionFacadeImpl.java @@ -38,7 +38,7 @@ import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductAttributeList; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionEntity; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionList; -import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueEntity; +import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValue; import com.salesmanager.shop.model.catalog.product.attribute.api.ReadableProductOptionValueList; import com.salesmanager.shop.model.entity.CodeEntity; import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; @@ -151,7 +151,7 @@ public ReadableProductOptionValueList optionValues(MerchantStore store, Language valueList.setRecordsTotal(options.getTotalElements()); valueList.setNumber(options.getNumber()); - List values = options.getContent().stream() + List values = options.getContent().stream() .map(option -> readableOptionValueMapper.convert(option, store, null)).collect(Collectors.toList()); valueList.setOptionValues(values); @@ -217,7 +217,7 @@ public boolean optionValueExists(String code, MerchantStore store) { } @Override - public ReadableProductOptionValueEntity saveOptionValue(PersistableProductOptionValue optionValue, + public ReadableProductOptionValue saveOptionValue(PersistableProductOptionValue optionValue, MerchantStore store, Language language) { Validate.notNull(optionValue, "Option value code must not be null"); Validate.notNull(store, "Store code must not be null"); @@ -243,7 +243,7 @@ public ReadableProductOptionValueEntity saveOptionValue(PersistableProductOption ProductOptionValue optValue = productOptionValueService.getById(store, value.getId()); // convert to readable - ReadableProductOptionValueEntity readableProductOptionValue = new ReadableProductOptionValueEntity(); + ReadableProductOptionValue readableProductOptionValue = new ReadableProductOptionValue(); readableProductOptionValue = readableOptionValueMapper.merge(optValue, readableProductOptionValue, store, language); @@ -251,7 +251,7 @@ public ReadableProductOptionValueEntity saveOptionValue(PersistableProductOption } @Override - public ReadableProductOptionValueEntity getOptionValue(Long optionValueId, MerchantStore store, Language language) { + public ReadableProductOptionValue getOptionValue(Long optionValueId, MerchantStore store, Language language) { Validate.notNull(optionValueId, "OptionValue id cannot be null"); Validate.notNull(store, "Store cannot be null"); From 4bfc431fab0aa916ce6b4bd86dd0142ce8b3ead7 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Tue, 21 Jun 2022 20:19:53 -0400 Subject: [PATCH 12/15] ProductRelationship --- .../ProductRelationshipRepositoryCustom.java | 2 ++ .../ProductRelationshipRepositoryImpl.java | 18 ++++++++++++++++++ .../ProductRelationshipServiceImpl.java | 2 +- .../facade/items/ProductItemsFacadeImpl.java | 9 ++++----- 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryCustom.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryCustom.java index b8b5e8199d..4f1294c185 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryCustom.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryCustom.java @@ -29,5 +29,7 @@ List getByType(MerchantStore store, String type, List getByType(MerchantStore store, String type, Product product); + List getByTypeAndRelatedProduct(MerchantStore store, String type, + Product product); } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryImpl.java index 9d2131f4ac..d3c0beda87 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/relationship/ProductRelationshipRepositoryImpl.java @@ -23,6 +23,13 @@ public class ProductRelationshipRepositoryImpl implements ProductRelationshipRep + "and pr.store.id=:storeId " + "and p.id=:id " + "and rpd.language.id=:langId"; + private static final String HQL_GET_BY_CODE_AND_STORE_ID_AND_RP_PRODUCT_ID = + "select distinct pr from ProductRelationship as pr " + + "left join fetch pr.relatedProduct rp " + + "where pr.code=:code " + + "and pr.store.id=:storeId " + + "and rp.available=:available " + + "and rp.id=:rpid"; private static final String HQL_GET_BY_PRODUCT_ID_AND_CODE_AVAILABLE = "select distinct pr from ProductRelationship as pr " + "left join fetch pr.product p " @@ -199,4 +206,15 @@ public List getByType(MerchantStore store, String type, Pro .setParameter("pId", product.getId()) .getResultList(); } + + @SuppressWarnings("unchecked") + @Override + public List getByTypeAndRelatedProduct(MerchantStore store, String type, Product product) { + return entityManager.createQuery(HQL_GET_BY_CODE_AND_STORE_ID_AND_RP_PRODUCT_ID) + .setParameter("code", type) + .setParameter("available", true) + .setParameter("rpid", product.getId()) + .setParameter("storeId", store.getId()) + .getResultList(); + } } diff --git a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/relationship/ProductRelationshipServiceImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/relationship/ProductRelationshipServiceImpl.java index db213b337f..6c72269e14 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/relationship/ProductRelationshipServiceImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/services/catalog/product/relationship/ProductRelationshipServiceImpl.java @@ -154,7 +154,7 @@ public List getGroupDefinition(MerchantStore store, String @Override public List getByType(MerchantStore store, Product product, String name) throws ServiceException { - return productRelationshipRepository.getByType(store, name, product); + return productRelationshipRepository.getByTypeAndRelatedProduct(store, name, product); } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/items/ProductItemsFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/items/ProductItemsFacadeImpl.java index b130b6624b..38fe0da103 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/facade/items/ProductItemsFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/facade/items/ProductItemsFacadeImpl.java @@ -188,13 +188,12 @@ public ReadableProductList addItemToGroup(Product product, String group, Merchan public ReadableProductList removeItemFromGroup(Product product, String group, MerchantStore store, Language language) throws Exception { - ProductRelationship relationship = null; - List relationships = productRelationshipService.getByType(store, product, group); + List relationships = productRelationshipService + .getByType(store, product, group); + for(ProductRelationship r : relationships) { - if(r.getRelatedProduct().getId().longValue()==product.getId().longValue()) { - productRelationshipService.delete(relationship); - } + productRelationshipService.delete(r); } return listItemsByGroup(group,store,language); From 956a4fe490488ea181b2af6fab4a3cb25be6a030 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Wed, 22 Jun 2022 08:50:55 -0400 Subject: [PATCH 13/15] variants + --- .../catalog/product/ProductRepositoryImpl.java | 9 ++++++++- .../catalog/product/attribute/ReadableProductOption.java | 9 +++++++++ .../shop/mapper/catalog/ReadableProductMapper.java | 1 + 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java index 300dd4d212..fddac54a53 100755 --- a/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java +++ b/sm-core/src/main/java/com/salesmanager/core/business/repositories/catalog/product/ProductRepositoryImpl.java @@ -1084,6 +1084,10 @@ public Product getBySku(String sku, MerchantStore store, Language language) { qs.append("select distinct p from Product as p "); qs.append("join fetch p.descriptions pd "); qs.append("join fetch p.merchantStore pm "); + qs.append("left join fetch p.availabilities pavail "); + qs.append("left join fetch p.type type "); + qs.append("left join fetch pavail.prices pavailpr "); + qs.append("left join fetch pavailpr.descriptions pavailprdesc "); qs.append("left join fetch p.categories categs "); qs.append("left join fetch categs.descriptions categsd "); @@ -1117,7 +1121,10 @@ public Product getBySku(String sku, MerchantStore store, Language language) { //instance availability and price qs.append("left join fetch pinst.availabilities pinsta "); qs.append("left join fetch pinsta.prices pinstap "); - qs.append("left join fetch pinst.productInstanceGroup "); + qs.append("left join fetch pinstap.descriptions pinstapdesc "); + qs.append("left join fetch pinst.productInstanceGroup pinstg "); + qs.append("left join fetch pinstg.images pinstgimg "); + qs.append("left join fetch pinstgimg.descriptions "); qs.append("where pinst.sku=:code or p.sku=:code and pm.id=:id"); diff --git a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java index 7741ee6cf8..de2882701c 100755 --- a/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java +++ b/sm-shop-model/src/main/java/com/salesmanager/shop/model/catalog/product/attribute/ReadableProductOption.java @@ -14,6 +14,7 @@ public class ReadableProductOption extends ProductPropertyOption { private String name; private String lang; + private boolean variant; private List optionValues = new ArrayList(); @@ -41,6 +42,14 @@ public void setOptionValues(List optionValues) { this.optionValues = optionValues; } + public boolean isVariant() { + return variant; + } + + public void setVariant(boolean variant) { + this.variant = variant; + } + } diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java index 483e8a3e10..690cb6ef16 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/catalog/ReadableProductMapper.java @@ -569,6 +569,7 @@ private void instanceToOption(TreeMap selectableOpt ReadableProductOption option = this.option(selectableOptions, instance.getVariant().getProductOption(), language); + option.setVariant(true); // take care of option value From c88c28bf055f7e30d9ec0c8109d7ca17fb4297be Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Wed, 22 Jun 2022 12:15:43 -0400 Subject: [PATCH 14/15] persiatable id check --- .../mapper/inventory/PersistableInventoryMapper.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java index 4ba0918f80..087b101a18 100644 --- a/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/mapper/inventory/PersistableInventoryMapper.java @@ -76,15 +76,15 @@ public ProductAvailability merge(PersistableInventory source, ProductAvailabilit destination.setProductDateAvailable(DateUtil.getDate(source.getDateAvailable())); } - if(source.getProductId()!= null && source.getInstance() > 0) { - Product product =productService.findOne(source.getId(), store); + if(source.getProductId()!= null && source.getProductId().longValue() > 0) { + Product product = productService.findOne(source.getId(), store); if(product == null) { throw new ResourceNotFoundException("Product with id [" + source.getId() + "] not found for store [" + store.getCode() + "]"); } destination.setSku(product.getSku()); } - if (source.getInstance() != null && source.getInstance() > 0) { + if (source.getInstance() != null && source.getInstance() .longValue()> 0) { Optional instance = productInstanceService.getById(source.getInstance(), store); if(instance.get() == null) { throw new ResourceNotFoundException("ProductInstance with id [" + source.getInstance() + "] not found for store [" + store.getCode() + "]"); @@ -102,9 +102,6 @@ public ProductAvailability merge(PersistableInventory source, ProductAvailabilit price.setId(priceEntity.getId()); } -// Set productPrices = Optional.ofNullable(destination.getPrices()).orElse(Collections.emptySet()); -// productPrices.stream() -// .filter() if (destination.getPrices() != null) { for (ProductPrice pp : destination.getPrices()) { if (isPositive(priceEntity.getId()) && priceEntity.getId().equals(pp.getId())) { From 1c8cedfab97dffc0389fc79ceb9a07bef9848e80 Mon Sep 17 00:00:00 2001 From: shopizerecomm Date: Wed, 22 Jun 2022 13:08:57 -0400 Subject: [PATCH 15/15] release notes --- README.md | 2 +- RELEASE-NOTES.md | 16 ++++++++++++++-- .../controller/order/facade/OrderFacadeImpl.java | 9 ++++++--- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 91e75affc1..2f1b10103a 100755 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ### Shopizer 2.X (for java 1.8 +) is still available -[![last_version](https://img.shields.io/badge/last_version-v3.0.0-blue.svg?style=flat)](https://github.com/shopizer-ecommerce/shopizer/tree/3.0.2) +[![last_version](https://img.shields.io/badge/last_version-v3.0.0-blue.svg?style=flat)](https://github.com/shopizer-ecommerce/shopizer/tree/3.2.0) [![Official site](https://img.shields.io/website-up-down-green-red/https/shields.io.svg?label=official%20site)](http://www.shopizer.com/) [![Docker Pulls](https://img.shields.io/docker/pulls/shopizerecomm/shopizer.svg)](https://hub.docker.com/r/shopizerecomm/shopizer) [![stackoverflow](https://img.shields.io/badge/shopizer-stackoverflow-orange.svg?style=flat)](http://stackoverflow.com/questions/tagged/shopizer) diff --git a/RELEASE-NOTES.md b/RELEASE-NOTES.md index 9ffd3f91e9..49ec5f2f4a 100755 --- a/RELEASE-NOTES.md +++ b/RELEASE-NOTES.md @@ -1,5 +1,17 @@ -Tag changes in version 2.16.0 +Version 3.2.0 -Spring boot 2.3.6 + +Changes + +Spring boot 2.5.12 + +Functionality + +Product variants addition to productOptions + +Fixes + +CVE-2022-23063 +Fix #727 diff --git a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java index 7326ac03da..39517fa622 100755 --- a/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java +++ b/sm-shop/src/main/java/com/salesmanager/shop/store/controller/order/facade/OrderFacadeImpl.java @@ -21,8 +21,8 @@ import javax.inject.Inject; import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -50,6 +50,7 @@ import com.salesmanager.core.business.services.shoppingcart.ShoppingCartService; import com.salesmanager.core.business.utils.CoreConfiguration; import com.salesmanager.core.business.utils.CreditCardUtils; +import com.salesmanager.core.business.utils.ProductPriceUtils; import com.salesmanager.core.model.catalog.product.Product; import com.salesmanager.core.model.catalog.product.availability.ProductAvailability; import com.salesmanager.core.model.common.Billing; @@ -102,7 +103,6 @@ import com.salesmanager.shop.store.api.exception.ResourceNotFoundException; import com.salesmanager.shop.store.api.exception.ServiceRuntimeException; import com.salesmanager.shop.store.controller.customer.facade.CustomerFacade; -import com.salesmanager.shop.store.controller.order.facade.OrderFacade; import com.salesmanager.shop.store.controller.shoppingCart.facade.ShoppingCartFacade; import com.salesmanager.shop.utils.DateUtil; import com.salesmanager.shop.utils.EmailTemplatesUtils; @@ -143,6 +143,8 @@ public class OrderFacadeImpl implements OrderFacade { private CountryService countryService; @Inject private ZoneService zoneService; + @Autowired + private ProductPriceUtils productPriceUtils; @Autowired private PersistableOrderApiPopulator persistableOrderApiPopulator; @@ -1273,12 +1275,13 @@ public Order processOrder(com.salesmanager.shop.model.order.v1.PersistableOrder } String submitedAmount = order.getPayment().getAmount(); + BigDecimal submitedAmountFormat = productPriceUtils.getAmount(submitedAmount); BigDecimal calculatedAmount = orderTotalSummary.getTotal(); String strCalculatedTotal = calculatedAmount.toPlainString(); // compare both prices - if (!submitedAmount.equals(strCalculatedTotal)) { + if (calculatedAmount.compareTo(submitedAmountFormat) != 0) { throw new ConversionException("Payment.amount does not match what the system has calculated " + strCalculatedTotal + " (received " + submitedAmount + ") please recalculate the order and submit again"); }