Example #1
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;
  }
Example #2
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;
  }
Example #3
0
  /**
   * Retrieve the last deactivation date if the party is currently deactivated.
   *
   * @param partyId
   * @param delegator
   * @return the timestamp of last deactivation, null if the party is not deactivated
   * @throws GenericEntityNotFoundException
   */
  public static Timestamp getDeactivationDate(String partyId, Delegator delegator)
      throws GenericEntityException {
    // check party current status:
    if (isActive(partyId, delegator)) {
      return null;
    }

    // party is currently deactivated, get the deactivation date
    try {

      List<GenericValue> deactivationDates =
          delegator.findByAnd(
              "PartyDeactivation",
              UtilMisc.toMap("partyId", partyId),
              UtilMisc.toList("-deactivationTimestamp"));
      if (UtilValidate.isNotEmpty(deactivationDates)) {
        return (Timestamp) deactivationDates.get(0).get("deactivationTimestamp");
      } else {
        Debug.logWarning(
            "The party ["
                + partyId
                + "] status is disabled but there is no registered deactivation date.",
            MODULE);
      }

    } catch (GenericEntityException e) {
      Debug.logError(e, MODULE);
    }
    return null;
  }
Example #4
0
  public static Map<String, GenericValue> getPartyOtherValues(
      ServletRequest request,
      String partyId,
      String partyAttr,
      String personAttr,
      String partyGroupAttr) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Map<String, GenericValue> result = FastMap.newInstance();
    try {
      GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));

      if (party != null) result.put(partyAttr, party);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting Party entity", module);
    }

    try {
      GenericValue person =
          delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId));

      if (person != null) result.put(personAttr, person);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting Person entity", module);
    }

    try {
      GenericValue partyGroup =
          delegator.findByPrimaryKey("PartyGroup", UtilMisc.toMap("partyId", partyId));

      if (partyGroup != null) result.put(partyGroupAttr, partyGroup);
    } catch (GenericEntityException e) {
      Debug.logWarning(e, "Problems getting PartyGroup entity", module);
    }
    return result;
  }
Example #5
0
  /**
   * Performs a cascade delete on a party.
   *
   * <p>One reason this method can fail is that there were relationships with entities that are not
   * being deleted. If a party is not being deleted like it should, the developer should take a look
   * at the exception thrown by this method to see if any relations were violated. If there were
   * violations, consider adding the entities to the CASCADE array above.
   *
   * <p>XXX Warning, this method is very brittle. It is essentially emulating the ON DELETE CASCADE
   * functionality of well featured databases, but very poorly. As the datamodel evolves, this
   * method would have to be updated.
   */
  public static void deleteCrmParty(String partyId, Delegator delegator)
      throws GenericEntityException {
    // remove related entities from constant list
    for (int i = 0; i < CRM_PARTY_DELETE_CASCADE.length; i++) {
      String entityName = CRM_PARTY_DELETE_CASCADE[i][0];
      String fieldName = CRM_PARTY_DELETE_CASCADE[i][1];

      Map<String, Object> input = UtilMisc.<String, Object>toMap(fieldName, partyId);
      delegator.removeByAnd(entityName, input);
    }

    // remove communication events
    GenericValue party = delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", partyId));
    List<GenericValue> commEvnts = FastList.<GenericValue>newInstance();
    commEvnts.addAll(party.getRelated("ToCommunicationEvent"));
    commEvnts.addAll(party.getRelated("FromCommunicationEvent"));
    for (GenericValue commEvnt : commEvnts) {
      commEvnt.removeRelated("CommunicationEventRole");
      commEvnt.removeRelated("CommunicationEventWorkEff");
      commEvnt.removeRelated("CommEventContentAssoc");
      delegator.removeValue(commEvnt);
    }

    // finally remove party
    delegator.removeValue(party);
  }
Example #6
0
  private static EntityCondition getActiveClientPartiesCondition(
      LocalDispatcher dispatcher, Map<String, ?> parameters, List<String> roles, EntityCondition ec)
      throws GeneralException {
    Map<String, Object> results =
        dispatcher.runSync(
            "prepareFind",
            UtilMisc.toMap(
                "entityName",
                "PartyFromSummaryByRelationship",
                "inputFields",
                parameters,
                "filterByDate",
                "Y",
                "noConditionFind",
                "N"));
    if (ServiceUtil.isError(results)) {
      throw new GenericServiceException(ServiceUtil.getErrorMessage(results));
    }
    EntityCondition findConditions = (EntityCondition) results.get("entityConditionList");
    if (findConditions == null) {
      return null;
    }

    List<String> conditionRoles = (roles == null || roles.size() == 0 ? CLIENT_PARTY_ROLES : roles);
    List<EntityCondition> combinedConditions =
        UtilMisc.<EntityCondition>toList(
            findConditions,
            EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.IN, conditionRoles));
    if (ec != null) {
      combinedConditions.add(ec);
    }

    return EntityCondition.makeCondition(combinedConditions, EntityOperator.AND);
  }
  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;
    }
  }
Example #8
0
  /**
   * 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;
  }
  /**
   * Remove a party attribute entity.
   *
   * @exception ServiceException if an error occurs
   */
  public void removePartyAttribute() throws ServiceException {
    try {
      String roleTypeId =
          PartyHelper.getFirstValidRoleTypeId(
              partyId, VALID_PARTY_ROLES, getInfrastructure().getDelegator());
      if (roleTypeId == null) {
        throw new ServiceException(
            "CrmError_InvalidPartyRoleOnCustomFields", UtilMisc.toMap("partyId", partyId));
      }
      String securityModule = null;
      if ("PROSPECT".equals(roleTypeId)) {
        securityModule = "CRMSFA_LEAD";
      } else if ("ACCOUNT".equals(roleTypeId)) {
        securityModule = "CRMSFA_ACCOUNT";
      } else if ("CONTACT".equals(roleTypeId)) {
        securityModule = "CRMSFA_CONTACT";
      }

      Session session = getInfrastructure().getSession();

      // check if existing same party attribute alreay
      String hql =
          "from PartyAttribute eo where eo.id.partyId = :partyId and eo.id.attrName = :attrName";
      Query query = session.createQuery(hql);
      query.setString("partyId", partyId);
      query.setString("attrName", attrName);
      List<PartyAttribute> attributes = query.list();
      if (attributes.size() == 0) {
        throw new ServiceException(
            "CrmError_NotExistingTheCustomField",
            UtilMisc.toMap("partyId", partyId, "attrName", attrName));
      }
      PartyAttribute attribute = attributes.get(0);
      // DELETE permission is required to delete the custom fields if the user was not the original
      // creator of the custom field.
      if (attribute.getCreatedByUserLoginId().equals(this.getUser().getUserId())
          || CrmsfaSecurity.hasPartyRelationSecurity(
              security, securityModule, "_CUST_DELETE", getUser().getOfbizUserLogin(), partyId)) {
        session.delete(attribute);
        session.flush();
      } else {
        String err =
            UtilMessage.getPermissionDeniedError(locale)
                + ": user ["
                + getUser().getUserId()
                + "] does not have permission "
                + securityModule
                + "_CUST_DELETE";
        throw new ServiceException(err);
      }
      session.close();

    } catch (GenericEntityException e) {
      throw new ServiceException(e);
    } catch (InfrastructureException e) {
      throw new ServiceException(e);
    }
  }
Example #10
0
  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();
  }
Example #11
0
 /** Finds active Leads for a party. */
 public static EntityListIterator findActiveLeads(
     Delegator delegator, LocalDispatcher dispatcher, String partyId) throws GeneralException {
   return findActiveClientParties(
       delegator,
       dispatcher,
       UtilMisc.toMap("partyIdTo", partyId),
       UtilMisc.toList("PROSPECT"),
       null);
 }
Example #12
0
  /** Remove all items from the given list. */
  public static int clearListInfo(Delegator delegator, String shoppingListId)
      throws GenericEntityException {
    // remove the survey responses first
    delegator.removeByAnd(
        "ShoppingListItemSurvey", UtilMisc.toMap("shoppingListId", shoppingListId));

    // next remove the items
    return delegator.removeByAnd(
        "ShoppingListItem", UtilMisc.toMap("shoppingListId", shoppingListId));
  }
Example #13
0
  public static Map<String, Object> deactivateContact(
      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);

    // what contact we're expiring
    String contactPartyId = (String) context.get("partyId");

    // check that userLogin has CRMSFA_CONTACT_DEACTIVATE permission for this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_DEACTIVATE", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }

    // when to expire the contact
    Timestamp expireDate = (Timestamp) context.get("expireDate");
    if (expireDate == null) {
      expireDate = UtilDateTime.nowTimestamp();
    }

    // in order to deactivate a contact, we expire all party relationships on the expire date
    try {
      List<GenericValue> partyRelationships =
          delegator.findByAnd(
              "PartyRelationship",
              UtilMisc.toMap("partyIdFrom", contactPartyId, "roleTypeIdFrom", "CONTACT"));
      PartyHelper.expirePartyRelationships(partyRelationships, expireDate, dispatcher, userLogin);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateContactFail", locale, MODULE);
    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateContactFail", locale, MODULE);
    }

    // set the party statusId to PARTY_DISABLED and register the PartyDeactivation
    try {
      GenericValue contactParty =
          delegator.findByPrimaryKey("Party", UtilMisc.toMap("partyId", contactPartyId));
      contactParty.put("statusId", "PARTY_DISABLED");
      contactParty.store();

      delegator.create(
          "PartyDeactivation",
          UtilMisc.toMap("partyId", contactPartyId, "deactivationTimestamp", expireDate));
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateAccountFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Example #14
0
  public static List<GenericValue> getGroupValues(String groupId, String stype) throws Exception {
    EntityCondition whereCondition =
        EntityCondition.makeCondition(
            UtilMisc.toList(
                EntityCondition.makeCondition("groupId", EntityOperator.EQUALS, groupId),
                EntityCondition.makeCondition("stype", EntityOperator.EQUALS, stype)),
            EntityOperator.AND);

    return getDelegator()
        .findList("SvGroupValue", whereCondition, null, UtilMisc.toList("idx"), null, false);
  }
 /**
  * Returns a complete category trail - can be used for exporting proper category trees. This is
  * mostly useful when used in combination with bread-crumbs, for building a faceted index tree, or
  * to export a category tree for migration to another system. Will create the tree from root point
  * to categoryId.
  *
  * <p>This method is not meant to be run on every request. Its best use is to generate the trail
  * every so often and store somewhere (a lucene/solr tree, entities, cache or so).
  *
  * @param productCategoryId id of category the trail should be generated for
  * @returns List organized trail from root point to categoryId.
  */
 public static Map getCategoryTrail(DispatchContext dctx, Map context) {
   String productCategoryId = (String) context.get("productCategoryId");
   Map<String, Object> results = ServiceUtil.returnSuccess();
   GenericDelegator delegator = (GenericDelegator) dctx.getDelegator();
   List<String> trailElements = FastList.newInstance();
   trailElements.add(productCategoryId);
   String parentProductCategoryId = productCategoryId;
   while (UtilValidate.isNotEmpty(parentProductCategoryId)) {
     // find product category rollup
     try {
       List<EntityCondition> rolllupConds = FastList.newInstance();
       rolllupConds.add(
           EntityCondition.makeCondition("productCategoryId", parentProductCategoryId));
       rolllupConds.add(EntityUtil.getFilterByDateExpr());
       List<GenericValue> productCategoryRollups =
           delegator.findList(
               "ProductCategoryRollup",
               EntityCondition.makeCondition(rolllupConds),
               null,
               UtilMisc.toList("sequenceNum"),
               null,
               true);
       if (UtilValidate.isNotEmpty(productCategoryRollups)) {
         // add only categories that belong to the top category to trail
         for (GenericValue productCategoryRollup : productCategoryRollups) {
           String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId");
           parentProductCategoryId = trailCategoryId;
           if (trailElements.contains(trailCategoryId)) {
             break;
           } else {
             trailElements.add(trailCategoryId);
           }
         }
       } else {
         parentProductCategoryId = null;
       }
     } catch (GenericEntityException e) {
       Map<String, String> messageMap =
           UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. ");
       String errMsg =
           UtilProperties.getMessage(
               "CommonUiLabels",
               "CommonDatabaseProblem",
               messageMap,
               (Locale) context.get("locale"));
       Debug.logError(e, errMsg, module);
       return ServiceUtil.returnError(errMsg);
     }
   }
   Collections.reverse(trailElements);
   results.put("trail", trailElements);
   return results;
 }
Example #16
0
  /**
   * Generic service to find party by id. By default return the party find by partyId but you can
   * pass searchPartyFirst at false if you want search in partyIdentification before or pass
   * searchAllId at true to find apartyuct with this id (party.partyId and
   * partyIdentification.idValue)
   *
   * @param delegator
   * @param idToFind
   * @param partyIdentificationTypeId
   * @param searchPartyFirst
   * @param searchAllId
   * @return
   * @throws GenericEntityException
   */
  public static List<GenericValue> findPartiesById(
      Delegator delegator,
      String idToFind,
      String partyIdentificationTypeId,
      boolean searchPartyFirst,
      boolean searchAllId)
      throws GenericEntityException {

    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: entered id = "
              + idToFind
              + ", partyIdentificationTypeId = "
              + partyIdentificationTypeId,
          module);

    GenericValue party = null;
    List<GenericValue> partiesFound = null;

    // 1) look if the idToFind given is a real partyId
    if (searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (searchAllId || (searchPartyFirst && UtilValidate.isEmpty(party))) {
      // 2) Retrieve party in PartyIdentification
      Map<String, String> conditions = UtilMisc.toMap("idValue", idToFind);
      if (UtilValidate.isNotEmpty(partyIdentificationTypeId)) {
        conditions.put("partyIdentificationTypeId", partyIdentificationTypeId);
      }
      partiesFound =
          delegator.findByAndCache(
              "PartyIdentificationAndParty", conditions, UtilMisc.toList("partyId"));
    }

    if (!searchPartyFirst) {
      party = delegator.findByPrimaryKeyCache("Party", UtilMisc.toMap("partyId", idToFind));
    }

    if (UtilValidate.isNotEmpty(party)) {
      if (UtilValidate.isNotEmpty(partiesFound)) partiesFound.add(party);
      else partiesFound = UtilMisc.toList(party);
    }
    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: found party.partyId = "
              + party
              + ", and list : "
              + partiesFound,
          module);
    return partiesFound;
  }
Example #17
0
  private static List<String> getActiveClientPartiesOrderBy(Map<String, ?> parameters) {
    List<String> orderBy =
        UtilMisc.toList("groupName", "lastName", "companyName"); // fields to order by (default)

    // see if we're given a different order by
    String requestOrderBy = (String) parameters.get("activeOrderBy");
    if ("lastName".equals(requestOrderBy)) {
      orderBy = UtilMisc.toList("lastName", "groupName", "companyName");
    } else if ("companyName".equals(requestOrderBy)) {
      orderBy = UtilMisc.toList("companyName", "groupName", "lastName");
    }
    return orderBy;
  }
Example #18
0
  /**
   * JavaMail Service that gets body content from a URL
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param rcontext Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> sendMailFromUrl(
      DispatchContext ctx, Map<String, ? extends Object> rcontext) {
    // pretty simple, get the content and then call the sendMail method below
    Map<String, Object> sendMailContext = UtilMisc.makeMapWritable(rcontext);
    String bodyUrl = (String) sendMailContext.remove("bodyUrl");
    Map<String, Object> bodyUrlParameters =
        UtilGenerics.checkMap(sendMailContext.remove("bodyUrlParameters"));
    Locale locale = (Locale) rcontext.get("locale");
    LocalDispatcher dispatcher = ctx.getDispatcher();

    URL url = null;

    try {
      url = new URL(bodyUrl);
    } catch (MalformedURLException e) {
      Debug.logWarning(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendMalformedUrl",
              UtilMisc.toMap("bodyUrl", bodyUrl, "errorString", e.toString()),
              locale));
    }

    HttpClient httpClient = new HttpClient(url, bodyUrlParameters);
    String body = null;

    try {
      body = httpClient.post();
    } catch (HttpClientException e) {
      Debug.logWarning(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonEmailSendGettingError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }

    sendMailContext.put("body", body);
    Map<String, Object> sendMailResult;
    try {
      sendMailResult = dispatcher.runSync("sendMail", sendMailContext);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // just return the same result; it contains all necessary information
    return sendMailResult;
  }
Example #19
0
  /**
   * Create Note Record
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp noteDate = (Timestamp) context.get("noteDate");
    String partyId = (String) context.get("partyId");
    String noteName = (String) context.get("noteName");
    String note = (String) context.get("note");
    String noteId = delegator.getNextSeqId("NoteData");
    Locale locale = (Locale) context.get("locale");
    if (noteDate == null) {
      noteDate = UtilDateTime.nowTimestamp();
    }

    // check for a party id
    if (partyId == null) {
      if (userLogin != null && userLogin.get("partyId") != null)
        partyId = userLogin.getString("partyId");
    }

    Map<String, Object> fields =
        UtilMisc.toMap(
            "noteId",
            noteId,
            "noteName",
            noteName,
            "noteInfo",
            note,
            "noteParty",
            partyId,
            "noteDateTime",
            noteDate);

    try {
      GenericValue newValue = delegator.makeValue("NoteData", fields);

      delegator.create(newValue);
    } catch (GenericEntityException e) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "CommonNoteCannotBeUpdated",
              UtilMisc.toMap("errorString", e.getMessage()),
              locale));
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();

    result.put("noteId", noteId);
    result.put("partyId", partyId);
    return result;
  }
Example #20
0
  /**
   * 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();
  }
  public String invoke(
      Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response)
      throws EventHandlerException {
    try {
      Map<String, Object> groovyContext = FastMap.newInstance();
      groovyContext.put("request", request);
      groovyContext.put("response", response);
      HttpSession session = request.getSession();
      groovyContext.put("session", session);

      groovyContext.put("dispatcher", request.getAttribute("dispatcher"));
      groovyContext.put("delegator", request.getAttribute("delegator"));
      groovyContext.put("security", request.getAttribute("security"));
      groovyContext.put("locale", UtilHttp.getLocale(request));
      groovyContext.put("timeZone", UtilHttp.getTimeZone(request));
      groovyContext.put("userLogin", session.getAttribute("userLogin"));
      groovyContext.put(
          "parameters",
          UtilHttp.getCombinedMap(
              request,
              UtilMisc.toSet(
                  "delegator", "dispatcher", "security", "locale", "timeZone", "userLogin")));

      Object result = GroovyUtil.runScriptAtLocation(event.path + event.invoke, groovyContext);
      // check the result
      if (result != null && !(result instanceof String)) {
        throw new EventHandlerException(
            "Event did not return a String result, it returned a " + result.getClass().getName());
      }
      return (String) result;
    } catch (Exception e) {
      throw new EventHandlerException("Groovy Event Error", e);
    }
  }
 public AssignmentEventAudit(EntityAuditMgr mgr, Delegator delegator) {
   super(mgr, delegator);
   this.newValue = true;
   this.assignmentEventAudit =
       delegator.makeValue(
           "WfAssignmentEventAudit", UtilMisc.toMap("eventAuditId", this.eventAuditId));
 }
Example #23
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;
 }
 @Override
 protected Object get(Map<String, ? extends Object> context, TimeZone timeZone, Locale locale) {
   try {
     Object obj =
         BshUtil.eval(
             new String(this.chars, this.parseStart, this.parseLength),
             UtilMisc.makeMapWritable(context));
     if (obj != null) {
       return obj;
     } else {
       if (Debug.verboseOn()) {
         Debug.logVerbose(
             "BSH scriptlet evaluated to null ["
                 + this
                 + "], got no return so inserting nothing.",
             module);
       }
     }
   } catch (EvalError e) {
     Debug.logWarning(
         e,
         "Error evaluating BSH scriptlet [" + this + "], inserting nothing; error was: " + e,
         module);
   }
   return null;
 }
Example #25
0
  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;
  }
Example #26
0
  /**
   * Finds all matching PartyAndPostalAddress records based on the values provided. Excludes party
   * records with a statusId of PARTY_DISABLED. Results are ordered by descending
   * PartyContactMech.fromDate. The matching process is as follows: 1. Calls {@link
   * #findMatchingPartyPostalAddress(Delegator, String, String, String, String, String, String,
   * String, String)} to retrieve a list of address matched PartyAndPostalAddress records. Results
   * are limited to Parties of type PERSON. 2. For each matching PartyAndPostalAddress record, the
   * Person record for the Party is then retrieved and an upper case comparison is performed against
   * the supplied firstName, lastName and if provided, middleName.
   *
   * @param delegator Delegator instance
   * @param address1 PostalAddress.address1 to match against (Required).
   * @param address2 Optional PostalAddress.address2 to match against.
   * @param city PostalAddress.city value to match against (Required).
   * @param stateProvinceGeoId Optional PostalAddress.stateProvinceGeoId value to match against. If
   *     null or "**" is passed then the value will be ignored during matching. "NA" can be passed
   *     in place of "_NA_".
   * @param postalCode PostalAddress.postalCode value to match against. Cannot be null but can be
   *     skipped by passing a value starting with an "*". If the length of the supplied string is 10
   *     characters and the string contains a "-" then the postal code will be split at the "-" and
   *     the second half will be used as the postalCodeExt.
   * @param postalCodeExt Optional PostalAddress.postalCodeExt value to match against. Will be
   *     overridden if a postalCodeExt value is retrieved from postalCode as described above.
   * @param countryGeoId Optional PostalAddress.countryGeoId value to match against.
   * @param firstName Person.firstName to match against (Required).
   * @param middleName Optional Person.middleName to match against.
   * @param lastName Person.lastName to match against (Required).
   * @return List of PartyAndPostalAddress GenericValue objects that match the supplied criteria.
   * @throws GeneralException
   */
  public static List<GenericValue> findMatchingPersonPostalAddresses(
      Delegator delegator,
      String address1,
      String address2,
      String city,
      String stateProvinceGeoId,
      String postalCode,
      String postalCodeExt,
      String countryGeoId,
      String firstName,
      String middleName,
      String lastName)
      throws GeneralException {
    // return list
    List<GenericValue> returnList = FastList.newInstance();

    // address information
    if (firstName == null || lastName == null) {
      throw new IllegalArgumentException();
    }

    List<GenericValue> validFound =
        findMatchingPartyPostalAddress(
            delegator,
            address1,
            address2,
            city,
            stateProvinceGeoId,
            postalCode,
            postalCodeExt,
            countryGeoId,
            "PERSON");

    if (UtilValidate.isNotEmpty(validFound)) {
      for (GenericValue partyAndAddr : validFound) {
        String partyId = partyAndAddr.getString("partyId");
        if (UtilValidate.isNotEmpty(partyId)) {
          GenericValue p = delegator.findByPrimaryKey("Person", UtilMisc.toMap("partyId", partyId));
          if (p != null) {
            String fName = p.getString("firstName");
            String lName = p.getString("lastName");
            String mName = p.getString("middleName");
            if (lName.toUpperCase().equals(lastName.toUpperCase())) {
              if (fName.toUpperCase().equals(firstName.toUpperCase())) {
                if (mName != null && middleName != null) {
                  if (mName.toUpperCase().equals(middleName.toUpperCase())) {
                    returnList.add(partyAndAddr);
                  }
                } else if (middleName == null) {
                  returnList.add(partyAndAddr);
                }
              }
            }
          }
        }
      }
    }

    return returnList;
  }
Example #27
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", "");
  }
Example #28
0
  public static Map<String, Object> pagerSettingInfo(DispatchContext ctx, Map<?, ?> context) {
    String id = (String) context.get("id");
    Map<String, Object> map = new HashMap<String, Object>();
    if (id == null || "".equalsIgnoreCase(id)) {
      map.put("_id", "");
      map.put("_name", "");
      map.put("_disabled", "no");
      map.put("_pagerSpeed", "");
      map.put("_pagerAlphaPhone", "");
      map.put("_pagerAlphaPIN", "");
      map.put("_pagerDirectPhone", "");
      map.put("_pagerOptionPhone", "");
      map.put("_pagerCustom", "");
      map.put("_pagerOption", "");
      map.put("_pagerType", "custom");
      Map retMap = ServiceUtil.returnSuccess();
      retMap.put("result", map);
      return retMap;
    } else {
      try {
        Map map1 =
            (Map<String, Object>)
                (ctx.getDispatcher().runSync("pagerSettingInfoValue", UtilMisc.toMap("id", id)))
                    .get("result");

        Map retMap = ServiceUtil.returnSuccess();
        retMap.put("result", map1);
        return retMap;
      } catch (GenericServiceException e) {
        return ServiceUtil.returnFailure(e.getMessage());
      }
    }
  }
Example #29
0
 public static Map<String, Object> saveAbsoluteSchedule(DispatchContext ctx, Map<?, ?> context) {
   try {
     String name = (String) context.get("name");
     String scheduleAt0 = (String) context.get("scheduleAt0");
     String scheduleAt1 = (String) context.get("scheduleAt1");
     String scheduleAt2 = (String) context.get("scheduleAt2");
     String scheduleAt3 = (String) context.get("scheduleAt3");
     String scheduleAt4 = (String) context.get("scheduleAt4");
     String scheduleAt5 = (String) context.get("scheduleAt5");
     String scheduleAt6 = (String) context.get("scheduleAt6");
     String timeV =
         " _name="
             + name
             + " _schedule="
             + "*"
             + scheduleAt0
             + ","
             + scheduleAt1
             + ","
             + scheduleAt2
             + ","
             + scheduleAt3
             + ","
             + scheduleAt4
             + ","
             + scheduleAt5
             + ","
             + scheduleAt6;
     ctx.getDispatcher().runSync("saveAbsoluteScheduleV", UtilMisc.toMap("value", timeV));
   } catch (Exception e) {
     return ServiceUtil.returnFailure(e.getMessage());
   }
   return ServiceUtil.returnSuccess();
 }
Example #30
0
  public static Map<String, Object> getPagerPrefefencesList(
      DispatchContext ctx, Map<?, ?> context) {
    try {
      Map<String, Object> map2 = ServiceUtil.returnSuccess();
      List<Map<Object, Object>> list = new ArrayList<Map<Object, Object>>();
      Map<String, Object> retDataMap =
          (Map<String, Object>)
              (ctx.getDispatcher()
                      .runSync("getConfigByName", UtilMisc.toMap("attrName", "_additionalPager")))
                  .get("result");
      if (retDataMap == null || retDataMap.size() == 0 || retDataMap.isEmpty()) {
        Map<Object, Object> map1 = new HashMap<Object, Object>();
        map1.put("_id", "no");
        map1.put("_name", "");
        map1.put("_pagerType", "no additional pager settings");
        map1.put("_pagerAlphaPhone", "");
        map1.put("_disabled", "");
        map1.put("_pagerAlphaPIN", "");

        list.add(map1);
        map2.put("result", list);
      } else {
        map2.put(
            "result",
            (ctx.getDispatcher().runSync("getPagerPrefefencesListValue", new HashMap()))
                .get("result"));
      }
      return map2;
    } catch (Exception e) {
      return ServiceUtil.returnFailure(e.getMessage());
    }
  }