Search in sources :

Example 1 with ShoppingCartItem

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

the class ShoppingOrderController method displayCheckout.

@SuppressWarnings("unused")
@RequestMapping("/checkout.html")
public String displayCheckout(@CookieValue("cart") String cookie, Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Customer customer = (Customer) request.getSession().getAttribute(Constants.CUSTOMER);
    model.addAttribute("googleMapsKey", googleMapsKey);
    /**
     * Shopping cart
     *
     * ShoppingCart should be in the HttpSession
     * Otherwise the cart id is in the cookie
     * Otherwise the customer is in the session and a cart exist in the DB
     * Else -> Nothing to display
     */
    // check if an existing order exist
    ShopOrder order = null;
    order = super.getSessionAttribute(Constants.ORDER, request);
    // Get the cart from the DB
    String shoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
    com.salesmanager.core.model.shoppingcart.ShoppingCart cart = null;
    if (StringUtils.isBlank(shoppingCartCode)) {
        if (cookie == null) {
            // session expired and cookie null, nothing to do
            return "redirect:/shop/cart/shoppingCart.html";
        }
        String[] merchantCookie = cookie.split("_");
        String merchantStoreCode = merchantCookie[0];
        if (!merchantStoreCode.equals(store.getCode())) {
            return "redirect:/shop/cart/shoppingCart.html";
        }
        shoppingCartCode = merchantCookie[1];
    }
    cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
    if (cart == null && customer != null) {
        cart = shoppingCartFacade.getShoppingCartModel(customer, store);
    }
    boolean allAvailables = true;
    boolean requiresShipping = false;
    boolean freeShoppingCart = true;
    // Filter items, delete unavailable
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> availables = new HashSet<ShoppingCartItem>();
    if (cart == null) {
        return "redirect:/shop/cart/shoppingCart.html";
    }
    // Take out items no more available
    Set<com.salesmanager.core.model.shoppingcart.ShoppingCartItem> items = cart.getLineItems();
    for (com.salesmanager.core.model.shoppingcart.ShoppingCartItem item : items) {
        Long id = item.getProduct().getId();
        Product p = productService.getById(id);
        if (p.isAvailable()) {
            availables.add(item);
        } else {
            allAvailables = false;
        }
        FinalPrice finalPrice = pricingService.calculateProductPrice(p);
        if (finalPrice.getFinalPrice().longValue() > 0) {
            freeShoppingCart = false;
        }
        if (p.isProductShipeable()) {
            requiresShipping = true;
        }
    }
    cart.setLineItems(availables);
    if (!allAvailables) {
        shoppingCartFacade.saveOrUpdateShoppingCart(cart);
    }
    super.setSessionAttribute(Constants.SHOPPING_CART, cart.getShoppingCartCode(), request);
    if (shoppingCartCode == null && cart == null) {
        // error
        return "redirect:/shop/cart/shoppingCart.html";
    }
    if (customer != null) {
        if (cart.getCustomerId() != customer.getId().longValue()) {
            return "redirect:/shop/shoppingCart.html";
        }
    } else {
        customer = orderFacade.initEmptyCustomer(store);
        AnonymousCustomer anonymousCustomer = (AnonymousCustomer) request.getAttribute(Constants.ANONYMOUS_CUSTOMER);
        if (anonymousCustomer != null && anonymousCustomer.getBilling() != null) {
            Billing billing = customer.getBilling();
            billing.setCity(anonymousCustomer.getBilling().getCity());
            Map<String, Country> countriesMap = countryService.getCountriesMap(language);
            Country anonymousCountry = countriesMap.get(anonymousCustomer.getBilling().getCountry());
            if (anonymousCountry != null) {
                billing.setCountry(anonymousCountry);
            }
            Map<String, Zone> zonesMap = zoneService.getZones(language);
            Zone anonymousZone = zonesMap.get(anonymousCustomer.getBilling().getZone());
            if (anonymousZone != null) {
                billing.setZone(anonymousZone);
            }
            if (anonymousCustomer.getBilling().getPostalCode() != null) {
                billing.setPostalCode(anonymousCustomer.getBilling().getPostalCode());
            }
            customer.setBilling(billing);
        }
    }
    if (CollectionUtils.isEmpty(items)) {
        return "redirect:/shop/shoppingCart.html";
    }
    if (order == null) {
        // TODO
        order = orderFacade.initializeOrder(store, customer, cart, language);
    }
    /**
     * hook for displaying or not delivery address configuration
     */
    ShippingMetaData shippingMetaData = shippingService.getShippingMetaData(store);
    model.addAttribute("shippingMetaData", shippingMetaData);
    /**
     * shipping *
     */
    ShippingQuote quote = null;
    if (requiresShipping) {
        // System.out.println("** Berfore default shipping quote **");
        // Get all applicable shipping quotes
        quote = orderFacade.getShippingQuote(customer, cart, order, store, language);
        model.addAttribute("shippingQuote", quote);
    }
    if (quote != null) {
        String shippingReturnCode = quote.getShippingReturnCode();
        if (StringUtils.isBlank(shippingReturnCode) || shippingReturnCode.equals(ShippingQuote.NO_POSTAL_CODE)) {
            if (order.getShippingSummary() == null) {
                ShippingSummary summary = orderFacade.getShippingSummary(quote, store, language);
                order.setShippingSummary(summary);
                // TODO DTO
                request.getSession().setAttribute(Constants.SHIPPING_SUMMARY, summary);
            }
            if (order.getSelectedShippingOption() == null) {
                order.setSelectedShippingOption(quote.getSelectedShippingOption());
            }
            // save quotes in HttpSession
            List<ShippingOption> options = quote.getShippingOptions();
            // TODO DTO
            request.getSession().setAttribute(Constants.SHIPPING_OPTIONS, options);
            if (!CollectionUtils.isEmpty(options)) {
                for (ShippingOption shipOption : options) {
                    StringBuilder moduleName = new StringBuilder();
                    moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                    String carrier = messages.getMessage(moduleName.toString(), locale);
                    String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
                    shipOption.setDescription(carrier);
                    shipOption.setNote(note);
                    // option name
                    if (!StringUtils.isBlank(shipOption.getOptionCode())) {
                        // try to get the translate
                        StringBuilder optionCodeBuilder = new StringBuilder();
                        try {
                            optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
                            String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                            shipOption.setOptionName(optionName);
                        } catch (Exception e) {
                            // label not found
                            LOGGER.warn("displayCheckout No shipping code found for " + optionCodeBuilder.toString());
                        }
                    }
                }
            }
        }
        if (quote.getDeliveryAddress() != null) {
            ReadableCustomerDeliveryAddressPopulator addressPopulator = new ReadableCustomerDeliveryAddressPopulator();
            addressPopulator.setCountryService(countryService);
            addressPopulator.setZoneService(zoneService);
            ReadableDelivery deliveryAddress = new ReadableDelivery();
            addressPopulator.populate(quote.getDeliveryAddress(), deliveryAddress, store, language);
            model.addAttribute("deliveryAddress", deliveryAddress);
            super.setSessionAttribute(Constants.KEY_SESSION_ADDRESS, deliveryAddress, request);
        }
        // get shipping countries
        List<Country> shippingCountriesList = orderFacade.getShipToCountry(store, language);
        model.addAttribute("countries", shippingCountriesList);
    } else {
        // get all countries
        List<Country> countries = countryService.getCountries(language);
        model.addAttribute("countries", countries);
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_MODULE_CONFIGURED)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", messages.getMessage(quote.getShippingReturnCode(), locale, quote.getShippingReturnCode()));
    }
    if (quote != null && !StringUtils.isBlank(quote.getQuoteError())) {
        LOGGER.error("Shipping quote error " + quote.getQuoteError());
        model.addAttribute("errorMessages", quote.getQuoteError());
    }
    if (quote != null && quote.getShippingReturnCode() != null && quote.getShippingReturnCode().equals(ShippingQuote.NO_SHIPPING_TO_SELECTED_COUNTRY)) {
        LOGGER.error("Shipping quote error " + quote.getShippingReturnCode());
        model.addAttribute("errorMessages", quote.getShippingReturnCode());
    }
    /**
     * end shipping *
     */
    // get payment methods
    List<PaymentMethod> paymentMethods = paymentService.getAcceptedPaymentMethods(store);
    // not free and no payment methods
    if (CollectionUtils.isEmpty(paymentMethods) && !freeShoppingCart) {
        LOGGER.error("No payment method configured");
        model.addAttribute("errorMessages", messages.getMessage("payment.not.configured", locale, "No payments configured"));
    }
    if (!CollectionUtils.isEmpty(paymentMethods)) {
        // select default payment method
        PaymentMethod defaultPaymentSelected = null;
        for (PaymentMethod paymentMethod : paymentMethods) {
            if (paymentMethod.isDefaultSelected()) {
                defaultPaymentSelected = paymentMethod;
                break;
            }
        }
        if (defaultPaymentSelected == null) {
            // forced default selection
            defaultPaymentSelected = paymentMethods.get(0);
            defaultPaymentSelected.setDefaultSelected(true);
        }
        order.setDefaultPaymentMethodCode(defaultPaymentSelected.getPaymentMethodCode());
    }
    // readable shopping cart items for order summary box
    ShoppingCartData shoppingCart = shoppingCartFacade.getShoppingCartData(cart, language);
    model.addAttribute("cart", shoppingCart);
    order.setCartCode(shoppingCart.getCode());
    // order total
    OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
    order.setOrderTotalSummary(orderTotalSummary);
    // if order summary has to be re-used
    super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
    // display hacks
    if (!StringUtils.isBlank(googleMapsKey)) {
        model.addAttribute("fieldDisabled", "true");
        model.addAttribute("cssClass", "");
    } else {
        model.addAttribute("fieldDisabled", "false");
        model.addAttribute("cssClass", "required");
    }
    model.addAttribute("order", order);
    model.addAttribute("paymentMethods", paymentMethods);
    /**
     * template *
     */
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.checkout).append(".").append(store.getStoreTemplate());
    return template.toString();
}
Also used : AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Product(com.salesmanager.core.model.catalog.product.Product) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) Language(com.salesmanager.core.model.reference.language.Language) ReadableCustomerDeliveryAddressPopulator(com.salesmanager.shop.populator.customer.ReadableCustomerDeliveryAddressPopulator) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) HashSet(java.util.HashSet) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) Zone(com.salesmanager.core.model.reference.zone.Zone) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ShippingMetaData(com.salesmanager.core.model.shipping.ShippingMetaData) ShippingQuote(com.salesmanager.core.model.shipping.ShippingQuote) Billing(com.salesmanager.core.model.common.Billing) Country(com.salesmanager.core.model.reference.country.Country) PaymentMethod(com.salesmanager.core.model.payments.PaymentMethod) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with ShoppingCartItem

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

the class ShoppingOrderController method calculateOrderTotal.

/**
 * Calculates the order total following price variation like changing a shipping option
 * @param order
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/calculateOrderTotal.json" }, method = RequestMethod.POST)
@ResponseBody
public ReadableShopOrder calculateOrderTotal(@ModelAttribute(value = "order") ShopOrder order, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
    Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
    ReadableShopOrder readableOrder = new ReadableShopOrder();
    try {
        // re-generate cart
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        ReadableShopOrderPopulator populator = new ReadableShopOrderPopulator();
        populator.populate(order, readableOrder, store, language);
        ReadableDelivery readableDelivery = super.getSessionAttribute(Constants.KEY_SESSION_ADDRESS, request);
        if (order.getSelectedShippingOption() != null) {
            ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute(Constants.SHIPPING_SUMMARY);
            @SuppressWarnings("unchecked") List<ShippingOption> options = (List<ShippingOption>) request.getSession().getAttribute(Constants.SHIPPING_OPTIONS);
            // for total calculation
            order.setShippingSummary(summary);
            ReadableShippingSummary readableSummary = new ReadableShippingSummary();
            ReadableShippingSummaryPopulator readableSummaryPopulator = new ReadableShippingSummaryPopulator();
            readableSummaryPopulator.setPricingService(pricingService);
            readableSummaryPopulator.populate(summary, readableSummary, store, language);
            // override summary
            readableSummary.setDelivery(readableDelivery);
            if (!CollectionUtils.isEmpty(options)) {
                // get submitted shipping option
                ShippingOption quoteOption = null;
                ShippingOption selectedOption = order.getSelectedShippingOption();
                // check if selectedOption exist
                for (ShippingOption shipOption : options) {
                    StringBuilder moduleName = new StringBuilder();
                    moduleName.append("module.shipping.").append(shipOption.getShippingModuleCode());
                    String carrier = messages.getMessage(moduleName.toString(), locale);
                    String note = messages.getMessage(moduleName.append(".note").toString(), locale, "");
                    shipOption.setNote(note);
                    shipOption.setDescription(carrier);
                    if (!StringUtils.isBlank(shipOption.getOptionId()) && shipOption.getOptionId().equals(selectedOption.getOptionId())) {
                        quoteOption = shipOption;
                    }
                    // option name
                    if (!StringUtils.isBlank(shipOption.getOptionCode())) {
                        // try to get the translate
                        StringBuilder optionCodeBuilder = new StringBuilder();
                        try {
                            // optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode()).append(".").append(shipOption.getOptionCode());
                            optionCodeBuilder.append("module.shipping.").append(shipOption.getShippingModuleCode());
                            String optionName = messages.getMessage(optionCodeBuilder.toString(), locale);
                            shipOption.setOptionName(optionName);
                        } catch (Exception e) {
                            // label not found
                            LOGGER.warn("calculateOrderTotal No shipping code found for " + optionCodeBuilder.toString());
                        }
                    }
                }
                if (quoteOption == null) {
                    quoteOption = options.get(0);
                }
                readableSummary.setSelectedShippingOption(quoteOption);
                readableSummary.setShippingOptions(options);
                summary.setShippingOption(quoteOption.getOptionId());
                summary.setShippingOptionCode(quoteOption.getOptionCode());
                summary.setShipping(quoteOption.getOptionPrice());
                // override with new summary
                order.setShippingSummary(summary);
                @SuppressWarnings("unchecked") Map<String, String> informations = (Map<String, String>) request.getSession().getAttribute("SHIPPING_INFORMATIONS");
                readableSummary.setQuoteInformations(informations);
            }
            // TODO readable address format
            readableOrder.setShippingSummary(readableSummary);
            readableOrder.setDelivery(readableDelivery);
        }
        // set list of shopping cart items for core price calculation
        List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(cart.getLineItems());
        order.setShoppingCartItems(items);
        order.setCartCode(shoppingCartCode);
        // order total calculation
        OrderTotalSummary orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
        super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
        ReadableOrderTotalPopulator totalPopulator = new ReadableOrderTotalPopulator();
        totalPopulator.setMessages(messages);
        totalPopulator.setPricingService(pricingService);
        List<ReadableOrderTotal> subtotals = new ArrayList<ReadableOrderTotal>();
        for (OrderTotal total : orderTotalSummary.getTotals()) {
            if (total.getOrderTotalCode() == null || !total.getOrderTotalCode().equals("order.total.total")) {
                ReadableOrderTotal t = new ReadableOrderTotal();
                totalPopulator.populate(total, t, store, language);
                subtotals.add(t);
            } else {
                // grand total
                ReadableOrderTotal ot = new ReadableOrderTotal();
                totalPopulator.populate(total, ot, store, language);
                readableOrder.setGrandTotal(ot.getTotal());
            }
        }
        readableOrder.setSubTotals(subtotals);
    } catch (Exception e) {
        LOGGER.error("Error while getting shipping quotes", e);
        readableOrder.setErrorMessage(messages.getMessage("message.error", locale));
    }
    return readableOrder;
}
Also used : OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) ReadableShippingSummaryPopulator(com.salesmanager.shop.populator.order.ReadableShippingSummaryPopulator) Language(com.salesmanager.core.model.reference.language.Language) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) List(java.util.List) ArrayList(java.util.ArrayList) ReadableShopOrderPopulator(com.salesmanager.shop.populator.order.ReadableShopOrderPopulator) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) ReadableDelivery(com.salesmanager.shop.model.customer.ReadableDelivery) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShippingOption(com.salesmanager.core.model.shipping.ShippingOption) ReadableShippingSummary(com.salesmanager.shop.model.order.shipping.ReadableShippingSummary) ReadableOrderTotalPopulator(com.salesmanager.shop.populator.order.ReadableOrderTotalPopulator) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ReadableOrderTotal(com.salesmanager.shop.model.order.total.ReadableOrderTotal) OrderTotal(com.salesmanager.core.model.order.OrderTotal) Map(java.util.Map) HashMap(java.util.HashMap) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with ShoppingCartItem

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

the class ShoppingOrderPaymentController method paymentAction.

/**
 * Recalculates shipping and tax following a change in country or province
 *
 * @param order
 * @param request
 * @param response
 * @param locale
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/order/payment/{action}/{paymentmethod}.html" }, method = RequestMethod.POST)
@ResponseBody
public String paymentAction(@Valid @ModelAttribute(value = "order") ShopOrder order, @PathVariable String action, @PathVariable String paymentmethod, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    Language language = (Language) request.getAttribute("LANGUAGE");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    String shoppingCartCode = getSessionAttribute(Constants.SHOPPING_CART, request);
    Validate.notNull(shoppingCartCode, "shoppingCartCode does not exist in the session");
    AjaxResponse ajaxResponse = new AjaxResponse();
    try {
        com.salesmanager.core.model.shoppingcart.ShoppingCart cart = shoppingCartFacade.getShoppingCartModel(shoppingCartCode, store);
        Set<ShoppingCartItem> items = cart.getLineItems();
        List<ShoppingCartItem> cartItems = new ArrayList<ShoppingCartItem>(items);
        order.setShoppingCartItems(cartItems);
        // validate order first
        Map<String, String> messages = new TreeMap<String, String>();
        orderFacade.validateOrder(order, new BeanPropertyBindingResult(order, "order"), messages, store, locale);
        if (CollectionUtils.isNotEmpty(messages.values())) {
            for (String key : messages.keySet()) {
                String value = messages.get(key);
                ajaxResponse.addValidationMessage(key, value);
            }
            ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_VALIDATION_FAILED);
            return ajaxResponse.toJSONString();
        }
        IntegrationConfiguration config = paymentService.getPaymentConfiguration(order.getPaymentModule(), store);
        IntegrationModule integrationModule = paymentService.getPaymentMethodByCode(store, order.getPaymentModule());
        // OrderTotalSummary orderTotalSummary =
        // orderFacade.calculateOrderTotal(store, order, language);
        OrderTotalSummary orderTotalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
        if (orderTotalSummary == null) {
            orderTotalSummary = orderFacade.calculateOrderTotal(store, order, language);
            super.setSessionAttribute(Constants.ORDER_SUMMARY, orderTotalSummary, request);
        }
        ShippingSummary summary = (ShippingSummary) request.getSession().getAttribute("SHIPPING_SUMMARY");
        if (summary != null) {
            order.setShippingSummary(summary);
        }
        if (action.equals(INIT_ACTION)) {
            if (paymentmethod.equals("PAYPAL")) {
                try {
                    PaymentModule module = paymentService.getPaymentModule("paypal-express-checkout");
                    PayPalExpressCheckoutPayment p = (PayPalExpressCheckoutPayment) module;
                    PaypalPayment payment = new PaypalPayment();
                    payment.setCurrency(store.getCurrency());
                    Transaction transaction = p.initPaypalTransaction(store, cartItems, orderTotalSummary, payment, config, integrationModule);
                    transactionService.create(transaction);
                    super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
                    StringBuilder urlAppender = new StringBuilder();
                    urlAppender.append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_REGULAR"));
                    urlAppender.append(transaction.getTransactionDetails().get("TOKEN"));
                    if (config.getEnvironment().equals(com.salesmanager.core.business.constants.Constants.PRODUCTION_ENVIRONMENT)) {
                        StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_PRODUCTION")).append(urlAppender.toString());
                        ajaxResponse.addEntry("url", url.toString());
                    } else {
                        StringBuilder url = new StringBuilder().append(coreConfiguration.getProperty("PAYPAL_EXPRESSCHECKOUT_SANDBOX")).append(urlAppender.toString());
                        ajaxResponse.addEntry("url", url.toString());
                    }
                    // keep order in session when user comes back from pp
                    super.setSessionAttribute(Constants.ORDER, order, request);
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
                } catch (Exception e) {
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
                }
            } else if (paymentmethod.equals("stripe3")) {
                try {
                    PaymentModule module = paymentService.getPaymentModule(paymentmethod);
                    Stripe3Payment p = (Stripe3Payment) module;
                    PaypalPayment payment = new PaypalPayment();
                    payment.setCurrency(store.getCurrency());
                    Transaction transaction = p.initTransaction(store, null, orderTotalSummary.getTotal(), null, config, integrationModule);
                    transactionService.create(transaction);
                    super.setSessionAttribute(Constants.INIT_TRANSACTION_KEY, transaction, request);
                    // keep order in session when user comes back from pp
                    super.setSessionAttribute(Constants.ORDER, order, request);
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_OPERATION_COMPLETED);
                    ajaxResponse.setDataMap(transaction.getTransactionDetails());
                } catch (Exception e) {
                    ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error while performing payment action " + action + " for payment method " + paymentmethod, e);
        ajaxResponse.setErrorMessage(e);
        ajaxResponse.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
    }
    return ajaxResponse.toJSONString();
}
Also used : Stripe3Payment(com.salesmanager.core.business.modules.integration.payment.impl.Stripe3Payment) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ArrayList(java.util.ArrayList) PayPalExpressCheckoutPayment(com.salesmanager.core.business.modules.integration.payment.impl.PayPalExpressCheckoutPayment) PaypalPayment(com.salesmanager.core.model.payments.PaypalPayment) PaymentModule(com.salesmanager.core.modules.integration.payment.model.PaymentModule) Language(com.salesmanager.core.model.reference.language.Language) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) IntegrationModule(com.salesmanager.core.model.system.IntegrationModule) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) AjaxResponse(com.salesmanager.core.business.utils.ajax.AjaxResponse) IntegrationConfiguration(com.salesmanager.core.model.system.IntegrationConfiguration) TreeMap(java.util.TreeMap) Transaction(com.salesmanager.core.model.payments.Transaction) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with ShoppingCartItem

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

the class PayPalExpressCheckoutPayment method initPaypalTransaction.

/*	@Override
	public Transaction capture(MerchantStore store, Customer customer,
			List<ShoppingCartItem> items, BigDecimal amount, Payment payment, Transaction transaction,
			IntegrationConfiguration configuration, IntegrationModule module)
			throws IntegrationException {
		
		com.salesmanager.core.business.payments.model.PaypalPayment paypalPayment = (com.salesmanager.core.business.payments.model.PaypalPayment)payment;
		Validate.notNull(paypalPayment.getPaymentToken(), "A paypal payment token is required to process this transaction");
		
		return processTransaction(store, customer, items, amount, paypalPayment, configuration, module);
		
	}*/
public Transaction initPaypalTransaction(MerchantStore store, List<ShoppingCartItem> items, OrderTotalSummary summary, Payment payment, IntegrationConfiguration configuration, IntegrationModule module) throws IntegrationException {
    Validate.notNull(configuration, "Configuration must not be null");
    Validate.notNull(payment, "Payment must not be null");
    Validate.notNull(summary, "OrderTotalSummary must not be null");
    try {
        PaymentDetailsType paymentDetails = new PaymentDetailsType();
        if (configuration.getIntegrationKeys().get("transaction").equalsIgnoreCase(TransactionType.AUTHORIZECAPTURE.name())) {
            paymentDetails.setPaymentAction(urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType.SALE);
        } else {
            paymentDetails.setPaymentAction(urn.ebay.apis.eBLBaseComponents.PaymentActionCodeType.AUTHORIZATION);
        }
        List<PaymentDetailsItemType> lineItems = new ArrayList<PaymentDetailsItemType>();
        for (ShoppingCartItem cartItem : items) {
            PaymentDetailsItemType item = new PaymentDetailsItemType();
            BasicAmountType amt = new BasicAmountType();
            amt.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(payment.getCurrency().getCode()));
            amt.setValue(pricingService.getStringAmount(cartItem.getFinalPrice().getFinalPrice(), store));
            // itemsTotal = itemsTotal.add(cartItem.getSubTotal());
            int itemQuantity = cartItem.getQuantity();
            item.setQuantity(itemQuantity);
            item.setName(cartItem.getProduct().getProductDescription().getName());
            item.setAmount(amt);
            // System.out.println(pricingService.getStringAmount(cartItem.getSubTotal(), store));
            lineItems.add(item);
        }
        List<OrderTotal> orderTotals = summary.getTotals();
        BigDecimal tax = null;
        for (OrderTotal total : orderTotals) {
            if (total.getModule().equals(Constants.OT_SHIPPING_MODULE_CODE)) {
                BasicAmountType shipping = new BasicAmountType();
                shipping.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
                shipping.setValue(pricingService.getStringAmount(total.getValue(), store));
                // System.out.println(pricingService.getStringAmount(total.getValue(), store));
                paymentDetails.setShippingTotal(shipping);
            }
            if (total.getModule().equals(Constants.OT_HANDLING_MODULE_CODE)) {
                BasicAmountType handling = new BasicAmountType();
                handling.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
                handling.setValue(pricingService.getStringAmount(total.getValue(), store));
                // System.out.println(pricingService.getStringAmount(total.getValue(), store));
                paymentDetails.setHandlingTotal(handling);
            }
            if (total.getModule().equals(Constants.OT_TAX_MODULE_CODE)) {
                if (tax == null) {
                    tax = new BigDecimal("0");
                }
                tax = tax.add(total.getValue());
            }
        }
        if (tax != null) {
            BasicAmountType taxAmnt = new BasicAmountType();
            taxAmnt.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
            taxAmnt.setValue(pricingService.getStringAmount(tax, store));
            // System.out.println(pricingService.getStringAmount(tax, store));
            paymentDetails.setTaxTotal(taxAmnt);
        }
        BasicAmountType itemTotal = new BasicAmountType();
        itemTotal.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
        itemTotal.setValue(pricingService.getStringAmount(summary.getSubTotal(), store));
        paymentDetails.setItemTotal(itemTotal);
        paymentDetails.setPaymentDetailsItem(lineItems);
        BasicAmountType orderTotal = new BasicAmountType();
        orderTotal.setCurrencyID(urn.ebay.apis.eBLBaseComponents.CurrencyCodeType.fromValue(store.getCurrency().getCode()));
        orderTotal.setValue(pricingService.getStringAmount(summary.getTotal(), store));
        // System.out.println(pricingService.getStringAmount(itemsTotal, store));
        paymentDetails.setOrderTotal(orderTotal);
        List<PaymentDetailsType> paymentDetailsList = new ArrayList<PaymentDetailsType>();
        paymentDetailsList.add(paymentDetails);
        String baseScheme = store.getDomainName();
        String scheme = coreConfiguration.getProperty("SHOP_SCHEME");
        if (!StringUtils.isBlank(scheme)) {
            baseScheme = new StringBuilder().append(coreConfiguration.getProperty("SHOP_SCHEME", "http")).append("://").append(store.getDomainName()).toString();
        }
        StringBuilder RETURN_URL = new StringBuilder();
        RETURN_URL.append(baseScheme);
        if (!StringUtils.isBlank(baseScheme) && !baseScheme.endsWith(Constants.SLASH)) {
            RETURN_URL.append(Constants.SLASH);
        }
        RETURN_URL.append(coreConfiguration.getProperty("CONTEXT_PATH", "sm-shop"));
        SetExpressCheckoutRequestDetailsType setExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
        String returnUrl = RETURN_URL.toString() + new StringBuilder().append(Constants.SHOP_URI).append("/paypal/checkout").append(coreConfiguration.getProperty("URL_EXTENSION", ".html")).append("/success").toString();
        String cancelUrl = RETURN_URL.toString() + new StringBuilder().append(Constants.SHOP_URI).append("/paypal/checkout").append(coreConfiguration.getProperty("URL_EXTENSION", ".html")).append("/cancel").toString();
        setExpressCheckoutRequestDetails.setReturnURL(returnUrl);
        setExpressCheckoutRequestDetails.setCancelURL(cancelUrl);
        setExpressCheckoutRequestDetails.setPaymentDetails(paymentDetailsList);
        SetExpressCheckoutRequestType setExpressCheckoutRequest = new SetExpressCheckoutRequestType(setExpressCheckoutRequestDetails);
        setExpressCheckoutRequest.setVersion("104.0");
        SetExpressCheckoutReq setExpressCheckoutReq = new SetExpressCheckoutReq();
        setExpressCheckoutReq.setSetExpressCheckoutRequest(setExpressCheckoutRequest);
        String mode = "sandbox";
        String env = configuration.getEnvironment();
        if (Constants.PRODUCTION_ENVIRONMENT.equals(env)) {
            mode = "production";
        }
        Map<String, String> configurationMap = new HashMap<String, String>();
        configurationMap.put("mode", mode);
        configurationMap.put("acct1.UserName", configuration.getIntegrationKeys().get("username"));
        configurationMap.put("acct1.Password", configuration.getIntegrationKeys().get("api"));
        configurationMap.put("acct1.Signature", configuration.getIntegrationKeys().get("signature"));
        PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(configurationMap);
        SetExpressCheckoutResponseType setExpressCheckoutResponse = service.setExpressCheckout(setExpressCheckoutReq);
        String token = setExpressCheckoutResponse.getToken();
        String correlationID = setExpressCheckoutResponse.getCorrelationID();
        String ack = setExpressCheckoutResponse.getAck().getValue();
        if (!"Success".equals(ack)) {
            LOGGER.error("Wrong value from init transaction " + ack);
            throw new IntegrationException("Wrong paypal ack from init transaction " + ack);
        }
        Transaction transaction = new Transaction();
        transaction.setAmount(summary.getTotal());
        // transaction.setOrder(order);
        transaction.setTransactionDate(new Date());
        transaction.setTransactionType(TransactionType.INIT);
        transaction.setPaymentType(PaymentType.PAYPAL);
        transaction.getTransactionDetails().put("TOKEN", token);
        transaction.getTransactionDetails().put("CORRELATION", correlationID);
        return transaction;
    // redirect user to
    // https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-5LL13394G30048922
    } catch (Exception e) {
        e.printStackTrace();
        throw new IntegrationException(e);
    }
}
Also used : IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BasicAmountType(urn.ebay.apis.CoreComponentTypes.BasicAmountType) PayPalAPIInterfaceServiceService(urn.ebay.api.PayPalAPI.PayPalAPIInterfaceServiceService) BigDecimal(java.math.BigDecimal) Date(java.util.Date) ServiceException(com.salesmanager.core.business.exception.ServiceException) IntegrationException(com.salesmanager.core.modules.integration.IntegrationException) SetExpressCheckoutResponseType(urn.ebay.api.PayPalAPI.SetExpressCheckoutResponseType) Transaction(com.salesmanager.core.model.payments.Transaction) SetExpressCheckoutRequestDetailsType(urn.ebay.apis.eBLBaseComponents.SetExpressCheckoutRequestDetailsType) SetExpressCheckoutRequestType(urn.ebay.api.PayPalAPI.SetExpressCheckoutRequestType) PaymentDetailsType(urn.ebay.apis.eBLBaseComponents.PaymentDetailsType) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) PaymentDetailsItemType(urn.ebay.apis.eBLBaseComponents.PaymentDetailsItemType) OrderTotal(com.salesmanager.core.model.order.OrderTotal) SetExpressCheckoutReq(urn.ebay.api.PayPalAPI.SetExpressCheckoutReq)

Example 5 with ShoppingCartItem

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

the class ShoppingCartServiceImpl method getPopulatedShoppingCart.

/*	@Override
	@Transactional
	public ShoppingCart getByCustomer(final Customer customer) throws ServiceException {

		try {
			List<ShoppingCart> 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 {
    try {
        boolean cartIsObsolete = false;
        if (shoppingCart != null) {
            Set<ShoppingCartItem> items = shoppingCart.getLineItems();
            if (items == null || items.size() == 0) {
                shoppingCart.setObsolete(true);
                return shoppingCart;
            }
            // HashSet<ShoppingCartItem>();
            for (ShoppingCartItem item : items) {
                LOGGER.debug("Populate item " + item.getId());
                getPopulatedItem(item);
                LOGGER.debug("Obsolete item ? " + item.isObsolete());
                if (item.isObsolete()) {
                    cartIsObsolete = true;
                }
            }
            // shoppingCart.setLineItems(shoppingCartItems);
            Set<ShoppingCartItem> refreshedItems = new HashSet<>(items);
            // if (refreshCart) {
            shoppingCart.setLineItems(refreshedItems);
            update(shoppingCart);
            if (cartIsObsolete) {
                shoppingCart.setObsolete(true);
            }
            return shoppingCart;
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        throw new ServiceException(e);
    }
    return shoppingCart;
}
Also used : ServiceException(com.salesmanager.core.business.exception.ServiceException) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ServiceException(com.salesmanager.core.business.exception.ServiceException) HashSet(java.util.HashSet) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

ShoppingCartItem (com.salesmanager.core.model.shoppingcart.ShoppingCartItem)24 ArrayList (java.util.ArrayList)15 OrderTotalSummary (com.salesmanager.core.model.order.OrderTotalSummary)11 ServiceException (com.salesmanager.core.business.exception.ServiceException)9 ShippingSummary (com.salesmanager.core.model.shipping.ShippingSummary)9 Product (com.salesmanager.core.model.catalog.product.Product)7 HashMap (java.util.HashMap)7 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)7 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)6 Language (com.salesmanager.core.model.reference.language.Language)6 FinalPrice (com.salesmanager.core.model.catalog.product.price.FinalPrice)5 OrderTotal (com.salesmanager.core.model.order.OrderTotal)5 PersistableCustomer (com.salesmanager.shop.model.customer.PersistableCustomer)5 ShopOrder (com.salesmanager.shop.model.order.ShopOrder)5 OrderSummary (com.salesmanager.core.model.order.OrderSummary)4 ShippingOption (com.salesmanager.core.model.shipping.ShippingOption)4 ShoppingCart (com.salesmanager.core.model.shoppingcart.ShoppingCart)4 ReadableDelivery (com.salesmanager.shop.model.customer.ReadableDelivery)4 ReadableShopOrder (com.salesmanager.shop.model.order.ReadableShopOrder)4 ReadableShippingSummary (com.salesmanager.shop.model.order.shipping.ReadableShippingSummary)4