Search in sources :

Example 21 with ShoppingCart

use of com.salesmanager.core.model.shoppingcart.ShoppingCart in project shopizer by shopizer-ecommerce.

the class IndexShoppingCartProcessor method process.

@Async
@Override
public void process(String event, Object entity, Customer customer, MerchantStore store) {
    ShoppingCart cart = (ShoppingCart) entity;
    try {
        RestHighLevelClient client = client();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        Mapping m = new Mapping("cart", event, cart, customer);
        String json = mapper.writeValueAsString(m);
        String indexName = new StringBuilder().append(INDEX_NAME).append(store.getCode().toLowerCase()).toString();
        IndexRequest indexRequest = new IndexRequest(indexName);
        indexRequest.id(String.valueOf(cart.getId()));
        indexRequest.source(json, XContentType.JSON);
        IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
        if (response.getResult() != DocWriteResponse.Result.CREATED && response.getResult() != DocWriteResponse.Result.UPDATED) {
            LOGGER.error("An error occured while indexing an shopping cart document " + cart.getId() + " " + response.getResult().name());
        }
        client.close();
    } catch (Exception e) {
        LOGGER.error("Cannot index cart [" + cart.getId() + "] ", e);
    }
}
Also used : ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) IndexResponse(org.elasticsearch.action.index.IndexResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) IndexRequest(org.elasticsearch.action.index.IndexRequest) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Async(org.springframework.scheduling.annotation.Async)

Example 22 with ShoppingCart

use of com.salesmanager.core.model.shoppingcart.ShoppingCart in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method processOrder.

/**
 * Process order from api
 */
@Override
public Order processOrder(com.salesmanager.shop.model.order.v1.PersistableOrder order, Customer customer, MerchantStore store, Language language, Locale locale) throws ServiceException {
    Validate.notNull(order, "Order cannot be null");
    Validate.notNull(customer, "Customer cannot be null");
    Validate.notNull(store, "MerchantStore cannot be null");
    Validate.notNull(language, "Language cannot be null");
    Validate.notNull(locale, "Locale cannot be null");
    try {
        Order modelOrder = new Order();
        persistableOrderApiPopulator.populate(order, modelOrder, store, language);
        Long shoppingCartId = order.getShoppingCartId();
        ShoppingCart cart = shoppingCartService.getById(shoppingCartId, store);
        if (cart == null) {
            throw new ServiceException("Shopping cart with id " + shoppingCartId + " does not exist");
        }
        Set<ShoppingCartItem> shoppingCartItems = cart.getLineItems();
        List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(shoppingCartItems);
        Set<OrderProduct> orderProducts = new LinkedHashSet<OrderProduct>();
        OrderProductPopulator orderProductPopulator = new OrderProductPopulator();
        orderProductPopulator.setDigitalProductService(digitalProductService);
        orderProductPopulator.setProductAttributeService(productAttributeService);
        orderProductPopulator.setProductService(productService);
        for (ShoppingCartItem item : shoppingCartItems) {
            OrderProduct orderProduct = new OrderProduct();
            orderProduct = orderProductPopulator.populate(item, orderProduct, store, language);
            orderProduct.setOrder(modelOrder);
            orderProducts.add(orderProduct);
        }
        modelOrder.setOrderProducts(orderProducts);
        if (order.getAttributes() != null && order.getAttributes().size() > 0) {
            Set<OrderAttribute> attrs = new HashSet<OrderAttribute>();
            for (com.salesmanager.shop.model.order.OrderAttribute attribute : order.getAttributes()) {
                OrderAttribute attr = new OrderAttribute();
                attr.setKey(attribute.getKey());
                attr.setValue(attribute.getValue());
                attr.setOrder(modelOrder);
                attrs.add(attr);
            }
            modelOrder.setOrderAttributes(attrs);
        }
        // requires Shipping information (need a quote id calculated)
        ShippingSummary shippingSummary = null;
        // get shipping quote if asked for
        if (order.getShippingQuote() != null && order.getShippingQuote().longValue() > 0) {
            shippingSummary = shippingQuoteService.getShippingSummary(order.getShippingQuote(), store);
            if (shippingSummary != null) {
                modelOrder.setShippingModuleCode(shippingSummary.getShippingModule());
            }
        }
        // requires Order Totals, this needs recalculation and then compare
        // total with the amount sent as part
        // of process order request. If totals does not match, an error
        // should be thrown.
        OrderTotalSummary orderTotalSummary = null;
        OrderSummary orderSummary = new OrderSummary();
        orderSummary.setShippingSummary(shippingSummary);
        List<ShoppingCartItem> itemsSet = new ArrayList<ShoppingCartItem>(cart.getLineItems());
        orderSummary.setProducts(itemsSet);
        orderTotalSummary = orderService.caculateOrderTotal(orderSummary, customer, store, language);
        if (order.getPayment().getAmount() == null) {
            throw new ConversionException("Requires Payment.amount");
        }
        String submitedAmount = order.getPayment().getAmount();
        BigDecimal calculatedAmount = orderTotalSummary.getTotal();
        String strCalculatedTotal = calculatedAmount.toPlainString();
        // compare both prices
        if (!submitedAmount.equals(strCalculatedTotal)) {
            throw new ConversionException("Payment.amount does not match what the system has calculated " + strCalculatedTotal + " (received " + submitedAmount + ") please recalculate the order and submit again");
        }
        modelOrder.setTotal(calculatedAmount);
        List<com.salesmanager.core.model.order.OrderTotal> totals = orderTotalSummary.getTotals();
        Set<com.salesmanager.core.model.order.OrderTotal> set = new HashSet<com.salesmanager.core.model.order.OrderTotal>();
        if (!CollectionUtils.isEmpty(totals)) {
            for (com.salesmanager.core.model.order.OrderTotal total : totals) {
                total.setOrder(modelOrder);
                set.add(total);
            }
        }
        modelOrder.setOrderTotal(set);
        PersistablePaymentPopulator paymentPopulator = new PersistablePaymentPopulator();
        paymentPopulator.setPricingService(pricingService);
        Payment paymentModel = new Payment();
        paymentPopulator.populate(order.getPayment(), paymentModel, store, language);
        modelOrder.setShoppingCartCode(cart.getShoppingCartCode());
        /**
         */
        if (!StringUtils.isBlank(customer.getNick()) && !customer.isAnonymous()) {
            if (order.getCustomerId() == null && (customerFacade.checkIfUserExists(customer.getNick(), store))) {
                customer.setAnonymous(true);
                customer.setNick(null);
            // send email instructions
            }
        }
        // order service
        modelOrder = orderService.processOrder(modelOrder, customer, items, orderTotalSummary, paymentModel, store);
        // update cart
        try {
            cart.setOrderId(modelOrder.getId());
            shoppingCartFacade.saveOrUpdateShoppingCart(cart);
        } catch (Exception e) {
            LOGGER.error("Cannot delete cart " + cart.getId(), e);
        }
        // email management
        if ("true".equals(coreConfiguration.getProperty("ORDER_EMAIL_API"))) {
            // send email
            try {
                notify(modelOrder, customer, store, language, locale);
            } catch (Exception e) {
                LOGGER.error("Cannot send order confirmation email", e);
            }
        }
        return modelOrder;
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) PersistableOrderProduct(com.salesmanager.shop.model.order.PersistableOrderProduct) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) OrderProductPopulator(com.salesmanager.shop.populator.order.OrderProductPopulator) ReadableOrderProductPopulator(com.salesmanager.shop.populator.order.ReadableOrderProductPopulator) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) OrderSummary(com.salesmanager.core.model.order.OrderSummary) ArrayList(java.util.ArrayList) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) OrderAttribute(com.salesmanager.core.model.order.attributes.OrderAttribute) PersistablePaymentPopulator(com.salesmanager.shop.populator.order.transaction.PersistablePaymentPopulator) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) ConversionException(com.salesmanager.core.business.exception.ConversionException) BigDecimal(java.math.BigDecimal) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ServiceException(com.salesmanager.core.business.exception.ServiceException) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) ConversionException(com.salesmanager.core.business.exception.ConversionException) CreditCardPayment(com.salesmanager.core.model.payments.CreditCardPayment) Payment(com.salesmanager.core.model.payments.Payment) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) OrderTotal(com.salesmanager.shop.model.order.total.OrderTotal)

Example 23 with ShoppingCart

use of com.salesmanager.core.model.shoppingcart.ShoppingCart in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method calculateOrderTotal.

private OrderTotalSummary calculateOrderTotal(MerchantStore store, Customer customer, com.salesmanager.shop.model.order.v0.PersistableOrder order, Language language) throws Exception {
    OrderTotalSummary orderTotalSummary = null;
    OrderSummary summary = new OrderSummary();
    if (order instanceof ShopOrder) {
        ShopOrder o = (ShopOrder) order;
        summary.setProducts(o.getShoppingCartItems());
        if (o.getShippingSummary() != null) {
            summary.setShippingSummary(o.getShippingSummary());
        }
        if (!StringUtils.isBlank(o.getCartCode())) {
            ShoppingCart shoppingCart = shoppingCartFacade.getShoppingCartModel(o.getCartCode(), store);
            // promo code
            if (!StringUtils.isBlank(shoppingCart.getPromoCode())) {
                // promo
                Date promoDateAdded = shoppingCart.getPromoAdded();
                // valid
                // 1 day
                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)) {
                    summary.setPromoCode(shoppingCart.getPromoCode());
                } else {
                    // clear promo
                    shoppingCart.setPromoCode(null);
                    shoppingCartService.saveOrUpdate(shoppingCart);
                }
            }
        }
        orderTotalSummary = orderService.caculateOrderTotal(summary, customer, store, language);
    } else {
        // PersistableOrder not implemented
        throw new Exception("calculateOrderTotal not yet implemented for PersistableOrder");
    }
    return orderTotalSummary;
}
Also used : ShopOrder(com.salesmanager.shop.model.order.ShopOrder) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ZonedDateTime(java.time.ZonedDateTime) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) OrderSummary(com.salesmanager.core.model.order.OrderSummary) Instant(java.time.Instant) LocalDate(java.time.LocalDate) Date(java.util.Date) LocalDate(java.time.LocalDate) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ServiceException(com.salesmanager.core.business.exception.ServiceException) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) ConversionException(com.salesmanager.core.business.exception.ConversionException)

Example 24 with ShoppingCart

use of com.salesmanager.core.model.shoppingcart.ShoppingCart in project shopizer by shopizer-ecommerce.

the class ShoppingCartFacadeImpl method getCart.

@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");
    // Check if customer has an existing shopping cart
    ShoppingCart cartModel = shoppingCartService.getShoppingCart(customer);
    if (cartModel == null) {
        return null;
    }
    shoppingCartCalculationService.calculate(cartModel, store, language);
    ReadableShoppingCart readableCart = new ReadableShoppingCart();
    readableCart = readableShoppingCartMapper.convert(cartModel, store, language);
    return readableCart;
}
Also used : ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ReadableShoppingCart(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart) ReadableShoppingCart(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart)

Example 25 with ShoppingCart

use of com.salesmanager.core.model.shoppingcart.ShoppingCart in project shopizer by shopizer-ecommerce.

the class ShoppingCartFacadeImpl method modifyCartMulti.

@Override
public ReadableShoppingCart modifyCartMulti(String cartCode, List<PersistableShoppingCartItem> 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);
}
Also used : ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ReadableShoppingCart(com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart)

Aggregations

ShoppingCart (com.salesmanager.core.model.shoppingcart.ShoppingCart)38 ReadableShoppingCart (com.salesmanager.shop.model.shoppingcart.ReadableShoppingCart)18 ServiceException (com.salesmanager.core.business.exception.ServiceException)11 Customer (com.salesmanager.core.model.customer.Customer)11 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)8 HashSet (java.util.HashSet)8 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)8 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)7 ArrayList (java.util.ArrayList)7 Date (java.util.Date)7 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)6 ShoppingCartDataPopulator (com.salesmanager.shop.populator.shoppingCart.ShoppingCartDataPopulator)6 ProductAttribute (com.salesmanager.core.model.catalog.product.attribute.ProductAttribute)5 FinalPrice (com.salesmanager.core.model.catalog.product.price.FinalPrice)5 ShippingSummary (com.salesmanager.core.model.shipping.ShippingSummary)5 ShoppingCartItem (com.salesmanager.shop.model.shoppingcart.ShoppingCartItem)5 LocalDate (java.time.LocalDate)5 ConversionException (com.salesmanager.core.business.exception.ConversionException)4