Search in sources :

Example 1 with Order

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

the class ShoppingOrderController method commitPreAuthorizedOrder.

@RequestMapping("/commitPreAuthorized.html")
public String commitPreAuthorizedOrder(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = (Language) request.getAttribute("LANGUAGE");
    ShopOrder order = super.getSessionAttribute(Constants.ORDER, request);
    if (order == null) {
        StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Pages.timeout).append(".").append(store.getStoreTemplate());
        return template.toString();
    }
    model.addAttribute("googleMapsKey", googleMapsKey);
    // display hacks
    if (!StringUtils.isBlank(googleMapsKey)) {
        model.addAttribute("disabled", "true");
        model.addAttribute("cssClass", "");
    } else {
        model.addAttribute("disabled", "false");
        model.addAttribute("cssClass", "required");
    }
    @SuppressWarnings("unchecked") Map<String, Object> configs = (Map<String, Object>) request.getAttribute(Constants.REQUEST_CONFIGS);
    if (configs != null && configs.containsKey(Constants.DEBUG_MODE)) {
        Boolean debugMode = (Boolean) configs.get(Constants.DEBUG_MODE);
        if (debugMode) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                String jsonInString = mapper.writeValueAsString(order);
                LOGGER.debug("Commit pre-authorized order -> " + jsonInString);
            } catch (Exception de) {
                LOGGER.error(de.getMessage());
            }
        }
    }
    try {
        OrderTotalSummary totalSummary = super.getSessionAttribute(Constants.ORDER_SUMMARY, request);
        if (totalSummary == null) {
            totalSummary = orderFacade.calculateOrderTotal(store, order, language);
            super.setSessionAttribute(Constants.ORDER_SUMMARY, totalSummary, request);
        }
        order.setOrderTotalSummary(totalSummary);
        // already validated, proceed with commit
        Order orderModel = this.commitOrder(order, request, locale);
        super.setSessionAttribute(Constants.ORDER_ID, orderModel.getId(), request);
        return "redirect:/shop/order/confirmation.html";
    } catch (Exception e) {
        LOGGER.error("Error while commiting order", e);
        throw e;
    }
}
Also used : ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) OrderTotalSummary(com.salesmanager.core.model.order.OrderTotalSummary) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShopOrder(com.salesmanager.shop.model.order.ShopOrder) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) Language(com.salesmanager.core.model.reference.language.Language) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) Map(java.util.Map) HashMap(java.util.HashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with Order

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

the class ShoppingOrderController method commitOrder.

private Order commitOrder(ShopOrder order, HttpServletRequest request, Locale locale) throws Exception, ServiceException {
    LOGGER.info("Entering comitOrder");
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    Language language = (Language) request.getAttribute("LANGUAGE");
    String userName = null;
    String password = null;
    PersistableCustomer customer = order.getCustomer();
    /**
     * set username and password to persistable object *
     */
    LOGGER.info("Set username and password to customer");
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Customer authCustomer = null;
    if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
        LOGGER.info("Customer authenticated");
        authCustomer = customerFacade.getCustomerByUserName(auth.getName(), store);
        // set id and authentication information
        customer.setUserName(authCustomer.getNick());
        // customer.setEncodedPassword(authCustomer.getPassword());
        customer.setId(authCustomer.getId());
    } else {
        // set customer id to null
        customer.setId(null);
    }
    // if the customer is new, generate a password
    LOGGER.info("New customer generate password");
    if (customer.getId() == null || customer.getId() == 0) {
    // new customer
    // password = UserReset.generateRandomString();
    // String encodedPassword = passwordEncoder.encode(password);
    // customer.setEncodedPassword(encodedPassword);
    }
    if (order.isShipToBillingAdress()) {
        customer.setDelivery(customer.getBilling());
    }
    LOGGER.info("Before creating new volatile");
    Customer modelCustomer = null;
    try {
        // set groups
        if (authCustomer == null) {
            // not authenticated, create a new volatile user
            modelCustomer = customerFacade.getCustomerModel(customer, store, language);
            customerFacade.setCustomerModelDefaultProperties(modelCustomer, store);
            userName = modelCustomer.getNick();
            LOGGER.debug("About to persist volatile customer to database.");
            if (modelCustomer.getDefaultLanguage() == null) {
                modelCustomer.setDefaultLanguage(languageService.toLanguage(locale));
            }
            customerService.saveOrUpdate(modelCustomer);
        } else {
            // use existing customer
            LOGGER.info("Populate customer model");
            modelCustomer = customerFacade.populateCustomerModel(authCustomer, customer, store, language);
        }
    } catch (Exception e) {
        throw new ServiceException(e);
    }
    LOGGER.debug("About to save transaction");
    Order modelOrder = null;
    Transaction initialTransaction = (Transaction) super.getSessionAttribute(Constants.INIT_TRANSACTION_KEY, request);
    if (initialTransaction != null) {
        modelOrder = orderFacade.processOrder(order, modelCustomer, initialTransaction, store, language);
    } else {
        modelOrder = orderFacade.processOrder(order, modelCustomer, store, language);
    }
    // save order id in session
    super.setSessionAttribute(Constants.ORDER_ID, modelOrder.getId(), request);
    // set a unique token for confirmation
    super.setSessionAttribute(Constants.ORDER_ID_TOKEN, modelOrder.getId(), request);
    LOGGER.debug("Transaction ended and order saved");
    LOGGER.debug("Remove cart");
    // get cart
    String cartCode = super.getSessionAttribute(Constants.SHOPPING_CART, request);
    if (StringUtils.isNotBlank(cartCode)) {
        try {
            shoppingCartFacade.setOrderId(cartCode, modelOrder.getId(), store);
        } catch (Exception e) {
            LOGGER.error("Cannot update cart " + cartCode, e);
            throw new ServiceException(e);
        }
    }
    // cleanup the order objects
    super.removeAttribute(Constants.ORDER, request);
    super.removeAttribute(Constants.ORDER_SUMMARY, request);
    super.removeAttribute(Constants.INIT_TRANSACTION_KEY, request);
    super.removeAttribute(Constants.SHIPPING_OPTIONS, request);
    super.removeAttribute(Constants.SHIPPING_SUMMARY, request);
    super.removeAttribute(Constants.SHOPPING_CART, request);
    LOGGER.debug("Refresh customer");
    try {
        // refresh customer --
        modelCustomer = customerFacade.getCustomerByUserName(modelCustomer.getNick(), store);
        // if has downloads, authenticate
        // check if any downloads exist for this order6
        List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(modelOrder.getId());
        if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
            LOGGER.debug("Is user authenticated ? ", auth.isAuthenticated());
            if (auth != null && request.isUserInRole("AUTH_CUSTOMER")) {
            // already authenticated
            } else {
                // authenticate
                customerFacade.authenticate(modelCustomer, userName, password);
                super.setSessionAttribute(Constants.CUSTOMER, modelCustomer, request);
            }
            // send new user registration template
            if (order.getCustomer().getId() == null || order.getCustomer().getId().longValue() == 0) {
                // send email for new customer
                // set clear password for email
                customer.setPassword(password);
                customer.setUserName(userName);
                emailTemplatesUtils.sendRegistrationEmail(customer, store, locale, request.getContextPath());
            }
        }
        // send order confirmation email to customer
        emailTemplatesUtils.sendOrderEmail(modelCustomer.getEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
        if (orderService.hasDownloadFiles(modelOrder)) {
            emailTemplatesUtils.sendOrderDownloadEmail(modelCustomer, modelOrder, store, locale, request.getContextPath());
        }
        // send order confirmation email to merchant
        emailTemplatesUtils.sendOrderEmail(store.getStoreEmailAddress(), modelCustomer, modelOrder, locale, language, store, request.getContextPath());
    } catch (Exception e) {
        LOGGER.error("Error while post processing order", e);
    }
    return modelOrder;
}
Also used : ShopOrder(com.salesmanager.shop.model.order.ShopOrder) Order(com.salesmanager.core.model.order.Order) ReadableShopOrder(com.salesmanager.shop.model.order.ReadableShopOrder) Language(com.salesmanager.core.model.reference.language.Language) ServiceException(com.salesmanager.core.business.exception.ServiceException) Transaction(com.salesmanager.core.model.payments.Transaction) AnonymousCustomer(com.salesmanager.shop.model.customer.AnonymousCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) Authentication(org.springframework.security.core.Authentication) OrderProductDownload(com.salesmanager.core.model.order.orderproduct.OrderProductDownload) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ServiceException(com.salesmanager.core.business.exception.ServiceException)

Example 3 with Order

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

the class ShoppingOrderDownloadController method downloadFile.

/**
 * Virtual product(s) download link
 * @param id
 * @param model
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@PreAuthorize("hasRole('AUTH_CUSTOMER')")
@RequestMapping("/download/{orderId}/{id}.html")
@ResponseBody
public byte[] downloadFile(@PathVariable Long orderId, @PathVariable Long id, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
    FileContentType fileType = FileContentType.PRODUCT_DIGITAL;
    // get customer and check order
    Order order = orderService.getById(orderId);
    if (order == null) {
        LOGGER.warn("Order is null for id " + orderId);
        response.sendError(404, "Image not found");
        return null;
    }
    // order belongs to customer
    Customer customer = (Customer) super.getSessionAttribute(Constants.CUSTOMER, request);
    if (customer == null) {
        response.sendError(404, "Image not found");
        return null;
    }
    // get it from OrderProductDownlaod
    String fileName = null;
    OrderProductDownload download = orderProductDownloadService.getById(id);
    if (download == null) {
        LOGGER.warn("OrderProductDownload is null for id " + id);
        response.sendError(404, "Image not found");
        return null;
    }
    fileName = download.getOrderProductFilename();
    // needs to query the new API
    OutputContentFile file = contentService.getContentFile(store.getCode(), fileType, fileName);
    if (file != null) {
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        return file.getFile().toByteArray();
    } else {
        LOGGER.warn("Image not found for OrderProductDownload id " + id);
        response.sendError(404, "Image not found");
        return null;
    }
// product image
// example -> /download/12345/120.html
}
Also used : Order(com.salesmanager.core.model.order.Order) Customer(com.salesmanager.core.model.customer.Customer) OutputContentFile(com.salesmanager.core.model.content.OutputContentFile) OrderProductDownload(com.salesmanager.core.model.order.orderproduct.OrderProductDownload) FileContentType(com.salesmanager.core.model.content.FileContentType) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 4 with Order

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

the class OrderServiceImpl method getCapturableOrders.

@Override
public List<Order> getCapturableOrders(MerchantStore store, Date startDate, Date endDate) throws ServiceException {
    List<Transaction> transactions = transactionService.listTransactions(startDate, endDate);
    List<Order> returnOrders = null;
    if (!CollectionUtils.isEmpty(transactions)) {
        returnOrders = new ArrayList<Order>();
        // order id
        Map<Long, Order> preAuthOrders = new HashMap<Long, Order>();
        // order id
        Map<Long, List<Transaction>> processingTransactions = new HashMap<Long, List<Transaction>>();
        for (Transaction trx : transactions) {
            Order order = trx.getOrder();
            if (TransactionType.AUTHORIZE.name().equals(trx.getTransactionType().name())) {
                preAuthOrders.put(order.getId(), order);
            }
            // put transaction
            List<Transaction> listTransactions = null;
            if (processingTransactions.containsKey(order.getId())) {
                listTransactions = processingTransactions.get(order.getId());
            } else {
                listTransactions = new ArrayList<Transaction>();
                processingTransactions.put(order.getId(), listTransactions);
            }
            listTransactions.add(trx);
        }
        for (Long orderId : processingTransactions.keySet()) {
            List<Transaction> trx = processingTransactions.get(orderId);
            if (CollectionUtils.isNotEmpty(trx)) {
                boolean capturable = true;
                for (Transaction t : trx) {
                    if (TransactionType.CAPTURE.name().equals(t.getTransactionType().name())) {
                        capturable = false;
                    } else if (TransactionType.AUTHORIZECAPTURE.name().equals(t.getTransactionType().name())) {
                        capturable = false;
                    } else if (TransactionType.REFUND.name().equals(t.getTransactionType().name())) {
                        capturable = false;
                    }
                }
                if (capturable) {
                    Order o = preAuthOrders.get(orderId);
                    returnOrders.add(o);
                }
            }
        }
    }
    return returnOrders;
}
Also used : Order(com.salesmanager.core.model.order.Order) Transaction(com.salesmanager.core.model.payments.Transaction) HashMap(java.util.HashMap) OrderList(com.salesmanager.core.model.order.OrderList) List(java.util.List) ArrayList(java.util.ArrayList)

Example 5 with Order

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

the class PersistableOrderApiPopulator method populate.

@Override
public Order populate(PersistableOrder source, Order target, MerchantStore store, Language language) throws ConversionException {
    /*		Validate.notNull(currencyService,"currencyService must be set");
		Validate.notNull(customerService,"customerService must be set");
		Validate.notNull(shoppingCartService,"shoppingCartService must be set");
		Validate.notNull(productService,"productService must be set");
		Validate.notNull(productAttributeService,"productAttributeService must be set");
		Validate.notNull(digitalProductService,"digitalProductService must be set");*/
    Validate.notNull(source.getPayment(), "Payment cannot be null");
    try {
        if (target == null) {
            target = new Order();
        }
        // target.setLocale(LocaleUtils.getLocale(store));
        target.setLocale(LocaleUtils.getLocale(store));
        Currency currency = null;
        try {
            currency = currencyService.getByCode(source.getCurrency());
        } catch (Exception e) {
            throw new ConversionException("Currency not found for code " + source.getCurrency());
        }
        if (currency == null) {
            throw new ConversionException("Currency not found for code " + source.getCurrency());
        }
        // Customer
        Customer customer = null;
        if (source.getCustomerId() != null && source.getCustomerId().longValue() > 0) {
            Long customerId = source.getCustomerId();
            customer = customerService.getById(customerId);
            if (customer == null) {
                throw new ConversionException("Curstomer with id " + source.getCustomerId() + " does not exist");
            }
            target.setCustomerId(customerId);
        } else {
            if (source instanceof PersistableAnonymousOrder) {
                PersistableCustomer persistableCustomer = ((PersistableAnonymousOrder) source).getCustomer();
                customer = new Customer();
                customer = customerPopulator.populate(persistableCustomer, customer, store, language);
            } else {
                throw new ConversionException("Curstomer details or id not set in request");
            }
        }
        target.setCustomerEmailAddress(customer.getEmailAddress());
        Delivery delivery = customer.getDelivery();
        target.setDelivery(delivery);
        Billing billing = customer.getBilling();
        target.setBilling(billing);
        if (source.getAttributes() != null && source.getAttributes().size() > 0) {
            Set<OrderAttribute> attrs = new HashSet<OrderAttribute>();
            for (com.salesmanager.shop.model.order.OrderAttribute attribute : source.getAttributes()) {
                OrderAttribute attr = new OrderAttribute();
                attr.setKey(attribute.getKey());
                attr.setValue(attribute.getValue());
                attr.setOrder(target);
                attrs.add(attr);
            }
            target.setOrderAttributes(attrs);
        }
        target.setDatePurchased(new Date());
        target.setCurrency(currency);
        target.setCurrencyValue(new BigDecimal(0));
        target.setMerchant(store);
        target.setChannel(OrderChannel.API);
        // need this
        target.setStatus(OrderStatus.ORDERED);
        target.setPaymentModuleCode(source.getPayment().getPaymentModule());
        target.setPaymentType(PaymentType.valueOf(source.getPayment().getPaymentType()));
        target.setCustomerAgreement(source.isCustomerAgreement());
        // force this to true, cannot perform this activity from the API
        target.setConfirmedAddress(true);
        if (!StringUtils.isBlank(source.getComments())) {
            OrderStatusHistory statusHistory = new OrderStatusHistory();
            statusHistory.setStatus(null);
            statusHistory.setOrder(target);
            statusHistory.setComments(source.getComments());
            target.getOrderHistory().add(statusHistory);
        }
        return target;
    } catch (Exception e) {
        throw new ConversionException(e);
    }
}
Also used : PersistableAnonymousOrder(com.salesmanager.shop.model.order.v1.PersistableAnonymousOrder) Order(com.salesmanager.core.model.order.Order) PersistableOrder(com.salesmanager.shop.model.order.v1.PersistableOrder) ConversionException(com.salesmanager.core.business.exception.ConversionException) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) ConversionException(com.salesmanager.core.business.exception.ConversionException) Date(java.util.Date) BigDecimal(java.math.BigDecimal) Currency(com.salesmanager.core.model.reference.currency.Currency) Billing(com.salesmanager.core.model.common.Billing) OrderAttribute(com.salesmanager.core.model.order.attributes.OrderAttribute) PersistableAnonymousOrder(com.salesmanager.shop.model.order.v1.PersistableAnonymousOrder) Delivery(com.salesmanager.core.model.common.Delivery) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) HashSet(java.util.HashSet)

Aggregations

Order (com.salesmanager.core.model.order.Order)26 ShopOrder (com.salesmanager.shop.model.order.ShopOrder)15 ConversionException (com.salesmanager.core.business.exception.ConversionException)12 ServiceException (com.salesmanager.core.business.exception.ServiceException)12 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)11 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)11 ArrayList (java.util.ArrayList)11 Customer (com.salesmanager.core.model.customer.Customer)9 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)9 Language (com.salesmanager.core.model.reference.language.Language)7 PersistableCustomer (com.salesmanager.shop.model.customer.PersistableCustomer)7 OrderProduct (com.salesmanager.core.model.order.orderproduct.OrderProduct)6 Transaction (com.salesmanager.core.model.payments.Transaction)6 OrderList (com.salesmanager.core.model.order.OrderList)5 OrderTotalSummary (com.salesmanager.core.model.order.OrderTotalSummary)5 OrderStatusHistory (com.salesmanager.core.model.order.orderstatus.OrderStatusHistory)5 ReadableCustomer (com.salesmanager.shop.model.customer.ReadableCustomer)5 ReadableOrderProduct (com.salesmanager.shop.model.order.ReadableOrderProduct)5 HashMap (java.util.HashMap)5 Product (com.salesmanager.core.model.catalog.product.Product)4