use of com.salesmanager.core.model.order.OrderTotal 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;
}
use of com.salesmanager.core.model.order.OrderTotal 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);
}
}
use of com.salesmanager.core.model.order.OrderTotal in project shopizer by shopizer-ecommerce.
the class ManufacturerShippingCodeOrderTotalModuleImpl method caculateProductPiceVariation.
@Override
public OrderTotal caculateProductPiceVariation(final OrderSummary summary, ShoppingCartItem shoppingCartItem, Product product, Customer customer, MerchantStore store) throws Exception {
Validate.notNull(product, "product must not be null");
Validate.notNull(product.getManufacturer(), "product manufacturer must not be null");
// requires shipping summary, otherwise return null
if (summary.getShippingSummary() == null) {
return null;
}
OrderTotalInputParameters inputParameters = new OrderTotalInputParameters();
inputParameters.setItemManufacturerCode(product.getManufacturer().getCode());
inputParameters.setShippingMethod(summary.getShippingSummary().getShippingOptionCode());
LOGGER.debug("Setting input parameters " + inputParameters.toString());
/* KieSession kieSession = kieManufacturerBasedPricingContainer.newKieSession();
kieSession.insert(inputParameters);
kieSession.fireAllRules();*/
// orderTotalMethodDecision.execute(inputParameters);
LOGGER.debug("Applied discount " + inputParameters.getDiscount());
OrderTotal orderTotal = null;
if (inputParameters.getDiscount() != null) {
orderTotal = new OrderTotal();
orderTotal.setOrderTotalCode(Constants.OT_DISCOUNT_TITLE);
orderTotal.setOrderTotalType(OrderTotalType.SUBTOTAL);
orderTotal.setTitle(Constants.OT_SUBTOTAL_MODULE_CODE);
// calculate discount that will be added as a negative value
FinalPrice productPrice = pricingService.calculateProductPrice(product);
Double discount = inputParameters.getDiscount();
BigDecimal reduction = productPrice.getFinalPrice().multiply(new BigDecimal(discount));
reduction = reduction.multiply(new BigDecimal(shoppingCartItem.getQuantity()));
orderTotal.setValue(reduction);
}
return orderTotal;
}
use of com.salesmanager.core.model.order.OrderTotal in project shopizer by shopizer-ecommerce.
the class PaymentServiceImpl method processRefund.
@Override
public Transaction processRefund(Order order, Customer customer, MerchantStore store, BigDecimal amount) throws ServiceException {
Validate.notNull(customer);
Validate.notNull(store);
Validate.notNull(amount);
Validate.notNull(order);
Validate.notNull(order.getOrderTotal());
BigDecimal orderTotal = order.getTotal();
if (amount.doubleValue() > orderTotal.doubleValue()) {
throw new ServiceException("Invalid amount, the refunded amount is greater than the total allowed");
}
String module = order.getPaymentModuleCode();
Map<String, IntegrationConfiguration> modules = this.getPaymentModulesConfigured(store);
if (modules == null) {
throw new ServiceException("No payment module configured");
}
IntegrationConfiguration configuration = modules.get(module);
if (configuration == null) {
throw new ServiceException("Payment module " + module + " is not configured");
}
PaymentModule paymentModule = this.paymentModules.get(module);
if (paymentModule == null) {
throw new ServiceException("Payment module " + paymentModule + " does not exist");
}
boolean partial = false;
if (amount.doubleValue() != order.getTotal().doubleValue()) {
partial = true;
}
IntegrationModule integrationModule = getPaymentMethodByCode(store, module);
// get the associated transaction
Transaction refundable = transactionService.getRefundableTransaction(order);
if (refundable == null) {
throw new ServiceException("No refundable transaction for this order");
}
Transaction transaction = paymentModule.refund(partial, store, refundable, order, amount, configuration, integrationModule);
transaction.setOrder(order);
transactionService.create(transaction);
OrderTotal refund = new OrderTotal();
refund.setModule(Constants.OT_REFUND_MODULE_CODE);
refund.setText(Constants.OT_REFUND_MODULE_CODE);
refund.setTitle(Constants.OT_REFUND_MODULE_CODE);
refund.setOrderTotalCode(Constants.OT_REFUND_MODULE_CODE);
refund.setOrderTotalType(OrderTotalType.REFUND);
refund.setValue(amount);
refund.setSortOrder(100);
refund.setOrder(order);
order.getOrderTotal().add(refund);
// update order total
orderTotal = orderTotal.subtract(amount);
// update ordertotal refund
Set<OrderTotal> totals = order.getOrderTotal();
for (OrderTotal total : totals) {
if (total.getModule().equals(Constants.OT_TOTAL_MODULE_CODE)) {
total.setValue(orderTotal);
}
}
order.setTotal(orderTotal);
order.setStatus(OrderStatus.REFUNDED);
OrderStatusHistory orderHistory = new OrderStatusHistory();
orderHistory.setOrder(order);
orderHistory.setStatus(OrderStatus.REFUNDED);
orderHistory.setDateAdded(new Date());
order.getOrderHistory().add(orderHistory);
orderService.saveOrUpdate(order);
return transaction;
}
use of com.salesmanager.core.model.order.OrderTotal in project shopizer by shopizer-ecommerce.
the class ReadableOrderSummaryPopulator method populate.
@Override
public ReadableOrderTotalSummary populate(OrderTotalSummary source, ReadableOrderTotalSummary target, MerchantStore store, Language language) throws ConversionException {
Validate.notNull(pricingService, "PricingService must be set");
Validate.notNull(messages, "LabelUtils must be set");
if (target == null) {
target = new ReadableOrderTotalSummary();
}
try {
if (source.getSubTotal() != null) {
target.setSubTotal(pricingService.getDisplayAmount(source.getSubTotal(), store));
}
if (source.getTaxTotal() != null) {
target.setTaxTotal(pricingService.getDisplayAmount(source.getTaxTotal(), store));
}
if (source.getTotal() != null) {
target.setTotal(pricingService.getDisplayAmount(source.getTotal(), store));
}
if (!CollectionUtils.isEmpty(source.getTotals())) {
ReadableOrderTotalPopulator orderTotalPopulator = new ReadableOrderTotalPopulator();
orderTotalPopulator.setMessages(messages);
orderTotalPopulator.setPricingService(pricingService);
for (OrderTotal orderTotal : source.getTotals()) {
ReadableOrderTotal t = new ReadableOrderTotal();
orderTotalPopulator.populate(orderTotal, t, store, language);
target.getTotals().add(t);
}
}
} catch (Exception e) {
LOGGER.error("Error during amount formatting " + e.getMessage());
throw new ConversionException(e);
}
return target;
}
Aggregations