Search in sources :

Example 66 with Product

use of com.salesmanager.core.model.catalog.product.Product in project shopizer by shopizer-ecommerce.

the class ProductVariantApi method calculateVariant.

/**
 * Calculates the price based on selected options if any
 * @param id
 * @param options
 * @param merchantStore
 * @param language
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/products/{id}/variant", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ApiOperation(httpMethod = "POST", value = "Get product price variation based on selected product", notes = "", produces = "application/json", response = ReadableProductPrice.class)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableProductPrice calculateVariant(@PathVariable final Long id, @RequestBody ReadableSelectedProductVariant options, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception {
    Product product = productService.getById(id);
    if (product == null) {
        response.sendError(404, "Product not fount for id " + id);
        return null;
    }
    List<ReadableProductVariantValue> ids = options.getOptions();
    if (CollectionUtils.isEmpty(ids)) {
        return null;
    }
    List<ReadableProductVariantValue> variants = options.getOptions();
    List<ProductAttribute> attributes = new ArrayList<ProductAttribute>();
    Set<ProductAttribute> productAttributes = product.getAttributes();
    for (ProductAttribute attribute : productAttributes) {
        Long option = attribute.getProductOption().getId();
        Long optionValue = attribute.getProductOptionValue().getId();
        for (ReadableProductVariantValue v : variants) {
            if (v.getOption().longValue() == option.longValue() && v.getValue().longValue() == optionValue.longValue()) {
                attributes.add(attribute);
            }
        }
    }
    FinalPrice price = pricingService.calculateProductPrice(product, attributes);
    ReadableProductPrice readablePrice = new ReadableProductPrice();
    ReadableFinalPricePopulator populator = new ReadableFinalPricePopulator();
    populator.setPricingService(pricingService);
    populator.populate(price, readablePrice, merchantStore, language);
    return readablePrice;
}
Also used : ArrayList(java.util.ArrayList) Product(com.salesmanager.core.model.catalog.product.Product) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) ReadableFinalPricePopulator(com.salesmanager.shop.populator.catalog.ReadableFinalPricePopulator) ReadableProductPrice(com.salesmanager.shop.model.catalog.product.ReadableProductPrice) ReadableProductVariantValue(com.salesmanager.shop.model.catalog.product.attribute.ReadableProductVariantValue) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 67 with Product

use of com.salesmanager.core.model.catalog.product.Product in project shopizer by shopizer-ecommerce.

the class OrderServiceImpl method process.

private Order process(Order order, Customer customer, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, Transaction transaction, MerchantStore store) throws ServiceException {
    Validate.notNull(order, "Order cannot be null");
    Validate.notNull(customer, "Customer cannot be null (even if anonymous order)");
    Validate.notEmpty(items, "ShoppingCart items cannot be null");
    Validate.notNull(payment, "Payment cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    Validate.notNull(summary, "Order total Summary cannot be null");
    UserContext context = UserContext.getCurrentInstance();
    if (context != null) {
        String ipAddress = context.getIpAddress();
        if (!StringUtils.isBlank(ipAddress)) {
            order.setIpAddress(ipAddress);
        }
    }
    // first process payment
    Transaction processTransaction = paymentService.processPayment(customer, store, payment, items, order);
    if (order.getOrderHistory() == null || order.getOrderHistory().size() == 0 || order.getStatus() == null) {
        OrderStatus status = order.getStatus();
        if (status == null) {
            status = OrderStatus.ORDERED;
            order.setStatus(status);
        }
        Set<OrderStatusHistory> statusHistorySet = new HashSet<OrderStatusHistory>();
        OrderStatusHistory statusHistory = new OrderStatusHistory();
        statusHistory.setStatus(status);
        statusHistory.setDateAdded(new Date());
        statusHistory.setOrder(order);
        statusHistorySet.add(statusHistory);
        order.setOrderHistory(statusHistorySet);
    }
    if (customer.getId() == null || customer.getId() == 0) {
        customerService.create(customer);
    }
    order.setCustomerId(customer.getId());
    this.create(order);
    if (transaction != null) {
        transaction.setOrder(order);
        if (transaction.getId() == null || transaction.getId() == 0) {
            transactionService.create(transaction);
        } else {
            transactionService.update(transaction);
        }
    }
    if (processTransaction != null) {
        processTransaction.setOrder(order);
        if (processTransaction.getId() == null || processTransaction.getId() == 0) {
            transactionService.create(processTransaction);
        } else {
            transactionService.update(processTransaction);
        }
    }
    /**
     * decrement inventory
     */
    LOGGER.debug("Update inventory");
    Set<OrderProduct> products = order.getOrderProducts();
    for (OrderProduct orderProduct : products) {
        orderProduct.getProductQuantity();
        Product p = productService.getById(orderProduct.getId());
        if (p == null)
            throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
        for (ProductAvailability availability : p.getAvailabilities()) {
            int qty = availability.getProductQuantity();
            if (qty < orderProduct.getProductQuantity()) {
                // throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
                LOGGER.error("APP-BACKEND [" + ServiceException.EXCEPTION_INVENTORY_MISMATCH + "]");
            }
            qty = qty - orderProduct.getProductQuantity();
            availability.setProductQuantity(qty);
        }
        productService.update(p);
    }
    return order;
}
Also used : OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) UserContext(com.salesmanager.core.model.common.UserContext) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Product(com.salesmanager.core.model.catalog.product.Product) Date(java.util.Date) LocalDate(java.time.LocalDate) OrderStatus(com.salesmanager.core.model.order.orderstatus.OrderStatus) Transaction(com.salesmanager.core.model.payments.Transaction) ServiceException(com.salesmanager.core.business.exception.ServiceException) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) HashSet(java.util.HashSet)

Example 68 with Product

use of com.salesmanager.core.model.catalog.product.Product in project shopizer by shopizer-ecommerce.

the class OrderTotalServiceImpl method findOrderTotalVariation.

@Override
public OrderTotalVariation findOrderTotalVariation(OrderSummary summary, Customer customer, MerchantStore store, Language language) throws Exception {
    RebatesOrderTotalVariation variation = new RebatesOrderTotalVariation();
    List<OrderTotal> totals = null;
    if (orderTotalPostProcessors != null) {
        for (OrderTotalPostProcessorModule module : orderTotalPostProcessors) {
            // TODO check if the module is enabled from the Admin
            List<ShoppingCartItem> items = summary.getProducts();
            for (ShoppingCartItem item : items) {
                Long productId = item.getProductId();
                Product product = productService.getProductForLocale(productId, language, languageService.toLocale(language, store));
                OrderTotal orderTotal = module.caculateProductPiceVariation(summary, item, product, customer, store);
                if (orderTotal == null) {
                    continue;
                }
                if (totals == null) {
                    totals = new ArrayList<OrderTotal>();
                    variation.setVariations(totals);
                }
                // if product is null it will be catched when invoking the module
                orderTotal.setText(StringUtils.isNoneBlank(orderTotal.getText()) ? orderTotal.getText() : product.getProductDescription().getName());
                variation.getVariations().add(orderTotal);
            }
        }
    }
    return variation;
}
Also used : OrderTotalPostProcessorModule(com.salesmanager.core.modules.order.total.OrderTotalPostProcessorModule) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) OrderTotal(com.salesmanager.core.model.order.OrderTotal) RebatesOrderTotalVariation(com.salesmanager.core.model.order.RebatesOrderTotalVariation)

Example 69 with Product

use of com.salesmanager.core.model.catalog.product.Product in project shopizer by shopizer-ecommerce.

the class ProductReviewServiceImpl method saveOrUpdate.

private void saveOrUpdate(ProductReview review) throws ServiceException {
    Validate.notNull(review, "ProductReview cannot be null");
    Validate.notNull(review.getProduct(), "ProductReview.product cannot be null");
    Validate.notNull(review.getCustomer(), "ProductReview.customer cannot be null");
    // refresh product
    Product product = productService.getById(review.getProduct().getId());
    // ajust product rating
    Integer count = 0;
    if (product.getProductReviewCount() != null) {
        count = product.getProductReviewCount();
    }
    BigDecimal averageRating = product.getProductReviewAvg();
    if (averageRating == null) {
        averageRating = new BigDecimal(0);
    }
    // get reviews
    BigDecimal totalRating = averageRating.multiply(new BigDecimal(count));
    totalRating = totalRating.add(new BigDecimal(review.getReviewRating()));
    count = count + 1;
    double avg = totalRating.doubleValue() / count;
    product.setProductReviewAvg(new BigDecimal(avg));
    product.setProductReviewCount(count);
    super.save(review);
    productService.update(product);
    review.setProduct(product);
}
Also used : Product(com.salesmanager.core.model.catalog.product.Product) BigDecimal(java.math.BigDecimal)

Example 70 with Product

use of com.salesmanager.core.model.catalog.product.Product in project shopizer by shopizer-ecommerce.

the class ProductFacadeV2Impl method getProductPrice.

@Override
public ReadableProductPrice getProductPrice(Long id, ProductPriceRequest priceRequest, MerchantStore store, Language language) {
    Validate.notNull(id, "Product id cannot be null");
    Validate.notNull(priceRequest, "Product price request cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    Validate.notNull(language, "Language cannot be null");
    try {
        Product model = productService.findOne(id, store);
        List<ProductAttribute> attributes = null;
        if (!CollectionUtils.isEmpty(priceRequest.getOptions())) {
            List<Long> attrinutesIds = priceRequest.getOptions().stream().map(p -> p.getId()).collect(Collectors.toList());
            attributes = productAttributeService.getByAttributeIds(store, model, attrinutesIds);
            for (ProductAttribute attribute : attributes) {
                if (attribute.getProduct().getId().longValue() != id.longValue()) {
                    // throw unauthorized
                    throw new OperationNotAllowedException("Attribute with id [" + attribute.getId() + "] is not attached to product id [" + id + "]");
                }
            }
        }
        if (!StringUtils.isBlank(priceRequest.getSku())) {
            // change default availability with sku (instance availability)
            List<ProductAvailability> availabilityList = productAvailabilityService.getBySku(priceRequest.getSku(), store);
            if (CollectionUtils.isNotEmpty(availabilityList)) {
                model.setAvailabilities(new HashSet(availabilityList));
            }
        }
        FinalPrice price;
        // attributes can be null;
        price = pricingService.calculateProductPrice(model, attributes);
        ReadableProductPrice readablePrice = new ReadableProductPrice();
        ReadableFinalPricePopulator populator = new ReadableFinalPricePopulator();
        populator.setPricingService(pricingService);
        return populator.populate(price, readablePrice, store, language);
    } catch (Exception e) {
        throw new ServiceRuntimeException("An error occured while getting product price", e);
    }
}
Also used : ProductService(com.salesmanager.core.business.services.catalog.product.ProductService) ReadableProductInstance(com.salesmanager.shop.model.catalog.product.product.instance.ReadableProductInstance) Autowired(org.springframework.beans.factory.annotation.Autowired) ProductFacade(com.salesmanager.shop.store.controller.product.facade.ProductFacade) StringUtils(org.apache.commons.lang3.StringUtils) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Language(com.salesmanager.core.model.reference.language.Language) ReadableFinalPricePopulator(com.salesmanager.shop.populator.catalog.ReadableFinalPricePopulator) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) ProductInstanceService(com.salesmanager.core.business.services.catalog.product.instance.ProductInstanceService) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) Service(org.springframework.stereotype.Service) Qualifier(org.springframework.beans.factory.annotation.Qualifier) PricingService(com.salesmanager.core.business.services.catalog.product.PricingService) CategoryService(com.salesmanager.core.business.services.catalog.category.CategoryService) ReadableProductPrice(com.salesmanager.shop.model.catalog.product.ReadableProductPrice) ProductAttributeService(com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService) ReadableProduct(com.salesmanager.shop.model.catalog.product.ReadableProduct) OperationNotAllowedException(com.salesmanager.shop.store.api.exception.OperationNotAllowedException) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) Product(com.salesmanager.core.model.catalog.product.Product) ProductCriteria(com.salesmanager.core.model.catalog.product.ProductCriteria) ProductPriceRequest(com.salesmanager.shop.model.catalog.product.ProductPriceRequest) ProductRelationshipService(com.salesmanager.core.business.services.catalog.product.relationship.ProductRelationshipService) ImageFilePath(com.salesmanager.shop.utils.ImageFilePath) ProductAvailabilityService(com.salesmanager.core.business.services.catalog.product.availability.ProductAvailabilityService) Page(org.springframework.data.domain.Page) ProductInstance(com.salesmanager.core.model.catalog.product.instance.ProductInstance) Collectors(java.util.stream.Collectors) Profile(org.springframework.context.annotation.Profile) List(java.util.List) LocaleUtils(com.salesmanager.shop.utils.LocaleUtils) Validate(org.apache.commons.lang3.Validate) ProductRelationship(com.salesmanager.core.model.catalog.product.relationship.ProductRelationship) ReadableProductPopulator(com.salesmanager.shop.populator.catalog.ReadableProductPopulator) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ProductRelationshipType(com.salesmanager.core.model.catalog.product.relationship.ProductRelationshipType) ReadableProductMapper(com.salesmanager.shop.mapper.catalog.ReadableProductMapper) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) Comparator(java.util.Comparator) ReadableProductList(com.salesmanager.shop.model.catalog.product.ReadableProductList) ReadableProductInstanceMapper(com.salesmanager.shop.mapper.catalog.product.ReadableProductInstanceMapper) ReadableProduct(com.salesmanager.shop.model.catalog.product.ReadableProduct) Product(com.salesmanager.core.model.catalog.product.Product) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) ReadableFinalPricePopulator(com.salesmanager.shop.populator.catalog.ReadableFinalPricePopulator) OperationNotAllowedException(com.salesmanager.shop.store.api.exception.OperationNotAllowedException) ReadableProductPrice(com.salesmanager.shop.model.catalog.product.ReadableProductPrice) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) OperationNotAllowedException(com.salesmanager.shop.store.api.exception.OperationNotAllowedException) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) HashSet(java.util.HashSet) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice)

Aggregations

Product (com.salesmanager.core.model.catalog.product.Product)120 ReadableProduct (com.salesmanager.shop.model.catalog.product.ReadableProduct)53 ArrayList (java.util.ArrayList)45 Language (com.salesmanager.core.model.reference.language.Language)42 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)41 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)36 ServiceException (com.salesmanager.core.business.exception.ServiceException)35 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)35 ProductAvailability (com.salesmanager.core.model.catalog.product.availability.ProductAvailability)33 ReadableProductPopulator (com.salesmanager.shop.populator.catalog.ReadableProductPopulator)33 PersistableProduct (com.salesmanager.shop.model.catalog.product.PersistableProduct)29 ProductAttribute (com.salesmanager.core.model.catalog.product.attribute.ProductAttribute)28 List (java.util.List)25 Date (java.util.Date)23 LightPersistableProduct (com.salesmanager.shop.model.catalog.product.LightPersistableProduct)22 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)21 Category (com.salesmanager.core.model.catalog.category.Category)20 Collectors (java.util.stream.Collectors)20 FinalPrice (com.salesmanager.core.model.catalog.product.price.FinalPrice)19 ConversionException (com.salesmanager.core.business.exception.ConversionException)17