Search in sources :

Example 6 with OrderProduct

use of com.salesmanager.core.model.order.orderproduct.OrderProduct 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 7 with OrderProduct

use of com.salesmanager.core.model.order.orderproduct.OrderProduct in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method processOrderModel.

/**
 * Commit an order
 * @param order
 * @param customer
 * @param transaction
 * @param store
 * @param language
 * @return
 * @throws ServiceException
 */
private Order processOrderModel(ShopOrder order, Customer customer, Transaction transaction, MerchantStore store, Language language) throws ServiceException {
    try {
        if (order.isShipToBillingAdress()) {
            // customer shipping is billing
            PersistableCustomer orderCustomer = order.getCustomer();
            Address billing = orderCustomer.getBilling();
            orderCustomer.setDelivery(billing);
        }
        Order modelOrder = new Order();
        modelOrder.setDatePurchased(new Date());
        modelOrder.setBilling(customer.getBilling());
        modelOrder.setDelivery(customer.getDelivery());
        modelOrder.setPaymentModuleCode(order.getPaymentModule());
        modelOrder.setPaymentType(PaymentType.valueOf(order.getPaymentMethodType()));
        modelOrder.setShippingModuleCode(order.getShippingModule());
        modelOrder.setCustomerAgreement(order.isCustomerAgreed());
        // set the store
        modelOrder.setLocale(LocaleUtils.getLocale(store));
        // locale based
        // on the
        // country for
        // order $
        // formatting
        List<ShoppingCartItem> shoppingCartItems = order.getShoppingCartItems();
        Set<OrderProduct> orderProducts = new LinkedHashSet<OrderProduct>();
        if (!StringUtils.isBlank(order.getComments())) {
            OrderStatusHistory statusHistory = new OrderStatusHistory();
            statusHistory.setStatus(OrderStatus.ORDERED);
            statusHistory.setOrder(modelOrder);
            statusHistory.setDateAdded(new Date());
            statusHistory.setComments(order.getComments());
            modelOrder.getOrderHistory().add(statusHistory);
        }
        OrderProductPopulator orderProductPopulator = new OrderProductPopulator();
        orderProductPopulator.setDigitalProductService(digitalProductService);
        orderProductPopulator.setProductAttributeService(productAttributeService);
        orderProductPopulator.setProductService(productService);
        String shoppingCartCode = null;
        for (ShoppingCartItem item : shoppingCartItems) {
            if (shoppingCartCode == null && item.getShoppingCart() != null) {
                shoppingCartCode = item.getShoppingCart().getShoppingCartCode();
            }
            /**
             * Before processing order quantity of item must be > 0
             */
            Product product = productService.getById(item.getProductId());
            if (product == null) {
                throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
            }
            LOGGER.debug("Validate inventory");
            for (ProductAvailability availability : product.getAvailabilities()) {
                if (availability.getRegion().equals(Constants.ALL_REGIONS)) {
                    int qty = availability.getProductQuantity();
                    if (qty < item.getQuantity()) {
                        throw new ServiceException(ServiceException.EXCEPTION_INVENTORY_MISMATCH);
                    }
                }
            }
            OrderProduct orderProduct = new OrderProduct();
            orderProduct = orderProductPopulator.populate(item, orderProduct, store, language);
            orderProduct.setOrder(modelOrder);
            orderProducts.add(orderProduct);
        }
        modelOrder.setOrderProducts(orderProducts);
        OrderTotalSummary summary = order.getOrderTotalSummary();
        List<com.salesmanager.core.model.order.OrderTotal> totals = summary.getTotals();
        // re-order totals
        Collections.sort(totals, new Comparator<com.salesmanager.core.model.order.OrderTotal>() {

            public int compare(com.salesmanager.core.model.order.OrderTotal x, com.salesmanager.core.model.order.OrderTotal y) {
                if (x.getSortOrder() == y.getSortOrder())
                    return 0;
                return x.getSortOrder() < y.getSortOrder() ? -1 : 1;
            }
        });
        Set<com.salesmanager.core.model.order.OrderTotal> modelTotals = new LinkedHashSet<com.salesmanager.core.model.order.OrderTotal>();
        for (com.salesmanager.core.model.order.OrderTotal total : totals) {
            total.setOrder(modelOrder);
            modelTotals.add(total);
        }
        modelOrder.setOrderTotal(modelTotals);
        modelOrder.setTotal(order.getOrderTotalSummary().getTotal());
        // order misc objects
        modelOrder.setCurrency(store.getCurrency());
        modelOrder.setMerchant(store);
        // customer object
        orderCustomer(customer, modelOrder, language);
        // populate shipping information
        if (!StringUtils.isBlank(order.getShippingModule())) {
            modelOrder.setShippingModuleCode(order.getShippingModule());
        }
        String paymentType = order.getPaymentMethodType();
        Payment payment = new Payment();
        payment.setPaymentType(PaymentType.valueOf(paymentType));
        payment.setAmount(order.getOrderTotalSummary().getTotal());
        payment.setModuleName(order.getPaymentModule());
        payment.setCurrency(modelOrder.getCurrency());
        if (order.getPayment() != null && order.getPayment().get("paymentToken") != null) {
            // set
            // token
            String paymentToken = order.getPayment().get("paymentToken");
            Map<String, String> paymentMetaData = new HashMap<String, String>();
            payment.setPaymentMetaData(paymentMetaData);
            paymentMetaData.put("paymentToken", paymentToken);
        }
        if (PaymentType.CREDITCARD.name().equals(paymentType)) {
            payment = new CreditCardPayment();
            ((CreditCardPayment) payment).setCardOwner(order.getPayment().get("creditcard_card_holder"));
            ((CreditCardPayment) payment).setCredidCardValidationNumber(order.getPayment().get("creditcard_card_cvv"));
            ((CreditCardPayment) payment).setCreditCardNumber(order.getPayment().get("creditcard_card_number"));
            ((CreditCardPayment) payment).setExpirationMonth(order.getPayment().get("creditcard_card_expirationmonth"));
            ((CreditCardPayment) payment).setExpirationYear(order.getPayment().get("creditcard_card_expirationyear"));
            Map<String, String> paymentMetaData = order.getPayment();
            payment.setPaymentMetaData(paymentMetaData);
            payment.setPaymentType(PaymentType.valueOf(paymentType));
            payment.setAmount(order.getOrderTotalSummary().getTotal());
            payment.setModuleName(order.getPaymentModule());
            payment.setCurrency(modelOrder.getCurrency());
            CreditCardType creditCardType = null;
            String cardType = order.getPayment().get("creditcard_card_type");
            // supported credit cards
            if (CreditCardType.AMEX.name().equalsIgnoreCase(cardType)) {
                creditCardType = CreditCardType.AMEX;
            } else if (CreditCardType.VISA.name().equalsIgnoreCase(cardType)) {
                creditCardType = CreditCardType.VISA;
            } else if (CreditCardType.MASTERCARD.name().equalsIgnoreCase(cardType)) {
                creditCardType = CreditCardType.MASTERCARD;
            } else if (CreditCardType.DINERS.name().equalsIgnoreCase(cardType)) {
                creditCardType = CreditCardType.DINERS;
            } else if (CreditCardType.DISCOVERY.name().equalsIgnoreCase(cardType)) {
                creditCardType = CreditCardType.DISCOVERY;
            }
            ((CreditCardPayment) payment).setCreditCard(creditCardType);
            if (creditCardType != null) {
                CreditCard cc = new CreditCard();
                cc.setCardType(creditCardType);
                cc.setCcCvv(((CreditCardPayment) payment).getCredidCardValidationNumber());
                cc.setCcOwner(((CreditCardPayment) payment).getCardOwner());
                cc.setCcExpires(((CreditCardPayment) payment).getExpirationMonth() + "-" + ((CreditCardPayment) payment).getExpirationYear());
                // hash credit card number
                if (!StringUtils.isBlank(cc.getCcNumber())) {
                    String maskedNumber = CreditCardUtils.maskCardNumber(order.getPayment().get("creditcard_card_number"));
                    cc.setCcNumber(maskedNumber);
                    modelOrder.setCreditCard(cc);
                }
            }
        }
        if (PaymentType.PAYPAL.name().equals(paymentType)) {
            // check for previous transaction
            if (transaction == null) {
                throw new ServiceException("payment.error");
            }
            payment = new com.salesmanager.core.model.payments.PaypalPayment();
            ((com.salesmanager.core.model.payments.PaypalPayment) payment).setPayerId(transaction.getTransactionDetails().get("PAYERID"));
            ((com.salesmanager.core.model.payments.PaypalPayment) payment).setPaymentToken(transaction.getTransactionDetails().get("TOKEN"));
        }
        modelOrder.setShoppingCartCode(shoppingCartCode);
        modelOrder.setPaymentModuleCode(order.getPaymentModule());
        payment.setModuleName(order.getPaymentModule());
        if (transaction != null) {
            orderService.processOrder(modelOrder, customer, order.getShoppingCartItems(), summary, payment, store);
        } else {
            orderService.processOrder(modelOrder, customer, order.getShoppingCartItems(), summary, payment, transaction, store);
        }
        return modelOrder;
    } catch (ServiceException se) {
        // may be invalid credit card
        throw se;
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Address(com.salesmanager.shop.model.customer.address.Address) 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) HashMap(java.util.HashMap) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) PersistableOrderProduct(com.salesmanager.shop.model.order.PersistableOrderProduct) Product(com.salesmanager.core.model.catalog.product.Product) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) CreditCardType(com.salesmanager.core.model.payments.CreditCardType) Date(java.util.Date) LocalDate(java.time.LocalDate) CreditCard(com.salesmanager.core.model.order.payment.CreditCard) 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) CreditCardPayment(com.salesmanager.core.model.payments.CreditCardPayment) Payment(com.salesmanager.core.model.payments.Payment) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ReadableOrderStatusHistory(com.salesmanager.shop.model.order.history.ReadableOrderStatusHistory) PersistableOrderStatusHistory(com.salesmanager.shop.model.order.history.PersistableOrderStatusHistory) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) OrderTotal(com.salesmanager.shop.model.order.total.OrderTotal)

Example 8 with OrderProduct

use of com.salesmanager.core.model.order.orderproduct.OrderProduct in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method setOrderProductList.

private void setOrderProductList(final Order order, final Locale locale, final MerchantStore store, final Language language, final com.salesmanager.shop.model.order.v0.ReadableOrder readableOrder) throws ConversionException {
    List<ReadableOrderProduct> orderProducts = new ArrayList<ReadableOrderProduct>();
    for (OrderProduct p : order.getOrderProducts()) {
        ReadableOrderProductPopulator orderProductPopulator = new ReadableOrderProductPopulator();
        orderProductPopulator.setLocale(locale);
        orderProductPopulator.setProductService(productService);
        orderProductPopulator.setPricingService(pricingService);
        orderProductPopulator.setimageUtils(imageUtils);
        ReadableOrderProduct orderProduct = new ReadableOrderProduct();
        orderProductPopulator.populate(p, orderProduct, store, language);
        // image
        // attributes
        orderProducts.add(orderProduct);
    }
    readableOrder.setProducts(orderProducts);
}
Also used : OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) PersistableOrderProduct(com.salesmanager.shop.model.order.PersistableOrderProduct) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) ReadableOrderProductPopulator(com.salesmanager.shop.populator.order.ReadableOrderProductPopulator) ArrayList(java.util.ArrayList) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct)

Example 9 with OrderProduct

use of com.salesmanager.core.model.order.orderproduct.OrderProduct in project shopizer by shopizer-ecommerce.

the class OrderFacadeImpl method getReadableOrder.

@Override
public com.salesmanager.shop.model.order.v0.ReadableOrder getReadableOrder(Long orderId, MerchantStore store, Language language) {
    Validate.notNull(store, "MerchantStore cannot be null");
    Order modelOrder = orderService.getOrder(orderId, store);
    if (modelOrder == null) {
        throw new ResourceNotFoundException("Order not found with id " + orderId);
    }
    com.salesmanager.shop.model.order.v0.ReadableOrder readableOrder = new com.salesmanager.shop.model.order.v0.ReadableOrder();
    Long customerId = modelOrder.getCustomerId();
    if (customerId != null) {
        ReadableCustomer readableCustomer = customerFacade.getCustomerById(customerId, store, language);
        if (readableCustomer == null) {
            LOGGER.warn("Customer id " + customerId + " not found in order " + orderId);
        } else {
            readableOrder.setCustomer(readableCustomer);
        }
    }
    try {
        readableOrderPopulator.populate(modelOrder, readableOrder, store, language);
        // order products
        List<ReadableOrderProduct> orderProducts = new ArrayList<ReadableOrderProduct>();
        for (OrderProduct p : modelOrder.getOrderProducts()) {
            ReadableOrderProductPopulator orderProductPopulator = new ReadableOrderProductPopulator();
            orderProductPopulator.setProductService(productService);
            orderProductPopulator.setPricingService(pricingService);
            orderProductPopulator.setimageUtils(imageUtils);
            ReadableOrderProduct orderProduct = new ReadableOrderProduct();
            orderProductPopulator.populate(p, orderProduct, store, language);
            orderProducts.add(orderProduct);
        }
        readableOrder.setProducts(orderProducts);
    } catch (Exception e) {
        throw new ServiceRuntimeException("Error while getting order [" + orderId + "]");
    }
    return readableOrder;
}
Also used : ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) PersistableOrderProduct(com.salesmanager.shop.model.order.PersistableOrderProduct) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) ArrayList(java.util.ArrayList) ReadableOrderProduct(com.salesmanager.shop.model.order.ReadableOrderProduct) 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) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ReadableOrderProductPopulator(com.salesmanager.shop.populator.order.ReadableOrderProductPopulator) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException)

Example 10 with OrderProduct

use of com.salesmanager.core.model.order.orderproduct.OrderProduct 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)

Aggregations

OrderProduct (com.salesmanager.core.model.order.orderproduct.OrderProduct)13 ConversionException (com.salesmanager.core.business.exception.ConversionException)8 Product (com.salesmanager.core.model.catalog.product.Product)7 ServiceException (com.salesmanager.core.business.exception.ServiceException)6 PersistableOrderProduct (com.salesmanager.shop.model.order.PersistableOrderProduct)6 ReadableOrderProduct (com.salesmanager.shop.model.order.ReadableOrderProduct)6 OrderProductAttribute (com.salesmanager.core.model.order.orderproduct.OrderProductAttribute)5 BigDecimal (java.math.BigDecimal)5 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 Order (com.salesmanager.core.model.order.Order)4 OrderStatusHistory (com.salesmanager.core.model.order.orderstatus.OrderStatusHistory)4 ReadableOrderProductPopulator (com.salesmanager.shop.populator.order.ReadableOrderProductPopulator)4 ProductAvailability (com.salesmanager.core.model.catalog.product.availability.ProductAvailability)3 OrderProductPrice (com.salesmanager.core.model.order.orderproduct.OrderProductPrice)3 CreditCard (com.salesmanager.core.model.order.payment.CreditCard)3 Country (com.salesmanager.core.model.reference.country.Country)3 Zone (com.salesmanager.core.model.reference.zone.Zone)3 ShopOrder (com.salesmanager.shop.model.order.ShopOrder)3 OrderTotal (com.salesmanager.shop.model.order.total.OrderTotal)3