use of com.salesmanager.core.model.order.Order in project shopizer by shopizer-ecommerce.
the class OrderFacadeImpl method getReadableOrder.
@Override
public com.salesmanager.shop.model.order.v0.ReadableOrder getReadableOrder(Long orderId, MerchantStore store, Language language) {
Validate.notNull(store, "MerchantStore cannot be null");
Order modelOrder = orderService.getOrder(orderId, store);
if (modelOrder == null) {
throw new ResourceNotFoundException("Order not found with id " + orderId);
}
com.salesmanager.shop.model.order.v0.ReadableOrder readableOrder = new com.salesmanager.shop.model.order.v0.ReadableOrder();
Long customerId = modelOrder.getCustomerId();
if (customerId != null) {
ReadableCustomer readableCustomer = customerFacade.getCustomerById(customerId, store, language);
if (readableCustomer == null) {
LOGGER.warn("Customer id " + customerId + " not found in order " + orderId);
} else {
readableOrder.setCustomer(readableCustomer);
}
}
try {
readableOrderPopulator.populate(modelOrder, readableOrder, store, language);
// order products
List<ReadableOrderProduct> orderProducts = new ArrayList<ReadableOrderProduct>();
for (OrderProduct p : modelOrder.getOrderProducts()) {
ReadableOrderProductPopulator orderProductPopulator = new ReadableOrderProductPopulator();
orderProductPopulator.setProductService(productService);
orderProductPopulator.setPricingService(pricingService);
orderProductPopulator.setimageUtils(imageUtils);
ReadableOrderProduct orderProduct = new ReadableOrderProduct();
orderProductPopulator.populate(p, orderProduct, store, language);
orderProducts.add(orderProduct);
}
readableOrder.setProducts(orderProducts);
} catch (Exception e) {
throw new ServiceRuntimeException("Error while getting order [" + orderId + "]");
}
return readableOrder;
}
use of com.salesmanager.core.model.order.Order in project shopizer by shopizer-ecommerce.
the class OrderFacadeImpl method orderConfirmation.
@Override
public ReadableOrderConfirmation orderConfirmation(Order order, Customer customer, MerchantStore store, Language language) {
Validate.notNull(order, "Order cannot be null");
Validate.notNull(customer, "Customer cannot be null");
Validate.notNull(store, "MerchantStore cannot be null");
ReadableOrderConfirmation orderConfirmation = new ReadableOrderConfirmation();
ReadableCustomer readableCustomer = readableCustomerMapper.convert(customer, store, language);
orderConfirmation.setBilling(readableCustomer.getBilling());
orderConfirmation.setDelivery(readableCustomer.getDelivery());
ReadableTotal readableTotal = new ReadableTotal();
Set<OrderTotal> totals = order.getOrderTotal();
List<ReadableOrderTotal> readableTotals = totals.stream().sorted(Comparator.comparingInt(OrderTotal::getSortOrder)).map(tot -> convertOrderTotal(tot, store, language)).collect(Collectors.toList());
readableTotal.setTotals(readableTotals);
Optional<ReadableOrderTotal> grandTotal = readableTotals.stream().filter(tot -> tot.getCode().equals("order.total.total")).findFirst();
if (grandTotal.isPresent()) {
readableTotal.setGrandTotal(grandTotal.get().getText());
}
orderConfirmation.setTotal(readableTotal);
List<ReadableOrderProduct> products = order.getOrderProducts().stream().map(pr -> convertOrderProduct(pr, store, language)).collect(Collectors.toList());
orderConfirmation.setProducts(products);
if (!StringUtils.isBlank(order.getShippingModuleCode())) {
StringBuilder optionCodeBuilder = new StringBuilder();
try {
optionCodeBuilder.append("module.shipping.").append(order.getShippingModuleCode());
String shippingName = messages.getMessage(optionCodeBuilder.toString(), new String[] { store.getStorename() }, languageService.toLocale(language, store));
orderConfirmation.setShipping(shippingName);
} catch (Exception e) {
// label not found
LOGGER.warn("No shipping code found for " + optionCodeBuilder.toString());
}
}
if (order.getPaymentType() != null) {
orderConfirmation.setPayment(order.getPaymentType().name());
}
/**
* Confirmation may be formatted
*/
orderConfirmation.setId(order.getId());
return orderConfirmation;
}
use of com.salesmanager.core.model.order.Order 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));
}
use of com.salesmanager.core.model.order.Order 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);
}
}
use of com.salesmanager.core.model.order.Order in project shopizer by shopizer-ecommerce.
the class ShoppingOrderConfirmationController method displayConfirmation.
/**
* Invoked once the payment is complete and order is fulfilled
* @param model
* @param request
* @param response
* @param locale
* @return
* @throws Exception
*/
@RequestMapping("/confirmation.html")
public String displayConfirmation(Model model, HttpServletRequest request, HttpServletResponse response, Locale locale) throws Exception {
Language language = (Language) request.getAttribute("LANGUAGE");
MerchantStore store = (MerchantStore) request.getAttribute(Constants.MERCHANT_STORE);
Long orderId = super.getSessionAttribute(Constants.ORDER_ID, request);
if (orderId == null) {
return new StringBuilder().append("redirect:").append(Constants.SHOP_URI).toString();
}
// get the order
Order order = orderService.getById(orderId);
if (order == null) {
LOGGER.warn("Order id [" + orderId + "] does not exist");
throw new Exception("Order id [" + orderId + "] does not exist");
}
if (order.getMerchant().getId().intValue() != store.getId().intValue()) {
LOGGER.warn("Store id [" + store.getId() + "] differs from order.store.id [" + order.getMerchant().getId() + "]");
return new StringBuilder().append("redirect:").append(Constants.SHOP_URI).toString();
}
if (super.getSessionAttribute(Constants.ORDER_ID_TOKEN, request) != null) {
// set this unique token for performing unique operations in the confirmation
model.addAttribute("confirmation", "confirmation");
}
// remove unique token
super.removeAttribute(Constants.ORDER_ID_TOKEN, request);
String[] orderMessageParams = { store.getStorename() };
String orderMessage = messages.getMessage("label.checkout.text", orderMessageParams, locale);
model.addAttribute("ordermessage", orderMessage);
String[] orderIdParams = { String.valueOf(order.getId()) };
String orderMessageId = messages.getMessage("label.checkout.orderid", orderIdParams, locale);
model.addAttribute("ordermessageid", orderMessageId);
String[] orderEmailParams = { order.getCustomerEmailAddress() };
String orderEmailMessage = messages.getMessage("label.checkout.email", orderEmailParams, locale);
model.addAttribute("orderemail", orderEmailMessage);
ReadableOrder readableOrder = orderFacade.getReadableOrder(orderId, store, language);
// resolve country and Zone for GA
String countryCode = readableOrder.getCustomer().getBilling().getCountry();
Map<String, Country> countriesMap = countryService.getCountriesMap(language);
Country billingCountry = countriesMap.get(countryCode);
if (billingCountry != null) {
readableOrder.getCustomer().getBilling().setCountry(billingCountry.getName());
}
String zoneCode = readableOrder.getCustomer().getBilling().getZone();
Map<String, Zone> zonesMap = zoneService.getZones(language);
Zone billingZone = zonesMap.get(zoneCode);
if (billingZone != null) {
readableOrder.getCustomer().getBilling().setZone(billingZone.getName());
}
model.addAttribute("order", readableOrder);
// check if any downloads exist for this order
List<OrderProductDownload> orderProductDownloads = orderProdctDownloadService.getByOrderId(order.getId());
if (CollectionUtils.isNotEmpty(orderProductDownloads)) {
ReadableOrderProductDownloadPopulator populator = new ReadableOrderProductDownloadPopulator();
List<ReadableOrderProductDownload> downloads = new ArrayList<ReadableOrderProductDownload>();
for (OrderProductDownload download : orderProductDownloads) {
ReadableOrderProductDownload view = new ReadableOrderProductDownload();
populator.populate(download, view, store, language);
downloads.add(view);
}
model.addAttribute("downloads", downloads);
}
/**
* template *
*/
StringBuilder template = new StringBuilder().append(ControllerConstants.Tiles.Checkout.confirmation).append(".").append(store.getStoreTemplate());
return template.toString();
}
Aggregations