Esempio n. 1
0
 private static GenericValue getCartUserLogin(ShoppingCart cart) {
   GenericValue ul = cart.getUserLogin();
   if (ul == null) {
     ul = cart.getAutoUserLogin();
   }
   return ul;
 }
Esempio n. 2
0
 private static String[] makeCartItemsArray(ShoppingCart cart) {
   int len = cart.size();
   String[] arr = new String[len];
   for (int i = 0; i < len; i++) {
     arr[i] = Integer.toString(i);
   }
   return arr;
 }
Esempio n. 3
0
  /**
   * Fills the specialized shopping list with the current shopping cart if one exists (if not leaves
   * it alone)
   */
  public static void fillAutoSaveList(ShoppingCart cart, LocalDispatcher dispatcher)
      throws GeneralException {
    if (cart != null && dispatcher != null) {
      GenericValue userLogin = ShoppingListEvents.getCartUserLogin(cart);
      Delegator delegator = cart.getDelegator();
      String autoSaveListId = cart.getAutoSaveListId();
      if (autoSaveListId == null) {
        autoSaveListId =
            getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
        cart.setAutoSaveListId(autoSaveListId);
      }
      GenericValue shoppingList =
          EntityQuery.use(delegator)
              .from("ShoppingList")
              .where("shoppingListId", autoSaveListId)
              .queryOne();
      Integer currentListSize = 0;
      if (UtilValidate.isNotEmpty(shoppingList)) {
        List<GenericValue> shoppingListItems =
            shoppingList.getRelated("ShoppingListItem", null, null, false);
        if (UtilValidate.isNotEmpty(shoppingListItems)) {
          currentListSize = shoppingListItems.size();
        }
      }

      try {
        String[] itemsArray = makeCartItemsArray(cart);
        if (itemsArray != null && itemsArray.length != 0) {
          addBulkFromCart(
              delegator,
              dispatcher,
              cart,
              userLogin,
              autoSaveListId,
              null,
              itemsArray,
              false,
              false);
        } else if (itemsArray.length == 0 && currentListSize != 0) {
          clearListInfo(delegator, autoSaveListId);
        }
      } catch (IllegalArgumentException e) {
        throw new GeneralException(e.getMessage(), e);
      }
    }
  }
Esempio n. 4
0
  private static GenericValue getPaymentMethodGatewayPayPal(
      DispatchContext dctx,
      Map<String, ? extends Object> context,
      String paymentServiceTypeEnumId) {
    Delegator delegator = dctx.getDelegator();
    String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId");
    GenericValue payPalGatewayConfig = null;

    if (paymentGatewayConfigId == null) {
      String productStoreId = null;
      GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
      if (orderPaymentPreference != null) {
        OrderReadHelper orh =
            new OrderReadHelper(delegator, orderPaymentPreference.getString("orderId"));
        productStoreId = orh.getProductStoreId();
      } else {
        ShoppingCart cart = (ShoppingCart) context.get("cart");
        if (cart != null) {
          productStoreId = cart.getProductStoreId();
        }
      }
      if (productStoreId != null) {
        GenericValue payPalPaymentSetting =
            ProductStoreWorker.getProductStorePaymentSetting(
                delegator, productStoreId, "EXT_PAYPAL", paymentServiceTypeEnumId, true);
        if (payPalPaymentSetting != null) {
          paymentGatewayConfigId = payPalPaymentSetting.getString("paymentGatewayConfigId");
        }
      }
    }
    if (paymentGatewayConfigId != null) {
      try {
        payPalGatewayConfig =
            EntityQuery.use(delegator)
                .from("PaymentGatewayPayPal")
                .where("paymentGatewayConfigId", paymentGatewayConfigId)
                .cache()
                .queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    return payPalGatewayConfig;
  }
Esempio n. 5
0
 private static void addCartDetails(NVPEncoder encoder, ShoppingCart cart)
     throws GenericEntityException {
   encoder.add("CURRENCYCODE", cart.getCurrency());
   int line = 0;
   for (ShoppingCartItem item : cart.items()) {
     encoder.add("L_NUMBER" + line, item.getProductId());
     encoder.add("L_NAME" + line, item.getName());
     encoder.add(
         "L_AMT" + line,
         item.getBasePrice().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
     encoder.add("L_QTY" + line, item.getQuantity().toBigInteger().toString());
     line++;
     BigDecimal otherAdjustments = item.getOtherAdjustments();
     if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
       encoder.add("L_NUMBER" + line, item.getProductId());
       encoder.add("L_NAME" + line, item.getName() + " Adjustments");
       encoder.add(
           "L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
       encoder.add("L_QTY" + line, "1");
       line++;
     }
   }
   BigDecimal otherAdjustments = cart.getOrderOtherAdjustmentTotal();
   if (otherAdjustments.compareTo(BigDecimal.ZERO) != 0) {
     encoder.add("L_NUMBER" + line, "N/A");
     encoder.add("L_NAME" + line, "Order Adjustments");
     encoder.add(
         "L_AMT" + line, otherAdjustments.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
     encoder.add("L_QTY" + line, "1");
     line++;
   }
   encoder.add("ITEMAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
   encoder.add("SHIPPINGAMT", "0.00");
   encoder.add("TAXAMT", "0.00");
   encoder.add("AMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
   // NOTE: The docs say this is optional but then won't work without it
   encoder.add("MAXAMT", cart.getSubTotal().add(otherAdjustments).setScale(2).toPlainString());
 }
Esempio n. 6
0
  /** Create the guest cookies for a shopping list */
  public static String createGuestShoppingListCookies(
      HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    HttpSession session = request.getSession(true);
    ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    Properties systemProps = System.getProperties();
    String guestShoppingUserName =
        "******" + systemProps.getProperty("user.name").replace(" ", "_");
    String productStoreId = ProductStoreWorker.getProductStoreId(request);
    int cookieAge = (60 * 60 * 24 * 30);
    String autoSaveListId = null;
    Cookie[] cookies = request.getCookies();

    // check userLogin
    if (UtilValidate.isNotEmpty(userLogin)) {
      String partyId = userLogin.getString("partyId");
      if (UtilValidate.isEmpty(partyId)) {
        return "success";
      }
    }

    // find shopping list ID
    if (cookies != null) {
      for (Cookie cookie : cookies) {
        if (cookie.getName().equals(guestShoppingUserName)) {
          autoSaveListId = cookie.getValue();
          break;
        }
      }
    }

    // clear the auto-save info
    if (ProductStoreWorker.autoSaveCart(delegator, productStoreId)) {
      if (UtilValidate.isEmpty(autoSaveListId)) {
        try {
          Map<String, Object> listFields =
              UtilMisc.<String, Object>toMap(
                  "userLogin",
                  userLogin,
                  "productStoreId",
                  productStoreId,
                  "shoppingListTypeId",
                  "SLT_SPEC_PURP",
                  "listName",
                  PERSISTANT_LIST_NAME);
          Map<String, Object> newListResult = dispatcher.runSync("createShoppingList", listFields);
          if (newListResult != null) {
            autoSaveListId = (String) newListResult.get("shoppingListId");
          }
        } catch (GeneralException e) {
          Debug.logError(e, module);
        }
        Cookie guestShoppingListCookie = new Cookie(guestShoppingUserName, autoSaveListId);
        guestShoppingListCookie.setMaxAge(cookieAge);
        guestShoppingListCookie.setPath("/");
        response.addCookie(guestShoppingListCookie);
      }
    }
    if (UtilValidate.isNotEmpty(autoSaveListId)) {
      if (UtilValidate.isNotEmpty(cart)) {
        cart.setAutoSaveListId(autoSaveListId);
      } else {
        cart = ShoppingCartEvents.getCartObject(request);
        cart.setAutoSaveListId(autoSaveListId);
      }
    }
    return "success";
  }
Esempio n. 7
0
  /** Restores the specialized (auto-save) shopping list back into the shopping cart */
  public static String restoreAutoSaveList(
      HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue productStore = ProductStoreWorker.getProductStore(request);

    if (!ProductStoreWorker.autoSaveCart(productStore)) {
      // if auto-save is disabled just return here
      return "success";
    }

    HttpSession session = request.getSession();
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    // safety check for missing required parameter.
    if (cart.getWebSiteId() == null) {
      cart.setWebSiteId(WebSiteWorker.getWebSiteId(request));
    }

    // locate the user's identity
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    if (userLogin == null) {
      userLogin = (GenericValue) session.getAttribute("autoUserLogin");
    }

    // find the list ID
    String autoSaveListId = cart.getAutoSaveListId();
    if (autoSaveListId == null) {
      try {
        autoSaveListId =
            getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
      } catch (GeneralException e) {
        Debug.logError(e, module);
      }
      cart.setAutoSaveListId(autoSaveListId);
    } else if (userLogin != null) {
      String existingAutoSaveListId = null;
      try {
        existingAutoSaveListId =
            getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
      } catch (GeneralException e) {
        Debug.logError(e, module);
      }
      if (existingAutoSaveListId != null) {
        if (!existingAutoSaveListId.equals(autoSaveListId)) {
          // Replace with existing shopping list
          cart.setAutoSaveListId(existingAutoSaveListId);
          autoSaveListId = existingAutoSaveListId;
          cart.setLastListRestore(null);
        } else {
          // CASE: User first login and logout and then re-login again. This condition does not
          // require a restore at all
          // because at this point items in the cart and the items in the shopping list are same so
          // just return.
          return "success";
        }
      }
    }

    // check to see if we are okay to load this list
    java.sql.Timestamp lastLoad = cart.getLastListRestore();
    boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false);
    if (!okayToLoad && lastLoad != null) {
      GenericValue shoppingList = null;
      try {
        shoppingList =
            EntityQuery.use(delegator)
                .from("ShoppingList")
                .where("shoppingListId", autoSaveListId)
                .queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
      if (shoppingList != null) {
        java.sql.Timestamp lastModified = shoppingList.getTimestamp("lastAdminModified");
        if (lastModified != null) {
          if (lastModified.after(lastLoad)) {
            okayToLoad = true;
          }
          if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) {
            okayToLoad = true;
          }
        }
      }
    }

    // load (restore) the list of we have determined it is okay to load
    if (okayToLoad) {
      String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
      try {
        addListToCart(
            delegator,
            dispatcher,
            cart,
            prodCatalogId,
            autoSaveListId,
            false,
            false,
            userLogin != null ? true : false);
        cart.setLastListRestore(UtilDateTime.nowTimestamp());
      } catch (IllegalArgumentException e) {
        Debug.logError(e, module);
      }
    }

    return "success";
  }
Esempio n. 8
0
  public static String addListToCart(
      Delegator delegator,
      LocalDispatcher dispatcher,
      ShoppingCart cart,
      String prodCatalogId,
      String shoppingListId,
      boolean includeChild,
      boolean setAsListItem,
      boolean append)
      throws java.lang.IllegalArgumentException {
    String errMsg = null;

    // no list; no add
    if (shoppingListId == null) {
      errMsg =
          UtilProperties.getMessage(
              resource_error, "shoppinglistevents.choose_shopping_list", cart.getLocale());
      throw new IllegalArgumentException(errMsg);
    }

    // get the shopping list
    GenericValue shoppingList = null;
    List<GenericValue> shoppingListItems = null;
    try {
      shoppingList =
          EntityQuery.use(delegator)
              .from("ShoppingList")
              .where("shoppingListId", shoppingListId)
              .queryOne();
      if (shoppingList == null) {
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.error_getting_shopping_list_and_items",
                cart.getLocale());
        throw new IllegalArgumentException(errMsg);
      }

      shoppingListItems = shoppingList.getRelated("ShoppingListItem", null, null, false);
      if (shoppingListItems == null) {
        shoppingListItems = FastList.newInstance();
      }

      // include all items of child lists if flagged to do so
      if (includeChild) {
        List<GenericValue> childShoppingLists =
            shoppingList.getRelated("ChildShoppingList", null, null, false);
        for (GenericValue v : childShoppingLists) {
          List<GenericValue> items = v.getRelated("ShoppingListItem", null, null, false);
          shoppingListItems.addAll(items);
        }
      }

    } catch (GenericEntityException e) {
      Debug.logError(e, "Problems getting ShoppingList and ShoppingListItem records", module);
      errMsg =
          UtilProperties.getMessage(
              resource_error,
              "shoppinglistevents.error_getting_shopping_list_and_items",
              cart.getLocale());
      throw new IllegalArgumentException(errMsg);
    }

    // no items; not an error; just mention that nothing was added
    if (UtilValidate.isEmpty(shoppingListItems)) {
      errMsg =
          UtilProperties.getMessage(
              resource_error, "shoppinglistevents.no_items_added", cart.getLocale());
      return errMsg;
    }

    // check if we are to clear the cart first
    if (!append) {
      cart.clear();
      // Prevent the system from creating a new shopping list every time the cart is restored for
      // anonymous user.
      cart.setAutoSaveListId(shoppingListId);
    }

    // get the survey info for all the items
    Map<String, List<String>> shoppingListSurveyInfo = getItemSurveyInfos(shoppingListItems);

    // add the items
    StringBuilder eventMessage = new StringBuilder();
    for (GenericValue shoppingListItem : shoppingListItems) {
      String productId = shoppingListItem.getString("productId");
      BigDecimal quantity = shoppingListItem.getBigDecimal("quantity");
      Timestamp reservStart = shoppingListItem.getTimestamp("reservStart");
      BigDecimal reservLength = shoppingListItem.getBigDecimal("reservLength");
      BigDecimal reservPersons = shoppingListItem.getBigDecimal("reservPersons");
      //    String accommodationMapId = shoppingListItem.getString("accommodationMapId");
      //    String accommodationSpotId = shoppingListItem.getString("accommodationSpotId");
      String configId = shoppingListItem.getString("configId");
      try {
        String listId = shoppingListItem.getString("shoppingListId");
        String itemId = shoppingListItem.getString("shoppingListItemSeqId");

        Map<String, Object> attributes = FastMap.newInstance();
        // list items are noted in the shopping cart
        if (setAsListItem) {
          attributes.put("shoppingListId", listId);
          attributes.put("shoppingListItemSeqId", itemId);
        }

        // check if we have existing survey responses to append
        if (shoppingListSurveyInfo.containsKey(listId + "." + itemId)
            && UtilValidate.isNotEmpty(shoppingListSurveyInfo.get(listId + "." + itemId))) {
          attributes.put("surveyResponses", shoppingListSurveyInfo.get(listId + "." + itemId));
        }

        ProductConfigWrapper configWrapper = null;
        if (UtilValidate.isNotEmpty(configId)) {
          configWrapper =
              ProductConfigWorker.loadProductConfigWrapper(
                  delegator,
                  dispatcher,
                  configId,
                  productId,
                  cart.getProductStoreId(),
                  prodCatalogId,
                  cart.getWebSiteId(),
                  cart.getCurrency(),
                  cart.getLocale(),
                  cart.getAutoUserLogin());
        }
        // TODO: add code to check for survey response requirement

        // i cannot get the addOrDecrease function to accept a null reservStart field: i get a null
        // pointer exception a null constant works....
        if (reservStart == null) {
          cart.addOrIncreaseItem(
              productId,
              null,
              quantity,
              null,
              null,
              null,
              null,
              null,
              null,
              attributes,
              prodCatalogId,
              configWrapper,
              null,
              null,
              null,
              dispatcher);
        } else {
          cart.addOrIncreaseItem(
              productId,
              null,
              quantity,
              reservStart,
              reservLength,
              reservPersons,
              null,
              null,
              null,
              null,
              null,
              attributes,
              prodCatalogId,
              configWrapper,
              null,
              null,
              null,
              dispatcher);
        }
        Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.added_product_to_cart",
                messageMap,
                cart.getLocale());
        eventMessage.append(errMsg).append("\n");
      } catch (CartItemModifyException e) {
        Debug.logWarning(
            e,
            UtilProperties.getMessage(
                resource_error, "OrderProblemsAddingItemFromListToCart", cart.getLocale()));
        Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.problem_adding_product_to_cart",
                messageMap,
                cart.getLocale());
        eventMessage.append(errMsg).append("\n");
      } catch (ItemNotFoundException e) {
        Debug.logWarning(
            e, UtilProperties.getMessage(resource_error, "OrderProductNotFound", cart.getLocale()));
        Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", productId);
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.problem_adding_product_to_cart",
                messageMap,
                cart.getLocale());
        eventMessage.append(errMsg).append("\n");
      }
    }

    if (eventMessage.length() > 0) {
      return eventMessage.toString();
    }

    // all done
    return ""; // no message to return; will simply reply as success
  }
Esempio n. 9
0
  public static String addBulkFromCart(
      Delegator delegator,
      LocalDispatcher dispatcher,
      ShoppingCart cart,
      GenericValue userLogin,
      String shoppingListId,
      String shoppingListTypeId,
      String[] items,
      boolean allowPromo,
      boolean append)
      throws IllegalArgumentException {
    String errMsg = null;

    if (items == null || items.length == 0) {
      errMsg =
          UtilProperties.getMessage(
              resource_error, "shoppinglistevents.select_items_to_add_to_list", cart.getLocale());
      throw new IllegalArgumentException(errMsg);
    }

    if (UtilValidate.isEmpty(shoppingListId)) {
      // create a new shopping list
      Map<String, Object> newListResult = null;
      try {
        newListResult =
            dispatcher.runSync(
                "createShoppingList",
                UtilMisc.<String, Object>toMap(
                    "userLogin",
                    userLogin,
                    "productStoreId",
                    cart.getProductStoreId(),
                    "partyId",
                    cart.getOrderPartyId(),
                    "shoppingListTypeId",
                    shoppingListTypeId,
                    "currencyUom",
                    cart.getCurrency()));
      } catch (GenericServiceException e) {
        Debug.logError(e, "Problems creating new ShoppingList", module);
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.cannot_create_new_shopping_list",
                cart.getLocale());
        throw new IllegalArgumentException(errMsg);
      }

      // check for errors
      if (ServiceUtil.isError(newListResult)) {
        throw new IllegalArgumentException(ServiceUtil.getErrorMessage(newListResult));
      }

      // get the new list id
      if (newListResult != null) {
        shoppingListId = (String) newListResult.get("shoppingListId");
      }

      // if no list was created throw an error
      if (shoppingListId == null || shoppingListId.equals("")) {
        errMsg =
            UtilProperties.getMessage(
                resource_error,
                "shoppinglistevents.shoppingListId_is_required_parameter",
                cart.getLocale());
        throw new IllegalArgumentException(errMsg);
      }
    } else if (!append) {
      try {
        clearListInfo(delegator, shoppingListId);
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        throw new IllegalArgumentException(
            "Could not clear current shopping list: " + e.toString());
      }
    }

    for (int i = 0; i < items.length; i++) {
      Integer cartIdInt = null;
      try {
        cartIdInt = Integer.valueOf(items[i]);
      } catch (Exception e) {
        Debug.logWarning(
            e,
            UtilProperties.getMessage(
                resource_error, "OrderIllegalCharacterInSelectedItemField", cart.getLocale()),
            module);
      }
      if (cartIdInt != null) {
        ShoppingCartItem item = cart.findCartItem(cartIdInt.intValue());
        if (allowPromo || !item.getIsPromo()) {
          Debug.logInfo(
              "Adding cart item to shopping list ["
                  + shoppingListId
                  + "], allowPromo="
                  + allowPromo
                  + ", item.getIsPromo()="
                  + item.getIsPromo()
                  + ", item.getProductId()="
                  + item.getProductId()
                  + ", item.getQuantity()="
                  + item.getQuantity(),
              module);
          Map<String, Object> serviceResult = null;
          try {
            Map<String, Object> ctx =
                UtilMisc.<String, Object>toMap(
                    "userLogin",
                    userLogin,
                    "shoppingListId",
                    shoppingListId,
                    "productId",
                    item.getProductId(),
                    "quantity",
                    item.getQuantity());
            ctx.put("reservStart", item.getReservStart());
            ctx.put("reservLength", item.getReservLength());
            ctx.put("reservPersons", item.getReservPersons());
            //    ctx.put("accommodationMapId", item.getAccommodationMapId());
            //    ctx.put("accommodationSpotId", item.getAccommodationSpotId());
            if (item.getConfigWrapper() != null) {
              ctx.put("configId", item.getConfigWrapper().getConfigId());
            }
            serviceResult = dispatcher.runSync("createShoppingListItem", ctx);
          } catch (GenericServiceException e) {
            Debug.logError(e, "Problems creating ShoppingList item entity", module);
            errMsg =
                UtilProperties.getMessage(
                    resource_error,
                    "shoppinglistevents.error_adding_item_to_shopping_list",
                    cart.getLocale());
            throw new IllegalArgumentException(errMsg);
          }

          // check for errors
          if (ServiceUtil.isError(serviceResult)) {
            throw new IllegalArgumentException(ServiceUtil.getErrorMessage(serviceResult));
          }
        }
      }
    }

    // return the shoppinglist id
    return shoppingListId;
  }
Esempio n. 10
0
  public static Map<String, Object> setExpressCheckout(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    ShoppingCart cart = (ShoppingCart) context.get("cart");
    Locale locale = cart.getLocale();
    if (cart == null || cart.items().size() <= 0) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalShoppingCartIsEmpty", locale));
    }

    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }

    NVPEncoder encoder = new NVPEncoder();

    // Set Express Checkout Request Parameters
    encoder.add("METHOD", "SetExpressCheckout");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
      encoder.add("TOKEN", token);
    }
    encoder.add("RETURNURL", payPalConfig.getString("returnUrl"));
    encoder.add("CANCELURL", payPalConfig.getString("cancelReturnUrl"));
    if (!cart.shippingApplies()) {
      encoder.add("NOSHIPPING", "1");
    } else {
      encoder.add("CALLBACK", payPalConfig.getString("shippingCallbackUrl"));
      encoder.add("CALLBACKTIMEOUT", "6");
      // Default to no
      String reqConfirmShipping =
          "Y".equals(payPalConfig.getString("requireConfirmedShipping")) ? "1" : "0";
      encoder.add("REQCONFIRMSHIPPING", reqConfirmShipping);
      // Default shipment method
      encoder.add("L_SHIPPINGOPTIONISDEFAULT0", "true");
      encoder.add("L_SHIPPINGOPTIONNAME0", "Calculated Offline");
      encoder.add("L_SHIPPINGOPTIONAMOUNT0", "0.00");
    }
    encoder.add("ALLOWNOTE", "1");
    encoder.add("INSURANCEOPTIONOFFERED", "false");
    if (UtilValidate.isNotEmpty(payPalConfig.getString("imageUrl"))) ;
    encoder.add("PAYMENTACTION", "Order");

    // Cart information
    try {
      addCartDetails(encoder, cart);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalErrorDuringRetrievingCartDetails", locale));
    }

    NVPDecoder decoder;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    Map<String, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
      if (errorMessages.containsKey("10411")) {
        // Token has expired, get a new one
        cart.setAttribute("payPalCheckoutToken", null);
        return PayPalServices.setExpressCheckout(dctx, context);
      }
      return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    token = decoder.get("TOKEN");
    cart.setAttribute("payPalCheckoutToken", token);
    TokenWrapper tokenWrapper = new TokenWrapper(token);
    cart.setAttribute("payPalCheckoutTokenObj", tokenWrapper);
    PayPalServices.tokenCartMap.put(tokenWrapper, new WeakReference<ShoppingCart>(cart));
    return ServiceUtil.returnSuccess();
  }
Esempio n. 11
0
  public static Map<String, Object> getExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
      encoder.add("TOKEN", token);
    } else {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }

    NVPDecoder decoder;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
      cart.addOrderNote(decoder.get("NOTE"));
    }

    if (cart.getUserLogin() == null) {
      try {
        GenericValue userLogin =
            EntityQuery.use(delegator)
                .from("UserLogin")
                .where("userLoginId", "anonymous")
                .queryOne();
        try {
          cart.setUserLogin(userLogin, dispatcher);
        } catch (CartItemModifyException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
      // Check nothing has been set on the anon userLogin either
      partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
      cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
      GenericValue party = null;
      try {
        party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
      if (party == null) {
        partyId = null;
      }
    }

    Map<String, Object> inMap = FastMap.newInstance();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
      newParty = true;
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("personalTitle", decoder.get("SALUTATION"));
      inMap.put("firstName", decoder.get("FIRSTNAME"));
      inMap.put("middleName", decoder.get("MIDDLENAME"));
      inMap.put("lastName", decoder.get("LASTNAME"));
      inMap.put("suffix", decoder.get("SUFFIX"));
      try {
        outMap = dispatcher.runSync("createPerson", inMap);
        partyId = (String) outMap.get("partyId");
        cart.setOrderPartyId(partyId);
        cart.getUserLogin().setString("partyId", partyId);
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        dispatcher.runSync("createPartyRole", inMap);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(
                      UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")),
                  EntityCondition.makeCondition(
                      EntityFunction.UPPER_FIELD("infoString"),
                      EntityComparisonOperator.EQUALS,
                      EntityFunction.UPPER(emailAddress))));

      try {
        GenericValue matchingEmail =
            EntityQuery.use(delegator)
                .from("PartyAndContactMech")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (matchingEmail != null) {
          emailContactMechId = matchingEmail.getString("contactMechId");
        } else {
          // No email found so we'll need to create one but first check if it should be PRIMARY or
          // just BILLING
          long primaryEmails =
              EntityQuery.use(delegator)
                  .from("PartyContactWithPurpose")
                  .where(
                      "partyId",
                      partyId,
                      "contactMechTypeId",
                      "EMAIL_ADDRESS",
                      "contactMechPurposeTypeId",
                      "PRIMARY_EMAIL")
                  .filterByDate(
                      "contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate")
                  .queryCount();
          if (primaryEmails > 0) emailContactPurposeTypeId = "BILLING_EMAIL";
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (emailContactMechId == null) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
      inMap.put("emailAddress", emailAddress);
      inMap.put("partyId", partyId);
      inMap.put("roleTypeId", "CUSTOMER");
      inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us
      inMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
        emailContactMechId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);

    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
      inMap.clear();
      if (phoneNumber.startsWith("+")) {
        // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
        String[] phoneNumbers = phoneNumber.split(" ");
        inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
        inMap.put("contactNumber", phoneNumbers[1]);
      } else {
        // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
        inMap.put("countryCode", "1");
        String[] phoneNumbers = phoneNumber.split("-");
        inMap.put("areaCode", phoneNumbers[0]);
        inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
      }
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("partyId", partyId);
      try {
        outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
        phoneContactId = (String) outMap.get("contactMechId");
        cart.addContactMech("PHONE_BILLING", phoneContactId);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
      }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = FastMap.newInstance();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId =
        PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put(
        "stateProvinceGeoId",
        parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
      // We want an exact match only
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(postalMap),
                  EntityCondition.makeCondition(
                      UtilMisc.toMap(
                          "attnName",
                          null,
                          "directions",
                          null,
                          "postalCodeExt",
                          null,
                          "postalCodeGeoId",
                          null)),
                  EntityCondition.makeCondition("partyId", partyId)));
      try {
        GenericValue postalMatch =
            EntityQuery.use(delegator)
                .from("PartyAndPostalAddress")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (postalMatch != null) {
          postalContactId = postalMatch.getString("contactMechId");
          List<GenericValue> postalPurposes =
              EntityQuery.use(delegator)
                  .from("PartyContactMechPurpose")
                  .where("partyId", partyId, "contactMechId", postalContactId)
                  .filterByDate()
                  .queryList();
          List<Object> purposeStrings =
              EntityUtil.getFieldListFromEntityList(
                  postalPurposes, "contactMechPurposeTypeId", false);
          if (UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("SHIPPING_LOCATION")) {
            needsShippingPurpose = false;
          }
          if (needsBillingPurpose
              && UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("BILLING_LOCATION")) {
            needsBillingPurpose = false;
          }
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (postalContactId == null) {
      postalMap.put("userLogin", cart.getUserLogin());
      postalMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
        postalContactId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechId", postalContactId);
      inMap.put("partyId", partyId);
      try {
        if (needsShippingPurpose) {
          inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
        if (needsBillingPurpose) {
          inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
      } catch (GenericServiceException e) {
        // Not the end of the world, we'll carry on
        Debug.logInfo(e.getMessage(), module);
      }
    }

    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work
    // with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
      cart.setAllCarrierPartyId("_NA_");
      cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
      String[] shipMethodSplit = shipMethod.split(" - ");
      cart.setAllCarrierPartyId(shipMethodSplit[0]);
      String shippingMethodTypeDesc =
          StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
      try {
        GenericValue shipmentMethod =
            EntityQuery.use(delegator)
                .from("ProductStoreShipmentMethView")
                .where(
                    "productStoreId",
                    cart.getProductStoreId(),
                    "partyId",
                    shipMethodSplit[0],
                    "roleTypeId",
                    "CARRIER",
                    "description",
                    shippingMethodTypeDesc)
                .queryFirst();
        cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
      } catch (GenericEntityException e1) {
        Debug.logError(e1, module);
      }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
      Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
      for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
        cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
      }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result =
        ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
      return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }

    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
      shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
      cho.calcAndAddTax();
    } catch (GeneralException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));

    try {
      outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");

    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);

    return ServiceUtil.returnSuccess();
  }
Esempio n. 12
0
  public static Map<String, Object> payPalCheckoutUpdate(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    HttpServletRequest request = (HttpServletRequest) context.get("request");
    HttpServletResponse response = (HttpServletResponse) context.get("response");

    Map<String, Object> paramMap = UtilHttp.getParameterMap(request);

    String token = (String) paramMap.get("TOKEN");
    WeakReference<ShoppingCart> weakCart = tokenCartMap.get(new TokenWrapper(token));
    ShoppingCart cart = null;
    if (weakCart != null) {
      cart = weakCart.get();
    }
    if (cart == null) {
      Debug.logError("Could locate the ShoppingCart for token " + token, module);
      return ServiceUtil.returnSuccess();
    }
    // Since most if not all of the shipping estimate codes requires a persisted contactMechId we'll
    // create one and
    // then delete once we're done, now is not the time to worry about updating everything
    String contactMechId = null;
    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("address1", paramMap.get("SHIPTOSTREET"));
    inMap.put("address2", paramMap.get("SHIPTOSTREET2"));
    inMap.put("city", paramMap.get("SHIPTOCITY"));
    String countryGeoCode = (String) paramMap.get("SHIPTOCOUNTRY");
    String countryGeoId = PayPalServices.getCountryGeoIdFromGeoCode(countryGeoCode, delegator);
    if (countryGeoId == null) {
      return ServiceUtil.returnSuccess();
    }
    inMap.put("countryGeoId", countryGeoId);
    inMap.put(
        "stateProvinceGeoId",
        parseStateProvinceGeoId((String) paramMap.get("SHIPTOSTATE"), countryGeoId, delegator));
    inMap.put("postalCode", paramMap.get("SHIPTOZIP"));

    try {
      GenericValue userLogin =
          EntityQuery.use(delegator)
              .from("UserLogin")
              .where("userLoginId", "system")
              .cache()
              .queryOne();
      inMap.put("userLogin", userLogin);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    boolean beganTransaction = false;
    Transaction parentTransaction = null;
    try {
      parentTransaction = TransactionUtil.suspend();
      beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
      Debug.logError(e1, module);
    }
    try {
      Map<String, Object> outMap = dispatcher.runSync("createPostalAddress", inMap);
      contactMechId = (String) outMap.get("contactMechId");
    } catch (GenericServiceException e) {
      Debug.logError(e.getMessage(), module);
      return ServiceUtil.returnSuccess();
    }
    try {
      TransactionUtil.commit(beganTransaction);
      if (parentTransaction != null) TransactionUtil.resume(parentTransaction);
    } catch (GenericTransactionException e) {
      Debug.logError(e, module);
    }
    // clone the cart so we can modify it temporarily
    CheckOutHelper coh = new CheckOutHelper(dispatcher, delegator, cart);
    String oldShipAddress = cart.getShippingContactMechId();
    coh.setCheckOutShippingAddress(contactMechId);
    ShippingEstimateWrapper estWrapper = new ShippingEstimateWrapper(dispatcher, cart, 0);
    int line = 0;
    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "CallbackResponse");

    for (GenericValue shipMethod : estWrapper.getShippingMethods()) {
      BigDecimal estimate = estWrapper.getShippingEstimate(shipMethod);
      // Check that we have a valid estimate (allowing zero value estimates for now)
      if (estimate == null || estimate.compareTo(BigDecimal.ZERO) < 0) {
        continue;
      }
      cart.setAllShipmentMethodTypeId(shipMethod.getString("shipmentMethodTypeId"));
      cart.setAllCarrierPartyId(shipMethod.getString("partyId"));
      try {
        coh.calcAndAddTax();
      } catch (GeneralException e) {
        Debug.logError(e, module);
        continue;
      }
      String estimateLabel =
          shipMethod.getString("partyId") + " - " + shipMethod.getString("description");
      encoder.add("L_SHIPINGPOPTIONLABEL" + line, estimateLabel);
      encoder.add(
          "L_SHIPPINGOPTIONAMOUNT" + line,
          estimate.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
      // Just make this first one default for now
      encoder.add("L_SHIPPINGOPTIONISDEFAULT" + line, line == 0 ? "true" : "false");
      encoder.add(
          "L_TAXAMT" + line,
          cart.getTotalSalesTax().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
      line++;
    }
    String responseMsg = null;
    try {
      responseMsg = encoder.encode();
    } catch (PayPalException e) {
      Debug.logError(e, module);
    }
    if (responseMsg != null) {
      try {
        response.setContentLength(responseMsg.getBytes("UTF-8").length);
      } catch (UnsupportedEncodingException e) {
        Debug.logError(e, module);
      }

      try {
        Writer writer = response.getWriter();
        writer.write(responseMsg);
        writer.close();
      } catch (IOException e) {
        Debug.logError(e, module);
      }
    }

    // Remove the temporary ship address
    try {
      GenericValue postalAddress =
          EntityQuery.use(delegator)
              .from("PostalAddress")
              .where("contactMechId", contactMechId)
              .queryOne();
      postalAddress.remove();
      GenericValue contactMech =
          EntityQuery.use(delegator)
              .from("ContactMech")
              .where("contactMechId", contactMechId)
              .queryOne();
      contactMech.remove();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    coh.setCheckOutShippingAddress(oldShipAddress);
    return ServiceUtil.returnSuccess();
  }