Search in sources :

Example 56 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class OrderTest method getMerchantOrders.

@Test
public void getMerchantOrders() throws ServiceException {
    Currency currency = currencyService.getByCode(USD_CURRENCY_CODE);
    Country country = countryService.getByCode("US");
    Zone zone = zoneService.getByCode("VT");
    Language en = languageService.getByCode("en");
    MerchantStore merchant = merchantService.getByCode(MerchantStore.DEFAULT_STORE);
    /**
     * Create a customer *
     */
    Customer customer = new Customer();
    customer.setMerchantStore(merchant);
    customer.setDefaultLanguage(en);
    customer.setEmailAddress("email@email.com");
    customer.setPassword("-1999");
    customer.setNick("My New nick");
    customer.setCompany(" Apple");
    customer.setGender(CustomerGender.M);
    customer.setDateOfBirth(new Date());
    Billing billing = new Billing();
    billing.setAddress("Billing address");
    billing.setCity("Billing city");
    billing.setCompany("Billing company");
    billing.setCountry(country);
    billing.setFirstName("Carl");
    billing.setLastName("Samson");
    billing.setPostalCode("Billing postal code");
    billing.setState("Billing state");
    billing.setZone(zone);
    Delivery delivery = new Delivery();
    delivery.setAddress("Shipping address");
    delivery.setCountry(country);
    delivery.setZone(zone);
    customer.setBilling(billing);
    customer.setDelivery(delivery);
    customerService.create(customer);
    // create a product with attributes
    /**
     * CATALOG CREATION *
     */
    ProductType generalType = productTypeService.getProductType(ProductType.GENERAL_TYPE);
    /**
     * Create the category
     */
    Category shirts = new Category();
    shirts.setMerchantStore(merchant);
    shirts.setCode("shirts");
    CategoryDescription shirtsEnglishDescription = new CategoryDescription();
    shirtsEnglishDescription.setName("Shirts");
    shirtsEnglishDescription.setCategory(shirts);
    shirtsEnglishDescription.setLanguage(en);
    Set<CategoryDescription> descriptions = new HashSet<CategoryDescription>();
    descriptions.add(shirtsEnglishDescription);
    shirts.setDescriptions(descriptions);
    categoryService.create(shirts);
    /**
     * Create a manufacturer
     */
    Manufacturer addidas = new Manufacturer();
    addidas.setMerchantStore(merchant);
    addidas.setCode("addidas");
    ManufacturerDescription addidasDesc = new ManufacturerDescription();
    addidasDesc.setLanguage(en);
    addidasDesc.setManufacturer(addidas);
    addidasDesc.setName("Addidas");
    addidas.getDescriptions().add(addidasDesc);
    manufacturerService.create(addidas);
    /**
     * Create an option
     */
    ProductOption option = new ProductOption();
    option.setMerchantStore(merchant);
    option.setCode("color");
    option.setProductOptionType(ProductOptionType.Radio.name());
    ProductOptionDescription optionDescription = new ProductOptionDescription();
    optionDescription.setLanguage(en);
    optionDescription.setName("Color");
    optionDescription.setDescription("Item color");
    optionDescription.setProductOption(option);
    option.getDescriptions().add(optionDescription);
    productOptionService.saveOrUpdate(option);
    /**
     * first option value *
     */
    ProductOptionValue white = new ProductOptionValue();
    white.setMerchantStore(merchant);
    white.setCode("white");
    ProductOptionValueDescription whiteDescription = new ProductOptionValueDescription();
    whiteDescription.setLanguage(en);
    whiteDescription.setName("White");
    whiteDescription.setDescription("White color");
    whiteDescription.setProductOptionValue(white);
    white.getDescriptions().add(whiteDescription);
    productOptionValueService.saveOrUpdate(white);
    ProductOptionValue black = new ProductOptionValue();
    black.setMerchantStore(merchant);
    black.setCode("black");
    /**
     * second option value *
     */
    ProductOptionValueDescription blackDesc = new ProductOptionValueDescription();
    blackDesc.setLanguage(en);
    blackDesc.setName("Black");
    blackDesc.setDescription("Black color");
    blackDesc.setProductOptionValue(black);
    black.getDescriptions().add(blackDesc);
    productOptionValueService.saveOrUpdate(black);
    /**
     * Create a complex product
     */
    Product product = new Product();
    product.setProductHeight(new BigDecimal(4));
    product.setProductLength(new BigDecimal(3));
    product.setProductWidth(new BigDecimal(1));
    product.setSku("TB12345");
    product.setManufacturer(addidas);
    product.setType(generalType);
    product.setMerchantStore(merchant);
    // Product description
    ProductDescription description = new ProductDescription();
    description.setName("Short sleeves shirt");
    description.setLanguage(en);
    description.setProduct(product);
    product.getDescriptions().add(description);
    product.getCategories().add(shirts);
    // availability
    ProductAvailability availability = new ProductAvailability();
    availability.setProductDateAvailable(new Date());
    availability.setProductQuantity(100);
    availability.setRegion("*");
    // associate with product
    availability.setProduct(product);
    // price
    ProductPrice dprice = new ProductPrice();
    dprice.setDefaultPrice(true);
    dprice.setProductPriceAmount(new BigDecimal(29.99));
    dprice.setProductAvailability(availability);
    ProductPriceDescription dpd = new ProductPriceDescription();
    dpd.setName("Base price");
    dpd.setProductPrice(dprice);
    dpd.setLanguage(en);
    dprice.getDescriptions().add(dpd);
    availability.getPrices().add(dprice);
    product.getAvailabilities().add(availability);
    // attributes
    // white
    ProductAttribute whiteAttribute = new ProductAttribute();
    whiteAttribute.setProduct(product);
    whiteAttribute.setProductOption(option);
    whiteAttribute.setAttributeDefault(true);
    // no price variation
    whiteAttribute.setProductAttributePrice(new BigDecimal(0));
    // no weight variation
    whiteAttribute.setProductAttributeWeight(new BigDecimal(0));
    whiteAttribute.setProductOption(option);
    whiteAttribute.setProductOptionValue(white);
    product.getAttributes().add(whiteAttribute);
    // black
    ProductAttribute blackAttribute = new ProductAttribute();
    blackAttribute.setProduct(product);
    blackAttribute.setProductOption(option);
    // 5 + dollars
    blackAttribute.setProductAttributePrice(new BigDecimal(5));
    // no weight variation
    blackAttribute.setProductAttributeWeight(new BigDecimal(0));
    blackAttribute.setProductOption(option);
    blackAttribute.setProductOptionValue(black);
    product.getAttributes().add(blackAttribute);
    productService.create(product);
    /**
     * Create an order *
     */
    Order order = new Order();
    /**
     * payment details *
     */
    CreditCard creditCard = new CreditCard();
    creditCard.setCardType(CreditCardType.VISA);
    creditCard.setCcCvv("123");
    creditCard.setCcExpires("12/30/2020");
    creditCard.setCcNumber("123456789");
    creditCard.setCcOwner("ccOwner");
    order.setCreditCard(creditCard);
    /**
     * order core attributes *
     */
    order.setDatePurchased(new Date());
    order.setCurrency(currency);
    order.setMerchant(merchant);
    order.setLastModified(new Date());
    // no price variation because of the currency
    order.setCurrencyValue(new BigDecimal(1));
    order.setCustomerId(1L);
    order.setDelivery(delivery);
    order.setIpAddress("ipAddress");
    order.setMerchant(merchant);
    order.setOrderDateFinished(new Date());
    order.setPaymentType(PaymentType.CREDITCARD);
    order.setPaymentModuleCode("payment Module Code");
    order.setShippingModuleCode("UPS");
    order.setStatus(OrderStatus.ORDERED);
    order.setCustomerAgreement(true);
    order.setConfirmedAddress(true);
    order.setTotal(dprice.getProductPriceAmount());
    order.setCustomerEmailAddress(customer.getEmailAddress());
    order.setBilling(billing);
    order.setDelivery(delivery);
    /**
     * ORDER PRODUCT *
     */
    // OrderProduct
    OrderProduct oproduct = new OrderProduct();
    oproduct.setDownloads(null);
    oproduct.setOneTimeCharge(dprice.getProductPriceAmount());
    oproduct.setOrder(order);
    oproduct.setProductName(description.getName());
    oproduct.setProductQuantity(1);
    oproduct.setSku(product.getSku());
    // set order product price
    OrderProductPrice orderProductPrice = new OrderProductPrice();
    // default price (same as default product price)
    orderProductPrice.setDefaultPrice(true);
    orderProductPrice.setOrderProduct(oproduct);
    orderProductPrice.setProductPrice(dprice.getProductPriceAmount());
    orderProductPrice.setProductPriceCode(ProductPriceType.ONE_TIME.name());
    oproduct.getPrices().add(orderProductPrice);
    // order product attribute
    OrderProductAttribute orderProductAttribute = new OrderProductAttribute();
    orderProductAttribute.setOrderProduct(oproduct);
    // no extra charge
    orderProductAttribute.setProductAttributePrice(new BigDecimal("0.00"));
    orderProductAttribute.setProductAttributeName(whiteDescription.getName());
    orderProductAttribute.setProductOptionId(option.getId());
    orderProductAttribute.setProductOptionValueId(white.getId());
    oproduct.getOrderAttributes().add(orderProductAttribute);
    order.getOrderProducts().add(oproduct);
    /**
     * ORDER TOTAL *
     */
    OrderTotal subTotal = new OrderTotal();
    subTotal.setOrder(order);
    subTotal.setOrderTotalCode(Constants.OT_SUBTOTAL_MODULE_CODE);
    subTotal.setSortOrder(0);
    subTotal.setTitle("Sub Total");
    subTotal.setValue(dprice.getProductPriceAmount());
    order.getOrderTotal().add(subTotal);
    OrderTotal total = new OrderTotal();
    total.setOrder(order);
    total.setOrderTotalCode(Constants.OT_TOTAL_MODULE_CODE);
    total.setSortOrder(1);
    total.setTitle("Total");
    total.setValue(dprice.getProductPriceAmount());
    order.getOrderTotal().add(total);
    /**
     * ORDER HISTORY *
     */
    // create a log entry in order history
    OrderStatusHistory history = new OrderStatusHistory();
    history.setOrder(order);
    history.setDateAdded(new Date());
    history.setStatus(OrderStatus.ORDERED);
    history.setComments("We received your order");
    order.getOrderHistory().add(history);
    /**
     * CREATE ORDER *
     */
    orderService.create(order);
    /**
     * SEARCH ORDERS *
     */
    OrderCriteria criteria = new OrderCriteria();
    criteria.setStartIndex(0);
    criteria.setMaxCount(10);
    OrderList ordserList = orderService.listByStore(merchant, criteria);
    Assert.assertNotNull(ordserList);
    Assert.assertNotNull("Merchant Orders are null.", ordserList.getOrders());
    Assert.assertTrue("Merchant Orders count is not one.", (ordserList.getOrders() != null && ordserList.getOrders().size() == 1));
}
Also used : Category(com.salesmanager.core.model.catalog.category.Category) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Customer(com.salesmanager.core.model.customer.Customer) OrderProduct(com.salesmanager.core.model.order.orderproduct.OrderProduct) Product(com.salesmanager.core.model.catalog.product.Product) ProductPrice(com.salesmanager.core.model.catalog.product.price.ProductPrice) OrderProductPrice(com.salesmanager.core.model.order.orderproduct.OrderProductPrice) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) OrderProductAttribute(com.salesmanager.core.model.order.orderproduct.OrderProductAttribute) ProductOptionDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionDescription) ProductOptionValue(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValue) Language(com.salesmanager.core.model.reference.language.Language) ProductAvailability(com.salesmanager.core.model.catalog.product.availability.ProductAvailability) Currency(com.salesmanager.core.model.reference.currency.Currency) Manufacturer(com.salesmanager.core.model.catalog.product.manufacturer.Manufacturer) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) ProductPriceDescription(com.salesmanager.core.model.catalog.product.price.ProductPriceDescription) HashSet(java.util.HashSet) ProductOption(com.salesmanager.core.model.catalog.product.attribute.ProductOption) Order(com.salesmanager.core.model.order.Order) Zone(com.salesmanager.core.model.reference.zone.Zone) ProductType(com.salesmanager.core.model.catalog.product.type.ProductType) OrderCriteria(com.salesmanager.core.model.order.OrderCriteria) Date(java.util.Date) BigDecimal(java.math.BigDecimal) CreditCard(com.salesmanager.core.model.order.payment.CreditCard) Billing(com.salesmanager.core.model.common.Billing) OrderProductPrice(com.salesmanager.core.model.order.orderproduct.OrderProductPrice) OrderProductAttribute(com.salesmanager.core.model.order.orderproduct.OrderProductAttribute) Country(com.salesmanager.core.model.reference.country.Country) ManufacturerDescription(com.salesmanager.core.model.catalog.product.manufacturer.ManufacturerDescription) CategoryDescription(com.salesmanager.core.model.catalog.category.CategoryDescription) Delivery(com.salesmanager.core.model.common.Delivery) ProductDescription(com.salesmanager.core.model.catalog.product.description.ProductDescription) OrderList(com.salesmanager.core.model.order.OrderList) OrderTotal(com.salesmanager.core.model.order.OrderTotal) OrderStatusHistory(com.salesmanager.core.model.order.orderstatus.OrderStatusHistory) ProductOptionValueDescription(com.salesmanager.core.model.catalog.product.attribute.ProductOptionValueDescription) Test(org.junit.Test)

Example 57 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class ShoppingCartServiceImpl method getShoppingCart.

/**
 * Retrieve a {@link ShoppingCart} cart for a given customer
 */
@Override
@Transactional
public ShoppingCart getShoppingCart(final Customer customer) throws ServiceException {
    try {
        List<ShoppingCart> shoppingCarts = shoppingCartRepository.findByCustomer(customer.getId());
        // elect valid shopping cart
        List<ShoppingCart> validCart = shoppingCarts.stream().filter((cart) -> cart.getOrderId() == null).collect(Collectors.toList());
        ShoppingCart shoppingCart = null;
        if (!CollectionUtils.isEmpty(validCart)) {
            shoppingCart = validCart.get(0);
            getPopulatedShoppingCart(shoppingCart);
            if (shoppingCart != null && shoppingCart.isObsolete()) {
                delete(shoppingCart);
                shoppingCart = null;
            }
        }
        return shoppingCart;
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}
Also used : ProductService(com.salesmanager.core.business.services.catalog.product.ProductService) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) LoggerFactory(org.slf4j.LoggerFactory) ShoppingCartItemRepository(com.salesmanager.core.business.repositories.shoppingcart.ShoppingCartItemRepository) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ServiceException(com.salesmanager.core.business.exception.ServiceException) ShoppingCartItem(com.salesmanager.core.model.shoppingcart.ShoppingCartItem) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) HashSet(java.util.HashSet) ShoppingCartAttributeRepository(com.salesmanager.core.business.repositories.shoppingcart.ShoppingCartAttributeRepository) BigDecimal(java.math.BigDecimal) MerchantStore(com.salesmanager.core.model.merchant.MerchantStore) FinalPrice(com.salesmanager.core.model.catalog.product.price.FinalPrice) ShippingProduct(com.salesmanager.core.model.shipping.ShippingProduct) Service(org.springframework.stereotype.Service) UserContext(com.salesmanager.core.model.common.UserContext) PricingService(com.salesmanager.core.business.services.catalog.product.PricingService) ProductAttributeService(com.salesmanager.core.business.services.catalog.product.attribute.ProductAttributeService) ProductAttribute(com.salesmanager.core.model.catalog.product.attribute.ProductAttribute) Product(com.salesmanager.core.model.catalog.product.Product) Logger(org.slf4j.Logger) ShoppingCartAttributeItem(com.salesmanager.core.model.shoppingcart.ShoppingCartAttributeItem) Customer(com.salesmanager.core.model.customer.Customer) Set(java.util.Set) Collectors(java.util.stream.Collectors) ShoppingCartRepository(com.salesmanager.core.business.repositories.shoppingcart.ShoppingCartRepository) List(java.util.List) Validate(org.apache.commons.lang3.Validate) SalesManagerEntityServiceImpl(com.salesmanager.core.business.services.common.generic.SalesManagerEntityServiceImpl) Transactional(org.springframework.transaction.annotation.Transactional) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ServiceException(com.salesmanager.core.business.exception.ServiceException) ServiceException(com.salesmanager.core.business.exception.ServiceException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 58 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class OrderApi method checkout.

/**
 * Main checkout resource that will complete the order flow
 * @param code
 * @param order
 * @param merchantStore
 * @param language
 * @return
 */
@RequestMapping(value = { "/cart/{code}/checkout" }, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") })
public ReadableOrderConfirmation checkout(// shopping cart
@PathVariable final String code, // order
@Valid @RequestBody PersistableAnonymousOrder order, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language) {
    Validate.notNull(order.getCustomer(), "Customer must not be null");
    ShoppingCart cart;
    try {
        cart = shoppingCartService.getByCode(code, merchantStore);
        if (cart == null) {
            throw new ResourceNotFoundException("Cart code " + code + " does not exist");
        }
        // security password validation
        PersistableCustomer presistableCustomer = order.getCustomer();
        if (!StringUtils.isBlank(presistableCustomer.getPassword())) {
            // validate customer password
            credentialsService.validateCredentials(presistableCustomer.getPassword(), presistableCustomer.getRepeatPassword(), merchantStore, language);
        }
        Customer customer = new Customer();
        customer = customerFacade.populateCustomerModel(customer, order.getCustomer(), merchantStore, language);
        if (!StringUtils.isBlank(presistableCustomer.getPassword())) {
            // check if customer already exist
            customer.setAnonymous(false);
            // username
            customer.setNick(customer.getEmailAddress());
            if (customerFacadev1.checkIfUserExists(customer.getNick(), merchantStore)) {
                // 409 Conflict
                throw new GenericRuntimeException("409", "Customer with email [" + customer.getEmailAddress() + "] is already registered");
            }
        }
        order.setShoppingCartId(cart.getId());
        Order modelOrder = orderFacade.processOrder(order, customer, merchantStore, language, LocaleUtils.getLocale(language));
        Long orderId = modelOrder.getId();
        // populate order confirmation
        order.setId(orderId);
        // set customer id
        order.getCustomer().setId(modelOrder.getCustomerId());
        return orderFacadeV1.orderConfirmation(modelOrder, customer, merchantStore, language);
    } catch (Exception e) {
        if (e instanceof CredentialsException) {
            throw new GenericRuntimeException("412", "Credentials creation Failed [" + e.getMessage() + "]");
        }
        String message = e.getMessage();
        if (StringUtils.isBlank(message)) {
            // exception type
            message = "APP-BACKEND";
            if (e.getCause() instanceof com.salesmanager.core.modules.integration.IntegrationException) {
                message = "Integration problen occured to complete order";
            }
        }
        throw new ServiceRuntimeException("Error during checkout [" + message + "]", e);
    }
}
Also used : PersistableAnonymousOrder(com.salesmanager.shop.model.order.v1.PersistableAnonymousOrder) PersistableOrder(com.salesmanager.shop.model.order.v1.PersistableOrder) Order(com.salesmanager.core.model.order.Order) ReadableOrder(com.salesmanager.shop.model.order.v0.ReadableOrder) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) GenericRuntimeException(com.salesmanager.shop.store.api.exception.GenericRuntimeException) CredentialsException(com.salesmanager.shop.store.security.services.CredentialsException) CredentialsException(com.salesmanager.shop.store.security.services.CredentialsException) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) GenericRuntimeException(com.salesmanager.shop.store.api.exception.GenericRuntimeException) ServiceRuntimeException(com.salesmanager.shop.store.api.exception.ServiceRuntimeException) ShoppingCart(com.salesmanager.core.model.shoppingcart.ShoppingCart) ResourceNotFoundException(com.salesmanager.shop.store.api.exception.ResourceNotFoundException) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 59 with Customer

use of com.salesmanager.core.model.customer.Customer in project shopizer by shopizer-ecommerce.

the class OrderApi method list.

/**
 * Get a list of orders for a given customer accept request parameter
 * 'start' start index for count accept request parameter 'max' maximum
 * number count, otherwise returns all Used for administrators
 *
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "/private/orders/customers/{id}" }, method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
@ApiImplicitParams({ @ApiImplicitParam(name = "store", dataType = "string", defaultValue = "DEFAULT"), @ApiImplicitParam(name = "lang", dataType = "string", defaultValue = "en") })
public ReadableOrderList list(@PathVariable final Long id, @RequestParam(value = "start", required = false) Integer start, @RequestParam(value = "count", required = false) Integer count, @ApiIgnore MerchantStore merchantStore, @ApiIgnore Language language, HttpServletResponse response) throws Exception {
    Customer customer = customerService.getById(id);
    if (customer == null) {
        LOGGER.error("Customer is null for id " + id);
        response.sendError(404, "Customer is null for id " + id);
        return null;
    }
    if (start == null) {
        start = new Integer(0);
    }
    if (count == null) {
        count = new Integer(100);
    }
    ReadableCustomer readableCustomer = new ReadableCustomer();
    ReadableCustomerPopulator customerPopulator = new ReadableCustomerPopulator();
    customerPopulator.populate(customer, readableCustomer, merchantStore, language);
    ReadableOrderList returnList = orderFacade.getReadableOrderList(merchantStore, customer, start, count, language);
    List<ReadableOrder> orders = returnList.getOrders();
    if (!CollectionUtils.isEmpty(orders)) {
        for (ReadableOrder order : orders) {
            order.setCustomer(readableCustomer);
        }
    }
    return returnList;
}
Also used : ReadableOrderList(com.salesmanager.shop.model.order.v0.ReadableOrderList) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) Customer(com.salesmanager.core.model.customer.Customer) PersistableCustomer(com.salesmanager.shop.model.customer.PersistableCustomer) ReadableCustomer(com.salesmanager.shop.model.customer.ReadableCustomer) ReadableCustomerPopulator(com.salesmanager.shop.populator.customer.ReadableCustomerPopulator) ReadableOrder(com.salesmanager.shop.model.order.v0.ReadableOrder) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 60 with Customer

use of com.salesmanager.core.model.customer.Customer 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)

Aggregations

Customer (com.salesmanager.core.model.customer.Customer)71 PersistableCustomer (com.salesmanager.shop.model.customer.PersistableCustomer)33 ReadableCustomer (com.salesmanager.shop.model.customer.ReadableCustomer)32 MerchantStore (com.salesmanager.core.model.merchant.MerchantStore)31 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)30 Language (com.salesmanager.core.model.reference.language.Language)26 ResourceNotFoundException (com.salesmanager.shop.store.api.exception.ResourceNotFoundException)17 ServiceRuntimeException (com.salesmanager.shop.store.api.exception.ServiceRuntimeException)17 ConversionException (com.salesmanager.core.business.exception.ConversionException)16 ServiceException (com.salesmanager.core.business.exception.ServiceException)16 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)16 ShoppingCart (com.salesmanager.core.model.shoppingcart.ShoppingCart)12 ApiImplicitParams (io.swagger.annotations.ApiImplicitParams)12 Authentication (org.springframework.security.core.Authentication)12 Date (java.util.Date)11 ConversionRuntimeException (com.salesmanager.shop.store.api.exception.ConversionRuntimeException)10 ArrayList (java.util.ArrayList)10 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)10 Product (com.salesmanager.core.model.catalog.product.Product)9 Country (com.salesmanager.core.model.reference.country.Country)9