/**
   * Copies a user preference group. Call with fromUserLoginId, userPrefGroupTypeId and optional
   * userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in user's
   * userLoginId will be used.
   *
   * @param ctx The DispatchContext that this service is operating in.
   * @param context Map containing the input arguments.
   * @return Map with the result of the service, the output parameters.
   */
  public static Map<String, Object> copyUserPreferenceGroup(
      DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    String userLoginId = PreferenceWorker.getUserLoginId(context, false);
    String fromUserLoginId = (String) context.get("fromUserLoginId");
    String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId");
    if (UtilValidate.isEmpty(userLoginId)
        || UtilValidate.isEmpty(userPrefGroupTypeId)
        || UtilValidate.isEmpty(fromUserLoginId)) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale));
    }

    try {
      Map<String, String> fieldMap =
          UtilMisc.toMap(
              "userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId);
      List<GenericValue> resultList = delegator.findByAnd("UserPreference", fieldMap);
      if (resultList != null) {
        for (GenericValue preference : resultList) {
          preference.set("userLoginId", userLoginId);
        }
        delegator.storeAll(resultList);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "copyPreference.writeFailure", new Object[] {e.getMessage()}, locale));
    }

    return ServiceUtil.returnSuccess();
  }
Beispiel #2
0
  /** Cause a Referential Integrity Error */
  public static Map<String, Object> entityFailTest(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    // attempt to create a DataSource entity w/ an invalid dataSourceTypeId
    GenericValue newEntity = delegator.makeValue("DataSource");
    newEntity.set("dataSourceId", "ENTITY_FAIL_TEST");
    newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST");
    newEntity.set("description", "Entity Fail Test - Delete me if I am here");
    try {
      delegator.create(newEntity);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "CommonEntityTestFailure", locale));
    }

    /*
    try {
        newEntity.remove();
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    */

    return ServiceUtil.returnSuccess();
  }
Beispiel #3
0
  public static GenericValue getPaymentAddress(Delegator delegator, String partyId) {
    List<GenericValue> paymentAddresses = null;
    try {
      paymentAddresses =
          delegator.findByAnd(
              "PartyContactMechPurpose",
              UtilMisc.toMap("partyId", partyId, "contactMechPurposeTypeId", "PAYMENT_LOCATION"),
              UtilMisc.toList("-fromDate"));
      paymentAddresses = EntityUtil.filterByDate(paymentAddresses);
    } catch (GenericEntityException e) {
      Debug.logError(e, "Trouble getting PartyContactMechPurpose entity list", module);
    }

    // get the address for the primary contact mech
    GenericValue purpose = EntityUtil.getFirst(paymentAddresses);
    GenericValue postalAddress = null;
    if (purpose != null) {
      try {
        postalAddress =
            delegator.findByPrimaryKey(
                "PostalAddress",
                UtilMisc.toMap("contactMechId", purpose.getString("contactMechId")));
      } catch (GenericEntityException e) {
        Debug.logError(
            e,
            "Trouble getting PostalAddress record for contactMechId: "
                + purpose.getString("contactMechId"),
            module);
      }
    }

    return postalAddress;
  }
  private static String getLastProductStoreId(Delegator delegator, String finAccountId) {
    GenericValue trans = null;
    try {
      trans =
          EntityQuery.use(delegator)
              .from("FinAccountTrans")
              .where(
                  EntityCondition.makeCondition(
                      "finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"),
                  EntityCondition.makeCondition(
                      "finAccountId", EntityOperator.EQUALS, finAccountId),
                  EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null))
              .orderBy("-transactionDate")
              .queryFirst();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    if (trans != null) {
      String orderId = trans.getString("orderId");
      OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
      return orh.getProductStoreId();
    }

    // none found; pick one from our set stores
    try {
      GenericValue store =
          EntityQuery.use(delegator).from("ProductStore").orderBy("productStoreId").queryFirst();
      if (store != null) return store.getString("productStoreId");
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    return null;
  }
Beispiel #5
0
  public static String getPartyName(GenericValue partyObject, boolean lastNameFirst) {
    if (partyObject == null) {
      return "";
    }
    if ("PartyGroup".equals(partyObject.getEntityName())
        || "Person".equals(partyObject.getEntityName())) {
      return formatPartyNameObject(partyObject, lastNameFirst);
    } else {
      String partyId = null;
      try {
        partyId = partyObject.getString("partyId");
      } catch (IllegalArgumentException e) {
        Debug.logError(e, "Party object does not contain a party ID", module);
      }

      if (partyId == null) {
        Debug.logWarning(
            "No party ID found; cannot get name based on entity: " + partyObject.getEntityName(),
            module);
        return "";
      } else {
        return getPartyName(partyObject.getDelegator(), partyId, lastNameFirst);
      }
    }
  }
    @Override
    public boolean eval(Map<String, Object> context) {
      // if no user is logged in, treat as if the user does not have permission
      GenericValue userLogin = (GenericValue) context.get("userLogin");
      if (userLogin != null) {
        String permission = permissionExdr.expandString(context);
        String action = actionExdr.expandString(context);

        Authorization authz = (Authorization) context.get("authz");
        Security security = (Security) context.get("security");
        if (UtilValidate.isNotEmpty(action)) {
          // Debug.logWarning("Deprecated method hasEntityPermission() was called; the action field
          // should no longer be used", module);
          // run hasEntityPermission
          if (security.hasEntityPermission(permission, action, userLogin)) {
            return true;
          }
        } else {
          // run hasPermission
          if (authz.hasPermission(userLogin.getString("userLoginId"), permission, context)) {
            return true;
          }
        }
      }
      return false;
    }
Beispiel #7
0
 /** Checks if the given party with role is assigned to the user login. */
 public static boolean isAssignedToUserLogin(
     String partyId, String roleTypeId, GenericValue userLogin) throws GenericEntityException {
   Delegator delegator = userLogin.getDelegator();
   String roleTypeIdTo =
       getFirstValidTeamMemberRoleTypeId(userLogin.getString("partyId"), delegator);
   if (roleTypeIdTo == null) {
     return false;
   }
   List<GenericValue> activeRelationships =
       EntityUtil.filterByDate(
           delegator.findByAnd(
               "PartyRelationship",
               UtilMisc.toMap(
                   "partyIdFrom",
                   partyId,
                   "roleTypeIdFrom",
                   roleTypeId,
                   "partyIdTo",
                   userLogin.get("partyId"),
                   "roleTypeIdTo",
                   roleTypeIdTo,
                   "partyRelationshipTypeId",
                   "ASSIGNED_TO")));
   return activeRelationships.size() > 0;
 }
Beispiel #8
0
  public static List<GenericValue> findParties(
      Delegator delegator, String idToFind, String partyIdentificationTypeId)
      throws GenericEntityException {
    List<GenericValue> partiesByIds =
        findPartiesById(delegator, idToFind, partyIdentificationTypeId);
    List<GenericValue> parties = null;
    if (UtilValidate.isNotEmpty(partiesByIds)) {
      for (GenericValue party : partiesByIds) {
        GenericValue partyToAdd = party;
        // retreive party GV if the actual genericValue came from viewEntity
        if (!"Party".equals(party.getEntityName())) {
          partyToAdd =
              delegator.findByPrimaryKeyCache(
                  "Party", UtilMisc.toMap("partyId", party.get("partyId")));
        }

        if (UtilValidate.isEmpty(parties)) {
          parties = UtilMisc.toList(partyToAdd);
        } else {
          parties.add(partyToAdd);
        }
      }
    }
    return parties;
  }
Beispiel #9
0
  public static String[] findFirstMatchingPartyAndContactMechId(
      Delegator delegator,
      String address1,
      String address2,
      String city,
      String stateProvinceGeoId,
      String postalCode,
      String postalCodeExt,
      String countryGeoId,
      String firstName,
      String middleName,
      String lastName)
      throws GeneralException {

    List<GenericValue> matching =
        findMatchingPersonPostalAddresses(
            delegator,
            address1,
            address2,
            city,
            stateProvinceGeoId,
            postalCode,
            postalCodeExt,
            countryGeoId,
            firstName,
            middleName,
            lastName);
    GenericValue v = EntityUtil.getFirst(matching);
    if (v != null) {
      return new String[] {v.getString("partyId"), v.getString("contactMechId")};
    }
    return null;
  }
Beispiel #10
0
  /**
   * Converts the supplied String into a String suitable for address line matching. Performs the
   * following transformations on the supplied String: - Converts to upper case - Retrieves all
   * records from the AddressMatchMap table and replaces all occurrences of addressMatchMap.mapKey
   * with addressMatchMap.mapValue using upper case matching. - Removes all non-word characters from
   * the String i.e. everything except A-Z, 0-9 and _
   *
   * @param delegator A Delegator instance
   * @param address The address String to convert
   * @return The converted Address
   */
  public static String makeMatchingString(Delegator delegator, String address) {
    if (address == null) {
      return null;
    }

    // upper case the address
    String str = address.trim().toUpperCase();

    // replace mapped words
    List<GenericValue> addressMap = null;
    try {
      addressMap =
          delegator.findList(
              "AddressMatchMap", null, null, UtilMisc.toList("sequenceNum"), null, false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }

    if (addressMap != null) {
      for (GenericValue v : addressMap) {
        str =
            str.replaceAll(
                v.getString("mapKey").toUpperCase(), v.getString("mapValue").toUpperCase());
      }
    }

    // remove all non-word characters
    return str.replaceAll("\\W", "");
  }
  public static void getCategoryContentWrappers(
      Map<String, CategoryContentWrapper> catContentWrappers,
      List<GenericValue> categoryList,
      HttpServletRequest request)
      throws GenericEntityException {
    if (catContentWrappers == null || categoryList == null) {
      return;
    }
    for (GenericValue cat : categoryList) {
      String productCategoryId = (String) cat.get("productCategoryId");

      if (catContentWrappers.containsKey(productCategoryId)) {
        // if this ID is already in the Map, skip it (avoids inefficiency, infinite recursion, etc.)
        continue;
      }

      CategoryContentWrapper catContentWrapper = new CategoryContentWrapper(cat, request);
      catContentWrappers.put(productCategoryId, catContentWrapper);
      List<GenericValue> subCat =
          getRelatedCategoriesRet(request, "subCatList", productCategoryId, true);
      if (subCat != null) {
        getCategoryContentWrappers(catContentWrappers, subCat, request);
      }
    }
  }
Beispiel #12
0
 public static String formatPartyNameObject(GenericValue partyValue, boolean lastNameFirst) {
   if (partyValue == null) {
     return "";
   }
   StringBuilder result = new StringBuilder();
   ModelEntity modelEntity = partyValue.getModelEntity();
   if (modelEntity.isField("firstName")
       && modelEntity.isField("middleName")
       && modelEntity.isField("lastName")) {
     if (lastNameFirst) {
       if (UtilFormatOut.checkNull(partyValue.getString("lastName")) != null) {
         result.append(UtilFormatOut.checkNull(partyValue.getString("lastName")));
         if (partyValue.getString("firstName") != null) {
           result.append(", ");
         }
       }
       result.append(UtilFormatOut.checkNull(partyValue.getString("firstName")));
     } else {
       result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("firstName"), "", " "));
       result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("middleName"), "", " "));
       result.append(UtilFormatOut.checkNull(partyValue.getString("lastName")));
     }
   }
   if (modelEntity.isField("groupName") && partyValue.get("groupName") != null) {
     result.append(partyValue.getString("groupName"));
   }
   return result.toString();
 }
Beispiel #13
0
  private static NVPDecoder sendNVPRequest(GenericValue payPalConfig, NVPEncoder encoder)
      throws PayPalException {
    NVPCallerServices caller = new NVPCallerServices();
    try {
      APIProfile profile = ProfileFactory.createSignatureAPIProfile();
      profile.setAPIUsername(payPalConfig.getString("apiUserName"));
      profile.setAPIPassword(payPalConfig.getString("apiPassword"));
      profile.setSignature(payPalConfig.getString("apiSignature"));
      profile.setEnvironment(payPalConfig.getString("apiEnvironment"));
      caller.setAPIProfile(profile);
    } catch (PayPalException e) {
      Debug.logError(e.getMessage(), module);
    }

    String requestMessage = encoder.encode();
    String responseMessage = caller.call(requestMessage);

    NVPDecoder decoder = new NVPDecoder();
    decoder.decode(responseMessage);
    if (!"Success".equals(decoder.get("ACK"))) {
      Debug.logError(
          "A response other than success was received from PayPal: " + responseMessage, module);
    }

    return decoder;
  }
Beispiel #14
0
  private static String parseStateProvinceGeoId(
      String payPalShipToState, String countryGeoId, Delegator delegator) {
    String lookupField = "geoName";
    List<EntityCondition> conditionList = FastList.newInstance();
    conditionList.add(EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"));
    if ("USA".equals(countryGeoId) || "CAN".equals(countryGeoId)) {
      // PayPal returns two letter code for US and Canadian States/Provinces
      String geoTypeId = "USA".equals(countryGeoId) ? "STATE" : "PROVINCE";
      conditionList.add(EntityCondition.makeCondition("geoTypeId", geoTypeId));
      lookupField = "geoCode";
    }
    conditionList.add(EntityCondition.makeCondition("geoIdFrom", countryGeoId));
    conditionList.add(EntityCondition.makeCondition(lookupField, payPalShipToState));
    EntityCondition cond = EntityCondition.makeCondition(conditionList);
    GenericValue geoAssocAndGeoTo = null;
    try {
      geoAssocAndGeoTo =
          EntityQuery.use(delegator).from("GeoAssocAndGeoTo").where(cond).cache().queryFirst();

    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    if (geoAssocAndGeoTo != null) {
      return geoAssocAndGeoTo.getString("geoId");
    }
    return null;
  }
  public void renderPortalPagePortletBody(
      Appendable writer,
      Map<String, Object> context,
      ModelScreenWidget.PortalPage portalPage,
      GenericValue portalPortlet)
      throws GeneralException, IOException {
    String portalPortletId = portalPortlet.getString("portalPortletId");
    String screenName = portalPortlet.getString("screenName");
    String screenLocation = portalPortlet.getString("screenLocation");

    ModelScreen modelScreen = null;
    if (UtilValidate.isNotEmpty(screenName) && UtilValidate.isNotEmpty(screenLocation)) {
      try {
        modelScreen = ScreenFactory.getScreenFromLocation(screenLocation, screenName);
      } catch (IOException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (SAXException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      } catch (ParserConfigurationException e) {
        String errMsg = "Error rendering portlet ID [" + portalPortletId + "]: " + e.toString();
        Debug.logError(e, errMsg, module);
        throw new RuntimeException(errMsg);
      }
    }
    modelScreen.renderScreenString(writer, context, this);
  }
  public static boolean isBinComplete(Delegator delegator, String picklistBinId)
      throws GeneralException {
    // lookup the items in the bin
    List<GenericValue> items;
    try {
      items = delegator.findByAnd("PicklistItem", UtilMisc.toMap("picklistBinId", picklistBinId));
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      throw e;
    }

    if (!UtilValidate.isEmpty(items)) {
      for (GenericValue v : items) {
        String itemStatus = v.getString("itemStatusId");
        if (itemStatus != null) {
          if (!"PICKITEM_COMPLETED".equals(itemStatus)) {
            return false;
          }
        }
      }
      return true;
    }

    return false;
  }
Beispiel #17
0
  @Override
  public boolean exec(MethodContext methodContext) {
    // if anything but false it will be true
    boolean setIfNull = !"false".equals(methodContext.expandString(setIfNullStr));

    GenericValue value = valueAcsr.get(methodContext);
    if (value == null) {
      String errMsg =
          "In set-pk-fields a value was not found with the specified valueAcsr: "
              + valueAcsr
              + ", not setting fields";

      Debug.logWarning(errMsg, module);
      if (methodContext.getMethodType() == MethodContext.EVENT) {
        methodContext.putEnv(simpleMethod.getEventErrorMessageName(), errMsg);
        methodContext.putEnv(
            simpleMethod.getEventResponseCodeName(), simpleMethod.getDefaultErrorCode());
      } else if (methodContext.getMethodType() == MethodContext.SERVICE) {
        methodContext.putEnv(simpleMethod.getServiceErrorMessageName(), errMsg);
        methodContext.putEnv(
            simpleMethod.getServiceResponseMessageName(), simpleMethod.getDefaultErrorCode());
      }
      return false;
    }

    Map<String, ? extends Object> theMap = mapAcsr.get(methodContext);
    if (theMap == null) {
      Debug.logWarning(
          "In set-pk-fields could not find map with name " + mapAcsr + ", not setting any fields",
          module);
    } else {
      value.setPKFields(theMap, setIfNull);
    }
    return true;
  }
  public static boolean isProductInCategory(
      Delegator delegator, String productId, String productCategoryId)
      throws GenericEntityException {
    if (productCategoryId == null) return false;
    if (UtilValidate.isEmpty(productId)) return false;

    List<GenericValue> productCategoryMembers =
        EntityUtil.filterByDate(
            delegator.findByAndCache(
                "ProductCategoryMember",
                UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId)),
            true);
    if (UtilValidate.isEmpty(productCategoryMembers)) {
      // before giving up see if this is a variant product, and if so look up the virtual product
      // and check it...
      GenericValue product =
          delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", productId));
      List<GenericValue> productAssocs = ProductWorker.getVariantVirtualAssocs(product);
      // this does take into account that a product could be a variant of multiple products, but
      // this shouldn't ever really happen...
      if (productAssocs != null) {
        for (GenericValue productAssoc : productAssocs) {
          if (isProductInCategory(
              delegator, productAssoc.getString("productId"), productCategoryId)) {
            return true;
          }
        }
      }

      return false;
    } else {
      return true;
    }
  }
  public static RecurrenceRule makeRule(
      Delegator delegator, int frequency, int interval, int count, long endTime)
      throws RecurrenceRuleException {
    String freq[] = {"", "SECONDLY", "MINUTELY", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};

    if (frequency < 1 || frequency > 7) throw new RecurrenceRuleException("Invalid frequency");
    if (interval < 0) throw new RecurrenceRuleException("Invalid interval");

    String freqStr = freq[frequency];

    try {
      GenericValue value = delegator.makeValue("RecurrenceRule");

      value.set("frequency", freqStr);
      value.set("intervalNumber", Long.valueOf(interval));
      value.set("countNumber", Long.valueOf(count));
      if (endTime > 0) {
        value.set("untilDateTime", new java.sql.Timestamp(endTime));
      }
      delegator.createSetNextSeqId(value);
      RecurrenceRule newRule = new RecurrenceRule(value);
      return newRule;
    } catch (GenericEntityException ee) {
      throw new RecurrenceRuleException(ee.getMessage(), ee);
    } catch (RecurrenceRuleException re) {
      throw re;
    }
  }
Beispiel #20
0
  public static Map<String, Object> doAuthorization(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    String orderId = (String) context.get("orderId");
    BigDecimal processAmount = (BigDecimal) context.get("processAmount");
    GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    GenericValue payPalConfig =
        getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    Locale locale = (Locale) context.get("locale");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoAuthorization");
    encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId"));
    encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("TRANSACTIONENTITY", "Order");
    String currency = (String) context.get("currency");
    if (currency == null) {
      currency = orh.getCurrency();
    }
    encoder.add("CURRENCYCODE", currency);

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

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("authResult", false);
      result.put("authRefNum", "N/A");
      result.put("processAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("authCode", error.getKey());
        result.put("authMessage", error.getValue());
      } else {
        result.put(
            "authMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("authResult", true);
      result.put("processAmount", new BigDecimal(decoder.get("AMT")));
      result.put("authRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what
    // should be checked for this type of transaction
    return result;
  }
  /**
   * Finds or creates a specialized (auto-save) shopping list used to record shopping bag contents
   * between user visits.
   */
  public static String getAutoSaveListId(
      Delegator delegator,
      LocalDispatcher dispatcher,
      String partyId,
      GenericValue userLogin,
      String productStoreId)
      throws GenericEntityException, GenericServiceException {
    if (partyId == null && userLogin != null) {
      partyId = userLogin.getString("partyId");
    }

    String autoSaveListId = null;
    GenericValue list = null;
    // TODO: add sorting, just in case there are multiple...
    if (partyId != null) {
      Map<String, Object> findMap =
          UtilMisc.<String, Object>toMap(
              "partyId",
              partyId,
              "productStoreId",
              productStoreId,
              "shoppingListTypeId",
              "SLT_SPEC_PURP",
              "listName",
              PERSISTANT_LIST_NAME);
      List<GenericValue> existingLists =
          EntityQuery.use(delegator).from("ShoppingList").where(findMap).queryList();
      Debug.logInfo(
          "Finding existing auto-save shopping list with:  \nfindMap: "
              + findMap
              + "\nlists: "
              + existingLists,
          module);

      if (UtilValidate.isNotEmpty(existingLists)) {
        list = EntityUtil.getFirst(existingLists);
        autoSaveListId = list.getString("shoppingListId");
      }
    }
    if (list == null && dispatcher != null) {
      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");
      }
    }

    return autoSaveListId;
  }
Beispiel #22
0
 /**
  * Check if the party has been deactivated.
  *
  * @param partyId
  * @param delegator
  * @return is active
  * @throws GenericEntityNotFoundException
  */
 public static boolean isActive(String partyId, Delegator delegator)
     throws GenericEntityException {
   GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));
   if (party == null) {
     throw new GenericEntityNotFoundException("No Party found with ID: " + partyId);
   }
   return (!"PARTY_DISABLED".equals(party.getString("statusId")));
 }
  public static Map<String, Object> updateContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    String contactPartyId = (String) context.get("partyId");

    // make sure userLogin has CRMSFA_CONTACT_UPDATE permission for this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_UPDATE", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }
    try {
      // update the Party and Person
      Map<String, Object> input =
          UtilMisc.<String, Object>toMap(
              "partyId",
              contactPartyId,
              "firstName",
              context.get("firstName"),
              "lastName",
              context.get("lastName"));
      input.put("firstNameLocal", context.get("firstNameLocal"));
      input.put("lastNameLocal", context.get("lastNameLocal"));
      input.put("personalTitle", context.get("personalTitle"));
      input.put("preferredCurrencyUomId", context.get("preferredCurrencyUomId"));
      input.put("description", context.get("description"));
      input.put("birthDate", context.get("birthDate"));
      input.put("userLogin", userLogin);
      Map<String, Object> serviceResults = dispatcher.runSync("updatePerson", input);
      if (ServiceUtil.isError(serviceResults)) {
        return UtilMessage.createAndLogServiceError(
            serviceResults, "CrmErrorUpdateContactFail", locale, MODULE);
      }

      // update PartySupplementalData
      GenericValue partyData =
          delegator.findByPrimaryKey(
              "PartySupplementalData", UtilMisc.toMap("partyId", contactPartyId));
      if (partyData == null) {
        // create a new one
        partyData =
            delegator.makeValue("PartySupplementalData", UtilMisc.toMap("partyId", contactPartyId));
        partyData.create();
      }
      partyData.setNonPKFields(context);
      partyData.store();

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Beispiel #24
0
  public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) {
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
    GenericValue payPalConfig =
        getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE);
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    Locale locale = (Locale) context.get("locale");
    if (authTrans == null) {
      authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
    }

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoCapture");
    encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum"));
    encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId"));
    encoder.add("COMPLETETYPE", "NotComplete");

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

    if (decoder == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale));
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    Map<String, String> errors = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errors)) {
      result.put("captureResult", false);
      result.put("captureRefNum", "N/A");
      result.put("captureAmount", BigDecimal.ZERO);
      if (errors.size() == 1) {
        Map.Entry<String, String> error = errors.entrySet().iterator().next();
        result.put("captureCode", error.getKey());
        result.put("captureMessage", error.getValue());
      } else {
        result.put(
            "captureMessage",
            "Multiple errors occurred, please refer to the gateway response messages");
        result.put("internalRespMsgs", errors);
      }
    } else {
      result.put("captureResult", true);
      result.put("captureAmount", new BigDecimal(decoder.get("AMT")));
      result.put("captureRefNum", decoder.get("TRANSACTIONID"));
    }
    // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what
    // should be checked for this type of transaction
    return result;
  }
Beispiel #25
0
 private static boolean hasChildrenAttr(
     List<GenericValue> monitors, String parentAttr, String id) {
   if (id == null) return false;
   if (parentAttr == null) return true;
   for (GenericValue val : monitors) {
     if (!id.equals(val.getString("id"))) continue;
     if (parentAttr.equals(val.getString("parentAttrName"))) return true;
   }
   return false;
 }
 public void setProcessMgrName(String s) {
   process.set(org.ofbiz.shark.SharkConstants.mgrName, s);
   try {
     ProcessMgrPersistenceInterface pm = mgr.restoreProcessMgr(s, null);
     process.set(org.ofbiz.shark.SharkConstants.packageId, pm.getPackageId());
     process.set(org.ofbiz.shark.SharkConstants.packageVer, pm.getVersion());
   } catch (PersistenceException e) {
     Debug.logError(e, "Unable to set package information", module);
   }
 }
Beispiel #27
0
 public static String findPartyId(
     Delegator delegator, String idToFind, String partyIdentificationTypeId)
     throws GenericEntityException {
   GenericValue party = findParty(delegator, idToFind, partyIdentificationTypeId);
   if (UtilValidate.isNotEmpty(party)) {
     return party.getString("partyId");
   } else {
     return null;
   }
 }
Beispiel #28
0
  public static void checkPathAlias(
      ServletRequest request, ServletResponse response, Delegator delegator, String pathInfo) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String webSiteId = WebSiteWorker.getWebSiteId(request);
    // check path alias
    GenericValue pathAlias = null;
    try {
      pathAlias =
          EntityQuery.use(delegator)
              .from("WebSitePathAlias")
              .where("webSiteId", webSiteId, "pathAlias", pathInfo)
              .cache()
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
    }
    if (pathAlias != null) {
      String alias = pathAlias.getString("aliasTo");
      String contentId = pathAlias.getString("contentId");
      if (contentId == null && UtilValidate.isNotEmpty(alias)) {
        if (!alias.startsWith("/")) {
          alias = "/" + alias;
        }

        RequestDispatcher rd = request.getRequestDispatcher(alias);
        try {
          rd.forward(request, response);
          return;
        } catch (ServletException e) {
          Debug.logWarning(e, module);
        } catch (IOException e) {
          Debug.logWarning(e, module);
        }
      }
    } else {
      // send 404 error if a URI is alias TO
      try {
        List<GenericValue> aliasTos =
            EntityQuery.use(delegator)
                .from("WebSitePathAlias")
                .where("webSiteId", webSiteId, "aliasTo", httpRequest.getRequestURI())
                .queryList();
        if (UtilValidate.isNotEmpty(aliasTos)) {
          httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND, "Not Found");
          return;
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      } catch (IOException e) {
        Debug.logError(e, module);
      }
    }
  }
 public static Map<String, Object> createCmsCatalog(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Map result = ServiceUtil.returnSuccess();
   Delegator delegator = dctx.getDelegator();
   String catalogId = delegator.getNextSeqId("CmsCatalog");
   GenericValue gv = delegator.makeValue("CmsCatalog", UtilMisc.toMap("catalogId", catalogId));
   gv.setNonPKFields(context);
   gv.create();
   result.put("catalogId", catalogId);
   return result;
 }
 public static Map<String, Object> deleteCmsCatalog(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Delegator delegator = dctx.getDelegator();
   String catalogId = (String) context.get("catalogId");
   GenericValue gv =
       delegator.findByPrimaryKey("CmsCatalog", UtilMisc.toMap("catalogId", catalogId));
   if (UtilValidate.isNotEmpty(gv)) {
     gv.remove();
   }
   return ServiceUtil.returnSuccess();
 }