Package org.broadleafcommerce.core.order.domain

Examples of org.broadleafcommerce.core.order.domain.Order


    }

    @Test(groups = { "testCartAndNamedOrder" })
    @Transactional
    public void testMoveItemToCartFromNamedOrder() throws RemoveFromCartException, AddToCartException {
        Order namedOrder = setUpNamedOrder();
        List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
        namedOrderItems.addAll(namedOrder.getOrderItems());
        List<OrderItem> movedOrderItems = new ArrayList<OrderItem>();
        movedOrderItems.add(namedOrderItems.get(0));
        Order cart = orderService.createNewCartForCustomer(namedOrder.getCustomer());
        cart = orderService.addItemFromNamedOrder(namedOrder, movedOrderItems.get(0), true);
        List<Order> customerNamedOrders = orderService.findOrdersForCustomer(namedOrder.getCustomer(), OrderStatus.NAMED);
        assert customerNamedOrders.size() == 0;
        assert cart.getOrderItems().size() == 1;
        assert namedOrder.getOrderItems().size() == 0;
        assert cartContainsOnlyTheseItems(cart, movedOrderItems);
    }
View Full Code Here


    }

    @Test(groups = { "testCartAndNamedOrder" })
    @Transactional
    public void testMoveItemToCartFromNamedOrderWithoutExistingCart() throws RemoveFromCartException, AddToCartException {
        Order namedOrder = setUpNamedOrder();
        List<OrderItem> namedOrderItems = new ArrayList<OrderItem>();
        namedOrderItems.addAll(namedOrder.getOrderItems());
        List<OrderItem> movedOrderItems = new ArrayList<OrderItem>();
        movedOrderItems.add(namedOrderItems.get(0));
        Order cart = orderService.addItemFromNamedOrder(namedOrder, movedOrderItems.get(0), true);
        List<Order> customerNamedOrders = orderService.findOrdersForCustomer(namedOrder.getCustomer(), OrderStatus.NAMED);

        assert customerNamedOrders.size() == 0;
        assert cart.getOrderItems().size() == 1;
        assert namedOrder.getOrderItems().size() == 0;
        assert cartContainsOnlyTheseItems(cart, movedOrderItems);
    }
View Full Code Here

    }
   
    @Transactional
    @Test(groups = { "testMergeCart" })
    public void testMergeWithNoAnonymousCart() throws PricingException, RemoveFromCartException, AddToCartException {
        Order anonymousCart = null;
        Order customerCart = setUpCartWithActiveSku();
        Customer customer = customerCart.getCustomer();
       
        MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
       
        assert response.getOrder().getOrderItems().size() == 1;
        assert response.getOrder().getId().equals(customerCart.getId());
        assert response.isMerged() == false;
    }
View Full Code Here

    }
   
    @Transactional
    @Test(groups = { "testMergeCart" })
    public void testMergeWithNoCustomerCart() throws PricingException, RemoveFromCartException, AddToCartException {
        Order anonymousCart = setUpCartWithActiveSku();
        Order customerCart = null;
        Customer customer = customerService.saveCustomer(createNamedCustomer());
       
        MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
       
        assert response.getOrder().getOrderItems().size() == 1;
View Full Code Here

    }
   
    @Transactional
    @Test(groups = { "testMergeCart" })
    public void testMergeWithBothCarts() throws PricingException, RemoveFromCartException, AddToCartException {
        Order anonymousCart = setUpCartWithActiveSku();
        Order customerCart = setUpCartWithActiveSku();
       
        Customer customer = customerCart.getCustomer();
       
        MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
       
        assert response.getOrder().getOrderItems().size() == 1;
        assert response.getOrder().getId().equals(anonymousCart.getId());
View Full Code Here

    }
   
    @Transactional
    @Test(groups = { "testMergeCart" })
    public void testMergeWithInactiveAnonymousCart() throws PricingException, RemoveFromCartException, AddToCartException {
        Order anonymousCart = null;
        Order customerCart = setUpCartWithInactiveSku();
       
        Customer customer = customerCart.getCustomer();
       
        MergeCartResponse response = mergeCartService.mergeCart(customer, anonymousCart);
       
        assert response.getOrder().getOrderItems().size() == 0;
        assert response.getOrder().getId().equals(customerCart.getId());
        assert response.isMerged() == false;
    }
View Full Code Here

    @Resource(name = "blSecureOrderPaymentService")
    protected SecureOrderPaymentService secureOrderPaymentService;

    @Override
    public ProcessContext<CheckoutSeed> execute(ProcessContext<CheckoutSeed> context) throws Exception {
        Order order = context.getSeedData().getOrder();
       
        Map<String, Object> rollbackState = new HashMap<String, Object>();
       
        // There are definitely enough payments on the order. We now need to confirm each unconfirmed payment on the order.
        // Unconfirmed payments could be added for things like gift cards and account credits; they are not actually
        // decremented from the user's account until checkout. This could also be used in some credit card processing
        // situations
        // Important: The payment.getAmount() must be the final amount that is going to be confirmed. If the order total
        // changed, the order payments need to be adjusted to reflect this and must add up to the order total.
        // This can happen in the case of PayPal Express or other hosted gateways where the unconfirmed payment comes back
        // to a review page, the customer selects shipping and the order total is adjusted.
       
        /**
         * This list contains the additional transactions that were created to confirm previously unconfirmed transactions
         * which can occur if you send credit card data directly to Broadlaef and rely on this activity to confirm
         * that transaction
         */
        Map<OrderPayment, PaymentTransaction> additionalTransactions = new HashMap<OrderPayment, PaymentTransaction>();
        List<PaymentResponseDTO> failedTransactions = new ArrayList<PaymentResponseDTO>();
        // Used for the rollback handler; we want to make sure that we roll back transactions that have already been confirmed
        // as well as transctions that we are about to confirm here
        List<PaymentTransaction> confirmedTransactions = new ArrayList<PaymentTransaction>();
        /**
         * This is a subset of the additionalTransactions that contains the transactions that were confirmed in this activity
         */
        Map<OrderPayment, PaymentTransactionType> additionalConfirmedTransactions = new HashMap<OrderPayment, PaymentTransactionType>();

        for (OrderPayment payment : order.getPayments()) {
            if (payment.isActive()) {
                for (PaymentTransaction tx : payment.getTransactions()) {
                    if (PaymentTransactionType.UNCONFIRMED.equals(tx.getType())) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Transaction " + tx.getId() + " is not confirmed. Proceeding to confirm transaction.");
                        }

                        // Cannot confirm anything here if there is no provider
                        if (paymentConfigurationServiceProvider == null) {
                            String msg = "There are unconfirmed payment transactions on this payment but no payment gateway" +
                                    " configuration or transaction confirmation service configured";
                            LOG.error(msg);
                            throw new CheckoutException(msg, context.getSeedData());
                        }

                        PaymentGatewayConfigurationService cfg = paymentConfigurationServiceProvider.getGatewayConfigurationService(tx.getOrderPayment().getGatewayType());
                        PaymentResponseDTO responseDTO = null;

                        if (PaymentType.CREDIT_CARD.equals(payment.getType())) {
                            // Handles the PCI-Compliant Scenario where you have an UNCONFIRMED CREDIT_CARD payment on the order.
                            // This can happen if you send the Credit Card directly to Broadleaf or you use a Digital Wallet solution like MasterPass.
                            // The Actual Credit Card PAN is stored in blSecurePU and will need to be sent to the Payment Gateway for processing.

                            PaymentRequestDTO s2sRequest = orderToPaymentRequestService.translatePaymentTransaction(payment.getAmount(), tx);
                            populateCreditCardOnRequest(s2sRequest, payment);
                            populateBillingAddressOnRequest(s2sRequest, payment);
                            populateCustomerOnRequest(s2sRequest, payment);

                            if (cfg.getConfiguration().isPerformAuthorizeAndCapture()) {
                                responseDTO = cfg.getTransactionService().authorizeAndCapture(s2sRequest);
                            } else {
                                responseDTO = cfg.getTransactionService().authorize(s2sRequest);
                            }

                        } else {
                            // This handles the THIRD_PARTY_ACCOUNT scenario (like PayPal Express Checkout) where
                            // the transaction just needs to be confirmed with the Gateway

                            responseDTO = cfg.getTransactionConfirmationService()
                                .confirmTransaction(orderToPaymentRequestService.translatePaymentTransaction(payment.getAmount(), tx));
                        }

                        if (responseDTO == null) {
                            String msg = "Unable to Confirm/Authorize the UNCONFIRMED Transaction with id: " + tx.getId() + ". " +
                                    "The ResponseDTO returned from the Gateway was null. Please check your implementation";
                            LOG.error(msg);
                            throw new CheckoutException(msg, context.getSeedData());
                        }

                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Transaction Confirmation Raw Response: " +  responseDTO.getRawResponse());
                        }

                        if (responseDTO.getAmount() == null || responseDTO.getPaymentTransactionType() == null) {
                            //Log an error, an exception will get thrown later as the payments won't add up.
                            LOG.error("The ResponseDTO returned from the Gateway does not contain either an Amount or Payment Transaction Type. " +
                                    "Please check your implementation");
                        }

                        // Create a new transaction that references its parent UNCONFIRMED transaction.
                        PaymentTransaction transaction = orderPaymentService.createTransaction();
                        transaction.setAmount(responseDTO.getAmount());
                        transaction.setRawResponse(responseDTO.getRawResponse());
                        transaction.setSuccess(responseDTO.isSuccessful());
                        transaction.setType(responseDTO.getPaymentTransactionType());
                        transaction.setParentTransaction(tx);
                        transaction.setOrderPayment(payment);
                        transaction.setAdditionalFields(responseDTO.getResponseMap());
                        additionalTransactions.put(payment, transaction);

                        if (responseDTO.isSuccessful()) {
                            additionalConfirmedTransactions.put(payment, transaction.getType());
                        } else {
                            failedTransactions.add(responseDTO);
                        }

                    } else if (PaymentTransactionType.AUTHORIZE.equals(tx.getType()) ||
                            PaymentTransactionType.AUTHORIZE_AND_CAPTURE.equals(tx.getType())) {
                        // After each transaction is confirmed, associate the new list of confirmed transactions to the rollback state. This has the added
                        // advantage of being able to invoke the rollback handler if there is an exception thrown at some point while confirming multiple
                        // transactions. This is outside of the transaction confirmation block in order to capture transactions
                        // that were already confirmed prior to this activity running
                        confirmedTransactions.add(tx);
                    }
                }
            }
        }
       
        // Add the new transactions to this payment (failed and confirmed) These need to be saved on the order payment
        // regardless of an error in the workflow later.
        for (OrderPayment payment : order.getPayments()) {
            if (additionalTransactions.containsKey(payment)) {
                PaymentTransactionType confirmedType = null;
                if (additionalConfirmedTransactions.containsKey(payment)) {
                    confirmedType = additionalConfirmedTransactions.get(payment);
                }

                payment.addTransaction(additionalTransactions.get(payment));
                payment = orderPaymentService.save(payment);

                if (confirmedType != null) {
                    List<PaymentTransaction> types = payment.getTransactionsForType(confirmedType);
                    if (types.size() == 1) {
                        confirmedTransactions.add(types.get(0));
                    } else {
                        throw new IllegalArgumentException("There should only be one AUTHORIZE or AUTHORIZE_AND_CAPTURE transaction." +
                                "There are more than one confirmed payment transactions for Order Payment:" + payment.getId() );
                    }
                }
            }
        }

        // Once all transactions have been confirmed, add them to the rollback state.
        // If an exception is thrown after this, the confirmed transactions will need to be voided or reversed
        // (based on the implementation requirements of the Gateway)
        rollbackState.put(CONFIRMED_TRANSACTIONS, confirmedTransactions);
        ActivityStateManagerImpl.getStateManager().registerState(this, context, getRollbackHandler(), rollbackState);

        //Handle the failed transactions (default implementation is to throw a new CheckoutException)
        if (!failedTransactions.isEmpty()) {
            handleUnsuccessfulTransactions(failedTransactions, context);
        }

        // Add authorize and authorize_and_capture; there should only be one or the other in the payment
        Money paymentSum = new Money(BigDecimal.ZERO);
        for (OrderPayment payment : order.getPayments()) {
            if (payment.isActive()) {
                paymentSum = paymentSum.add(payment.getSuccessfulTransactionAmountForType(PaymentTransactionType.AUTHORIZE))
                               .add(payment.getSuccessfulTransactionAmountForType(PaymentTransactionType.AUTHORIZE_AND_CAPTURE));
            }
        }
       
        if (paymentSum.lessThan(order.getTotal())) {
            throw new IllegalArgumentException("There are not enough payments to pay for the total order. The sum of " +
                    "the payments is " + paymentSum.getAmount().toPlainString() + " and the order total is " + order.getTotal().getAmount().toPlainString());
        }
       
        // There should also likely be something that says whether the payment was successful or not and this should check
        // that as well. Currently there isn't really a concept for that
        return context;
View Full Code Here

        if (config == null) {
            throw new IllegalArgumentException("Config service cannot be null");
        }
       
        Long orderId = Long.parseLong(responseDTO.getOrderId());
        Order order = orderService.findOrderById(orderId);
       
        if (!OrderStatus.IN_PROCESS.equals(order.getStatus()) && !OrderStatus.CSR_OWNED.equals(order.getStatus())) {
            throw new IllegalArgumentException("Cannot apply another payment to an Order that is not IN_PROCESS or CSR_OWNED");
        }
       
        Customer customer = order.getCustomer();
        if (customer.isAnonymous()) {
            GatewayCustomerDTO<PaymentResponseDTO> gatewayCustomer = responseDTO.getCustomer();
            if (StringUtils.isEmpty(customer.getFirstName()) && gatewayCustomer != null) {
                customer.setFirstName(gatewayCustomer.getFirstName());
            }
            if (StringUtils.isEmpty(customer.getLastName()) && gatewayCustomer != null) {
                customer.setLastName(gatewayCustomer.getLastName());
            }
            if (StringUtils.isEmpty(customer.getEmailAddress()) && gatewayCustomer != null) {
                customer.setEmailAddress(gatewayCustomer.getEmail());
            }
        }

        // If the gateway sends back an email address and the order does not contain one, set it.
        GatewayCustomerDTO<PaymentResponseDTO> gatewayCustomer = responseDTO.getCustomer();
        if (order.getEmailAddress() == null && gatewayCustomer != null) {
            order.setEmailAddress(gatewayCustomer.getEmail());
        }

        // If the gateway sends back Shipping Information, we will save that to the first shippable fulfillment group.
        populateShippingInfo(responseDTO, order);

        // ALWAYS create a new order payment for the payment that comes in. Invalid payments should be cleaned up by
        // invoking {@link #markPaymentAsInvalid}.
        OrderPayment payment = orderPaymentService.create();
        payment.setType(responseDTO.getPaymentType());
        payment.setPaymentGatewayType(responseDTO.getPaymentGatewayType());
        payment.setAmount(responseDTO.getAmount());

        // If this gateway does not support multiple payments then mark all of the existing payments
        // as invalid before adding the new one
        List<OrderPayment> paymentsToInvalidate = new ArrayList<OrderPayment>();
        Address tempBillingAddress = null;
        if (!config.handlesMultiplePayments()) {
            PaymentGatewayType gateway = config.getGatewayType();
            for (OrderPayment p : order.getPayments()) {
                // A Payment on the order will be invalidated if:
                // - It's a temporary order payment: There may be a temporary Order Payment on the Order (e.g. to save the billing address)
                // - The payment being added is a Final Payment and there already exists a Final Payment
                // - The payment being added has the same gateway type of an existing one.
                if (PaymentGatewayType.TEMPORARY.equals(p.getGatewayType()) ||
                        (p.isFinalPayment() && payment.isFinalPayment()) ||
                        (p.getGatewayType() != null && p.getGatewayType().equals(gateway))) {

                    paymentsToInvalidate.add(p);

                    if (PaymentType.CREDIT_CARD.equals(p.getType()) &&
                            PaymentGatewayType.TEMPORARY.equals(p.getGatewayType()) ) {
                        tempBillingAddress = p.getBillingAddress();
                    }
                }
            }
        }

        for (OrderPayment invalid : paymentsToInvalidate) {
            order.getPayments().remove(invalid);
            markPaymentAsInvalid(invalid.getId());
        }

        // The billing address that will be saved on the order will be parsed off the
        // Response DTO sent back from the Gateway as it may have Address Verification or Standardization.
View Full Code Here

    protected Processor pricingWorkflow;

    public Order executePricing(Order order) throws PricingException {
        try {
            ProcessContext<Order> context = (ProcessContext<Order>) pricingWorkflow.doActivities(order);
            Order response = context.getSeedData();

            return response;
        } catch (WorkflowException e) {
            throw new PricingException("Unable to execute pricing for order -- id: " + order.getId(), e);
        }
View Full Code Here

        orderPaymentService.delete(payment);
    }

    @Override
    public String initiateCheckout(Long orderId) throws Exception{
        Order order = orderService.findOrderById(orderId, true);
        if (order == null || order instanceof NullOrderImpl) {
            throw new IllegalArgumentException("Could not order with id " + orderId);
        }
       
        CheckoutResponse response;

        try {
            response = checkoutService.performCheckout(order);
        } catch (CheckoutException e) {
            throw new Exception(e);
        }

        if (response.getOrder().getOrderNumber() == null) {
            LOG.error("Order Number for Order ID: " + order.getId() + " is null.");
        }

        return response.getOrder().getOrderNumber();
    }
View Full Code Here

TOP

Related Classes of org.broadleafcommerce.core.order.domain.Order

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.