Search in sources :

Example 36 with ShoppingCart

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

the class OrderPaymentApi method init.

@RequestMapping(value = { "/auth/cart/{code}/payment/init" }, method = RequestMethod.POST)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableTransaction init(@Valid @RequestBody PersistablePayment payment, @PathVariable String code, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        Principal principal = request.getUserPrincipal();
        String userName = principal.getName();
        Customer customer = customerService.getByNick(userName);
        if (customer == null) {
            response.sendError(401, "Error while initializing the payment customer not authorized");
            return null;
        }
        ShoppingCart cart = shoppingCartService.getByCode(code, merchantStore);
        if (cart == null) {
            throw new ResourceNotFoundException("Cart code " + code + " does not exist");
        }
        if (cart.getCustomerId() == null) {
            response.sendError(404, "Cart code " + code + " does not exist for exist for user " + userName);
            return null;
        }
        if (cart.getCustomerId().longValue() != customer.getId().longValue()) {
            response.sendError(404, "Cart code " + code + " does not exist for exist for user " + userName);
            return null;
        }
        PersistablePaymentPopulator populator = new PersistablePaymentPopulator();
        populator.setPricingService(pricingService);
        Payment paymentModel = new Payment();
        populator.populate(payment, paymentModel, merchantStore, language);
        Transaction transactionModel = paymentService.initTransaction(customer, paymentModel, merchantStore);
        ReadableTransaction transaction = new ReadableTransaction();
        ReadableTransactionPopulator trxPopulator = new ReadableTransactionPopulator();
        trxPopulator.setOrderService(orderService);
        trxPopulator.setPricingService(pricingService);
        trxPopulator.populate(transactionModel, transaction, merchantStore, language);
        return transaction;
    } catch (Exception e) {
        LOGGER.error("Error while initializing the payment", e);
        try {
            response.sendError(503, "Error while initializing the payment " + e.getMessage());
        } catch (Exception ignore) {
        }
        return null;
    }
}
Also used : PersistablePayment(com.salesmanager.shop.model.order.transaction.PersistablePayment) Payment(com.salesmanager.core.model.payments.Payment) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ReadableTransaction(com.salesmanager.shop.model.order.transaction.ReadableTransaction) Transaction(com.salesmanager.core.model.payments.Transaction) ReadableTransactionPopulator(com.salesmanager.shop.populator.order.transaction.ReadableTransactionPopulator) Customer(com.salesmanager.core.model.customer.Customer) ReadableTransaction(com.salesmanager.shop.model.order.transaction.ReadableTransaction) PersistablePaymentPopulator(com.salesmanager.shop.populator.order.transaction.PersistablePaymentPopulator) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) Principal(java.security.Principal) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 37 with ShoppingCart

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

the class OrderTotalApi method payment.

/**
 * This service calculates order total for a given shopping cart This method takes in
 * consideration any applicable sales tax An optional request parameter accepts a quote id that
 * was received using shipping api
 *
 * @param quote
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/auth/cart/{id}/total" }, method = RequestMethod.GET)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "String", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "String", defaultValue = "en") })
public ReadableOrderTotalSummary payment(@PathVariable final Long id, @RequestParam(value = "quote", required = false) Long quote, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletRequest request, HttpServletResponse response) {
    try {
        Principal principal = request.getUserPrincipal();
        String userName = principal.getName();
        Customer customer = customerService.getByNick(userName);
        if (customer == null) {
            response.sendError(503, "Error while getting user details to calculate shipping quote");
        }
        ShoppingCart shoppingCart = shoppingCartFacade.getShoppingCartModel(id, merchantStore);
        if (shoppingCart == null) {
            response.sendError(404, "Cart id " + id + " does not exist");
            return null;
        }
        if (shoppingCart.getCustomerId() == null) {
            response.sendError(404, "Cart id " + id + " does not exist for exist for user " + userName);
            return null;
        }
        if (shoppingCart.getCustomerId().longValue() != customer.getId().longValue()) {
            response.sendError(404, "Cart id " + id + " does not exist for exist for user " + userName);
            return null;
        }
        ShippingSummary shippingSummary = null;
        // get shipping quote if asked for
        if (quote != null) {
            shippingSummary = shippingQuoteService.getShippingSummary(quote, merchantStore);
        }
        OrderTotalSummary orderTotalSummary = null;
        OrderSummary orderSummary = new OrderSummary();
        orderSummary.setShippingSummary(shippingSummary);
        List<ShoppingCartItem> itemsSet = new ArrayList<ShoppingCartItem>(shoppingCart.getLineItems());
        orderSummary.setProducts(itemsSet);
        orderTotalSummary = orderService.caculateOrderTotal(orderSummary, customer, merchantStore, language);
        ReadableOrderTotalSummary returnSummary = new ReadableOrderTotalSummary();
        ReadableOrderSummaryPopulator populator = new ReadableOrderSummaryPopulator();
        populator.setMessages(messages);
        populator.setPricingService(pricingService);
        populator.populate(orderTotalSummary, returnSummary, merchantStore, language);
        return returnSummary;
    } catch (Exception e) {
        LOGGER.error("Error while calculating order summary", e);
        try {
            response.sendError(503, "Error while calculating order summary " + e.getMessage());
        } catch (Exception ignore) {
        }
        return null;
    }
}
Also used : ReadableOrderSummaryPopulator(com.salesmanager.shop.populator.order.ReadableOrderSummaryPopulator) Customer(com.salesmanager.core.model.customer.Customer) ReadableOrderTotalSummary(com.salesmanager.shop.model.order.ReadableOrderTotalSummary) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) OrderSummary(com.salesmanager.core.model.order.OrderSummary) ArrayList(java.util.ArrayList) ReadableOrderTotalSummary(com.salesmanager.shop.model.order.ReadableOrderTotalSummary) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ShippingSummary(com.salesmanager.core.model.shipping.ShippingSummary) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) Principal(java.security.Principal) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 38 with ShoppingCart

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

the class CustomerRegistrationController method registerCustomer.

@RequestMapping(value = "/register.html", method = RequestMethod.POST)
public String registerCustomer(@Valid @ModelAttribute("customer") SecuredShopPersistableCustomer customer, BindingResult bindingResult, Model model, HttpServletRequest request, HttpServletResponse response, final Locale locale) throws Exception {
    MerchantStore merchantStore = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = super.getLanguage(request);
    String userName = null;
    String password = null;
    model.addAttribute("recapatcha_public_key", siteKeyKey);
    if (!StringUtils.isBlank(request.getParameter("g-recaptcha-response"))) {
        boolean validateCaptcha = captchaRequestUtils.checkCaptcha(request.getParameter("g-recaptcha-response"));
        if (!validateCaptcha) {
            LOGGER.debug("Captcha response does not matched");
            FieldError error = new FieldError("captchaChallengeField", "captchaChallengeField", messages.getMessage("validaion.recaptcha.not.matched", locale));
            bindingResult.addError(error);
        }
    }
    if (StringUtils.isNotBlank(customer.getUserName())) {
        if (customerFacade.checkIfUserExists(customer.getUserName(), merchantStore)) {
            LOGGER.debug("Customer with username {} already exists for this store ", customer.getUserName());
            FieldError error = new FieldError("userName", "userName", messages.getMessage("registration.username.already.exists", locale));
            bindingResult.addError(error);
        }
        userName = customer.getUserName();
    }
    if (StringUtils.isNotBlank(customer.getPassword()) && StringUtils.isNotBlank(customer.getCheckPassword())) {
        if (!customer.getPassword().equals(customer.getCheckPassword())) {
            FieldError error = new FieldError("password", "password", messages.getMessage("message.password.checkpassword.identical", locale));
            bindingResult.addError(error);
        }
        password = customer.getPassword();
    }
    if (bindingResult.hasErrors()) {
        LOGGER.debug("found {} validation error while validating in customer registration ", bindingResult.getErrorCount());
        StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.register).append(".").append(merchantStore.getStoreTemplate());
        return template.toString();
    }
    @SuppressWarnings("unused") CustomerEntity customerData = null;
    try {
        // set user clear password
        customer.setPassword(password);
        customerData = customerFacade.registerCustomer(customer, merchantStore, language);
    } catch (Exception e) {
        LOGGER.error("Error while registering customer.. ", e);
        ObjectError error = new ObjectError("registration", messages.getMessage("registration.failed", locale));
        bindingResult.addError(error);
        StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.register).append(".").append(merchantStore.getStoreTemplate());
        return template.toString();
    }
    try {
        /**
         * Send registration email
         */
        emailTemplatesUtils.sendRegistrationEmail(customer, merchantStore, locale, request.getContextPath());
    } catch (Exception e) {
        LOGGER.error("Cannot send email to customer ", e);
    }
    try {
        // refresh customer
        Customer c = customerFacade.getCustomerByUserName(customer.getUserName(), merchantStore);
        // authenticate
        customerFacade.authenticate(c, userName, password);
        super.setSessionAttribute(Constants.CUSTOMER, c, request);
        StringBuilder cookieValue = new StringBuilder();
        cookieValue.append(merchantStore.getCode()).append("_").append(c.getNick());
        // set username in the cookie
        Cookie cookie = new Cookie(Constants.COOKIE_NAME_USER, cookieValue.toString());
        cookie.setMaxAge(60 * 24 * 3600);
        cookie.setPath(Constants.SLASH);
        response.addCookie(cookie);
        String sessionShoppingCartCode = (String) request.getSession().getAttribute(Constants.SHOPPING_CART);
        if (!StringUtils.isBlank(sessionShoppingCartCode)) {
            ShoppingCart shoppingCart = customerFacade.mergeCart(c, sessionShoppingCartCode, merchantStore, language);
            ShoppingCartData shoppingCartData = this.populateShoppingCartData(shoppingCart, merchantStore, language);
            if (shoppingCartData != null) {
                request.getSession().setAttribute(Constants.SHOPPING_CART, shoppingCartData.getCode());
            }
            // set username in the cookie
            Cookie c1 = new Cookie(Constants.COOKIE_NAME_CART, shoppingCartData.getCode());
            c1.setMaxAge(60 * 24 * 3600);
            c1.setPath(Constants.SLASH);
            response.addCookie(c1);
        }
        return "redirect:/shop/customer/dashboard.html";
    } catch (Exception e) {
        LOGGER.error("Cannot authenticate user ", e);
        ObjectError error = new ObjectError("registration", messages.getMessage("registration.failed", locale));
        bindingResult.addError(error);
    }
    StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Customer.register).append(".").append(merchantStore.getStoreTemplate());
    return template.toString();
}
Also used : Cookie(javax.servlet.http.Cookie) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) SecuredShopPersistableCustomer(com.salesmanager.shop.model.customer.SecuredShopPersistableCustomer) Customer(com.salesmanager.core.model.customer.Customer) FieldError(org.springframework.validation.FieldError) ShoppingCartData(com.salesmanager.shop.model.shoppingcart.ShoppingCartData) ServiceException(com.salesmanager.core.business.exception.ServiceException) ConversionException(com.salesmanager.core.business.exception.ConversionException) ObjectError(org.springframework.validation.ObjectError) Language(com.salesmanager.core.model.reference.language.Language) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) CustomerEntity(com.salesmanager.shop.model.customer.CustomerEntity) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

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