Ejemplo n.º 1
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);
  }
Ejemplo n.º 2
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;
  }
Ejemplo n.º 3
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;
  }
Ejemplo n.º 4
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", "");
  }
Ejemplo n.º 5
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;
  }
Ejemplo n.º 6
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;
  }
Ejemplo n.º 7
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);
  }
Ejemplo n.º 8
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;
  }
Ejemplo n.º 9
0
 /**
  * Method to return the total amount of a payment which is applied to a payment
  *
  * @param payment GenericValue object of the Payment
  * @param actual false for currency of the payment, true for the actual currency
  * @return the applied total as BigDecimal in the currency of the payment
  */
 public static BigDecimal getPaymentApplied(GenericValue payment, Boolean actual) {
   BigDecimal paymentApplied = BigDecimal.ZERO;
   List<GenericValue> paymentApplications = null;
   try {
     List<EntityExpr> cond =
         UtilMisc.toList(
             EntityCondition.makeCondition(
                 "paymentId", EntityOperator.EQUALS, payment.getString("paymentId")),
             EntityCondition.makeCondition(
                 "toPaymentId", EntityOperator.EQUALS, payment.getString("paymentId")));
     EntityCondition partyCond = EntityCondition.makeCondition(cond, EntityOperator.OR);
     paymentApplications =
         payment
             .getDelegator()
             .findList(
                 "PaymentApplication",
                 partyCond,
                 null,
                 UtilMisc.toList("invoiceId", "billingAccountId"),
                 null,
                 false);
     if (UtilValidate.isNotEmpty(paymentApplications)) {
       for (GenericValue paymentApplication : paymentApplications) {
         BigDecimal amountApplied = paymentApplication.getBigDecimal("amountApplied");
         // check currency invoice and if different convert amount applied for display
         if (actual.equals(Boolean.FALSE)
             && paymentApplication.get("invoiceId") != null
             && payment.get("actualCurrencyAmount") != null
             && payment.get("actualCurrencyUomId") != null) {
           GenericValue invoice = paymentApplication.getRelatedOne("Invoice");
           if (payment
               .getString("actualCurrencyUomId")
               .equals(invoice.getString("currencyUomId"))) {
             amountApplied =
                 amountApplied
                     .multiply(payment.getBigDecimal("amount"))
                     .divide(payment.getBigDecimal("actualCurrencyAmount"), new MathContext(100));
           }
         }
         paymentApplied = paymentApplied.add(amountApplied).setScale(decimals, rounding);
       }
     }
   } catch (GenericEntityException e) {
     Debug.logError(e, "Trouble getting entities", module);
   }
   return paymentApplied;
 }
Ejemplo n.º 10
0
  public static Map<String, Object> assignContactToAccount(
      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("contactPartyId");
    String accountPartyId = (String) context.get("accountPartyId");

    try {
      // check if this contact is already a contact of this account
      EntityCondition searchConditions =
          EntityCondition.makeCondition(
              EntityOperator.AND,
              EntityCondition.makeCondition("partyIdFrom", EntityOperator.EQUALS, contactPartyId),
              EntityCondition.makeCondition("partyIdTo", EntityOperator.EQUALS, accountPartyId),
              EntityCondition.makeCondition("roleTypeIdFrom", EntityOperator.EQUALS, "CONTACT"),
              EntityCondition.makeCondition("roleTypeIdTo", EntityOperator.EQUALS, "ACCOUNT"),
              EntityCondition.makeCondition(
                  "partyRelationshipTypeId", EntityOperator.EQUALS, "CONTACT_REL_INV"),
              EntityUtil.getFilterByDateExpr());
      List<GenericValue> existingRelationships =
          delegator.findByCondition("PartyRelationship", searchConditions, null, null);
      if (existingRelationships.size() > 0) {
        return UtilMessage.createAndLogServiceError(
            "CrmErrorContactAlreadyAssociatedToAccount", locale, MODULE);
      }

      // check if userLogin has CRMSFA_ACCOUNT_UPDATE permission for this account
      if (!CrmsfaSecurity.hasPartyRelationSecurity(
          security, "CRMSFA_ACCOUNT", "_UPDATE", userLogin, accountPartyId)) {
        return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
      }
      // create the party relationship between the Contact and the Account
      PartyHelper.createNewPartyToRelationship(
          accountPartyId,
          contactPartyId,
          "CONTACT",
          "CONTACT_REL_INV",
          null,
          UtilMisc.toList("ACCOUNT"),
          false,
          userLogin,
          delegator,
          dispatcher);

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorAssignContactToAccountFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorAssignContactToAccountFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Ejemplo n.º 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);
 }
Ejemplo n.º 12
0
 public static List<String> getAssociatedPartyIdsByRelationshipType(
     Delegator delegator, String partyIdFrom, String partyRelationshipTypeId) {
   List<GenericValue> partyList = FastList.newInstance();
   List<String> partyIds = null;
   try {
     EntityConditionList<EntityExpr> baseExprs =
         EntityCondition.makeCondition(
             UtilMisc.toList(
                 EntityCondition.makeCondition("partyIdFrom", partyIdFrom),
                 EntityCondition.makeCondition(
                     "partyRelationshipTypeId", partyRelationshipTypeId)),
             EntityOperator.AND);
     List<GenericValue> associatedParties =
         delegator.findList("PartyRelationship", baseExprs, null, null, null, true);
     partyList.addAll(associatedParties);
     while (UtilValidate.isNotEmpty(associatedParties)) {
       List<GenericValue> currentAssociatedParties = FastList.newInstance();
       for (GenericValue associatedParty : associatedParties) {
         EntityConditionList<EntityExpr> innerExprs =
             EntityCondition.makeCondition(
                 UtilMisc.toList(
                     EntityCondition.makeCondition(
                         "partyIdFrom", associatedParty.get("partyIdTo")),
                     EntityCondition.makeCondition(
                         "partyRelationshipTypeId", partyRelationshipTypeId)),
                 EntityOperator.AND);
         List<GenericValue> associatedPartiesChilds =
             delegator.findList("PartyRelationship", innerExprs, null, null, null, true);
         if (UtilValidate.isNotEmpty(associatedPartiesChilds)) {
           currentAssociatedParties.addAll(associatedPartiesChilds);
         }
         partyList.add(associatedParty);
       }
       associatedParties = currentAssociatedParties;
     }
     partyIds = EntityUtil.getFieldListFromEntityList(partyList, "partyIdTo", true);
   } catch (GenericEntityException e) {
     Debug.logWarning(e, module);
   }
   return partyIds;
 }
 /**
  * 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;
 }
Ejemplo n.º 14
0
 public static List<ModelKeyMap> makeKeyMapList(
     String fieldName1,
     String relFieldName1,
     String fieldName2,
     String relFieldName2,
     String fieldName3,
     String relFieldName3) {
   return UtilMisc.toList(
       new ModelKeyMap(fieldName1, relFieldName1),
       new ModelKeyMap(fieldName2, relFieldName2),
       new ModelKeyMap(fieldName3, relFieldName3));
 }
Ejemplo n.º 15
0
  public static Map<String, Object> convertOrderIdListToHeaders(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();

    List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList"));
    List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList"));

    // we don't want to process if there is already a header list
    if (orderHeaderList == null) {
      // convert the ID list to headers
      if (orderIdList != null) {
        List<EntityCondition> conditionList1 = FastList.newInstance();
        List<EntityCondition> conditionList2 = FastList.newInstance();

        // we are only concerned about approved sales orders
        conditionList2.add(
            EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED"));
        conditionList2.add(
            EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER"));

        // build the expression list from the IDs
        for (String orderId : orderIdList) {
          conditionList1.add(
              EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId));
        }

        // create the conditions
        EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR);
        conditionList2.add(idCond);

        EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND);

        // run the query
        try {
          orderHeaderList =
              delegator.findList(
                  "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false);
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
        Debug.logInfo("Recieved orderIdList  - " + orderIdList, module);
        Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module);
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("orderHeaderList", orderHeaderList);
    return result;
  }
Ejemplo n.º 16
0
 public static GenericValue findPartyLatestUserLogin(String partyId, Delegator delegator) {
   try {
     List<GenericValue> userLoginList =
         delegator.findByAnd(
             "UserLogin",
             UtilMisc.toMap("partyId", partyId),
             UtilMisc.toList("-" + ModelEntity.STAMP_FIELD));
     return EntityUtil.getFirst(userLoginList);
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest UserLogin for party with ID ["
             + partyId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
Ejemplo n.º 17
0
 public static Timestamp findPartyLastLoginTime(String partyId, Delegator delegator) {
   try {
     List<GenericValue> loginHistory =
         delegator.findByAnd(
             "UserLoginHistory", UtilMisc.toMap("partyId", partyId), UtilMisc.toList("-fromDate"));
     GenericValue v = EntityUtil.getFirst(loginHistory);
     if (v != null) {
       return v.getTimestamp("fromDate");
     } else {
       return null;
     }
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest login time for party with ID ["
             + partyId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
Ejemplo n.º 18
0
 public static GenericValue findPartyLatestContactMech(
     String partyId, String contactMechTypeId, Delegator delegator) {
   try {
     List<GenericValue> cmList =
         delegator.findByAnd(
             "PartyAndContactMech",
             UtilMisc.toMap("partyId", partyId, "contactMechTypeId", contactMechTypeId),
             UtilMisc.toList("-fromDate"));
     cmList = EntityUtil.filterByDate(cmList);
     return EntityUtil.getFirst(cmList);
   } catch (GenericEntityException e) {
     Debug.logError(
         e,
         "Error while finding latest ContactMech for party with ID ["
             + partyId
             + "] TYPE ["
             + contactMechTypeId
             + "]: "
             + e.toString(),
         module);
     return null;
   }
 }
  public static List<GenericValue> getRelatedCategoriesRet(
      Delegator delegator,
      String attributeName,
      String parentId,
      boolean limitView,
      boolean excludeEmpty,
      boolean recursive) {
    List<GenericValue> categories = FastList.newInstance();

    if (Debug.verboseOn())
      Debug.logVerbose("[CategoryWorker.getRelatedCategories] ParentID: " + parentId, module);

    List<GenericValue> rollups = null;

    try {
      rollups =
          delegator.findByAndCache(
              "ProductCategoryRollup",
              UtilMisc.toMap("parentProductCategoryId", parentId),
              UtilMisc.toList("sequenceNum"));
      if (limitView) {
        rollups = EntityUtil.filterByDate(rollups, true);
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
    }
    if (rollups != null) {
      // Debug.logInfo("Rollup size: " + rollups.size(), module);
      for (GenericValue parent : rollups) {
        // Debug.logInfo("Adding child of: " + parent.getString("parentProductCategoryId"), module);
        GenericValue cv = null;

        try {
          cv = parent.getRelatedOneCache("CurrentProductCategory");
        } catch (GenericEntityException e) {
          Debug.logWarning(e.getMessage(), module);
        }
        if (cv != null) {
          if (excludeEmpty) {
            if (!isCategoryEmpty(cv)) {
              // Debug.logInfo("Child : " + cv.getString("productCategoryId") + " is not empty.",
              // module);
              categories.add(cv);
              if (recursive) {
                categories.addAll(
                    getRelatedCategoriesRet(
                        delegator,
                        attributeName,
                        cv.getString("productCategoryId"),
                        limitView,
                        excludeEmpty,
                        recursive));
              }
            }
          } else {
            categories.add(cv);
            if (recursive) {
              categories.addAll(
                  getRelatedCategoriesRet(
                      delegator,
                      attributeName,
                      cv.getString("productCategoryId"),
                      limitView,
                      excludeEmpty,
                      recursive));
            }
          }
        }
      }
    }
    return categories;
  }
Ejemplo n.º 20
0
/**
 * Party Helper methods which are designed to provide a consistent set of APIs that can be reused by
 * higher level services.
 *
 * <p>Many of the methods have been migrated to org.opentaps.common.party.PartyHelper. However, this
 * class also has a lot of CRMSFA specific functionality, so the code inside of these methods have
 * been replaced to reference the common PartyHelper, but we will keep this class and its methods.
 */
public final class PartyHelper {

  private PartyHelper() {}

  private static final String MODULE = PartyHelper.class.getName();

  public static List<String> TEAM_MEMBER_ROLES =
      UtilMisc.toList("ACCOUNT_MANAGER", "ACCOUNT_REP", "CUST_SERVICE_REP");
  public static List<String> CLIENT_PARTY_ROLES =
      UtilMisc.toList("ACCOUNT", "CONTACT", "PROSPECT", "PARTNER");
  public static List<String> FIND_PARTY_FIELDS =
      Arrays.asList(
          new String[] {
            "firstName",
            "lastName",
            "groupName",
            "partyId",
            "companyName",
            "primaryEmailId",
            "primaryPostalAddressId",
            "primaryTelecomNumberId",
            "primaryCity",
            "primaryStateProvinceGeoId",
            "primaryCountryGeoId",
            "primaryEmail",
            "primaryCountryCode",
            "primaryAreaCode",
            "primaryContactNumber"
          });

  /**
   * A helper method which finds the first valid roleTypeId for a partyId, using a List of possible
   * roleTypeIds.
   *
   * @param partyId
   * @param possibleRoleTypeIds a List of roleTypeIds
   * @param delegator
   * @return the first roleTypeId from possibleRoleTypeIds which is actually found in PartyRole for
   *     the given partyId
   * @throws GenericEntityException
   */
  public static String getFirstValidRoleTypeId(
      String partyId, List<String> possibleRoleTypeIds, Delegator delegator)
      throws GenericEntityException {
    return org.opentaps.common.party.PartyHelper.getFirstValidRoleTypeId(
        partyId, possibleRoleTypeIds, delegator);
  }

  /** As above, but pass in the list of internal party roles, such as ACCOUNT, CONTACT, PROSPECT. */
  public static String getFirstValidInternalPartyRoleTypeId(String partyId, Delegator delegator)
      throws GenericEntityException {
    return getFirstValidRoleTypeId(partyId, CLIENT_PARTY_ROLES, delegator);
  }

  /** As above, but pass in the list of team member roles such as ACCOUNT_REP, etc. */
  public static String getFirstValidTeamMemberRoleTypeId(String partyId, Delegator delegator)
      throws GenericEntityException {
    return getFirstValidRoleTypeId(partyId, TEAM_MEMBER_ROLES, delegator);
  }

  /** Find the first valid role of the party, whether it be a team member or client party. */
  public static String getFirstValidCrmsfaPartyRoleTypeId(String partyId, Delegator delegator)
      throws GenericEntityException {
    String roleTypeId = getFirstValidRoleTypeId(partyId, TEAM_MEMBER_ROLES, delegator);
    if (roleTypeId == null) {
      roleTypeId = getFirstValidRoleTypeId(partyId, CLIENT_PARTY_ROLES, delegator);
    }
    return roleTypeId;
  }

  /**
   * A helper method for creating a PartyRelationship entity from partyIdTo to partyIdFrom with
   * specified partyRelationshipTypeId, roleTypeIdFrom, a List of valid roles for the to-party, and
   * a flag to expire any existing relationships between the two parties of the same type. The idea
   * is that several services would do validation and then use this method to do all the work.
   *
   * @param partyIdTo
   * @param partyIdFrom
   * @param roleTypeIdFrom
   * @param partyRelationshipTypeId
   * @param securityGroupId
   * @param validToPartyRoles List of roleTypeIds which are valid for the partyIdTo in the create
   *     relationship. It will cycle through until the first of these roles is actually associated
   *     with partyIdTo and then create a PartyRelationship using that roleTypeId. If none of these
   *     are associated with partyIdTo, then it will return false
   * @param fromDate
   * @param expireExistingRelationships If set to true, will look for all existing
   *     PartyRelationships of partyIdFrom, partyRelationshipTypeId and expire all of them as of the
   *     passed in fromDate
   * @return false if no relationship was created or true if operation succeeds
   */
  public static boolean createNewPartyToRelationship(
      String partyIdTo,
      String partyIdFrom,
      String roleTypeIdFrom,
      String partyRelationshipTypeId,
      String securityGroupId,
      List<String> validToPartyRoles,
      Timestamp fromDate,
      boolean expireExistingRelationships,
      GenericValue userLogin,
      Delegator delegator,
      LocalDispatcher dispatcher)
      throws GenericEntityException, GenericServiceException {

    return org.opentaps.common.party.PartyHelper.createNewPartyToRelationship(
        partyIdTo,
        partyIdFrom,
        roleTypeIdFrom,
        partyRelationshipTypeId,
        securityGroupId,
        validToPartyRoles,
        fromDate,
        expireExistingRelationships,
        userLogin,
        delegator,
        dispatcher);
  }

  /** Same as above except uses a default of now for the timestamp. */
  public static boolean createNewPartyToRelationship(
      String partyIdTo,
      String partyIdFrom,
      String roleTypeIdFrom,
      String partyRelationshipTypeId,
      String securityGroupId,
      List<String> validToPartyRoles,
      boolean expireExistingRelationships,
      GenericValue userLogin,
      Delegator delegator,
      LocalDispatcher dispatcher)
      throws GenericEntityException, GenericServiceException {
    return createNewPartyToRelationship(
        partyIdTo,
        partyIdFrom,
        roleTypeIdFrom,
        partyRelationshipTypeId,
        securityGroupId,
        validToPartyRoles,
        UtilDateTime.nowTimestamp(),
        expireExistingRelationships,
        userLogin,
        delegator,
        dispatcher);
  }

  /** Expires a list of PartyRelationships that are still active on expireDate. */
  public static void expirePartyRelationships(
      List<GenericValue> partyRelationships,
      Timestamp expireDate,
      LocalDispatcher dispatcher,
      GenericValue userLogin)
      throws GenericServiceException {
    org.opentaps.common.party.PartyHelper.expirePartyRelationships(
        partyRelationships, expireDate, dispatcher, userLogin);
  }

  /**
   * Method to get the current non-expired party responsible for the given account/contact/lead.
   *
   * @param partyIdFrom The partyId of the account/contact/lead
   * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD)
   * @return First non-expired PartySummaryCRMView or null if none found
   */
  public static GenericValue getCurrentResponsibleParty(
      String partyIdFrom, String roleTypeIdFrom, Delegator delegator)
      throws GenericEntityException {
    return getActivePartyByRole(
        "RESPONSIBLE_FOR", partyIdFrom, roleTypeIdFrom, UtilDateTime.nowTimestamp(), delegator);
  }

  /** Method to get the current lead owner of a lead. */
  public static GenericValue getCurrentLeadOwner(String leadPartyId, Delegator delegator)
      throws GenericEntityException {
    return getActivePartyByRole(
        "RESPONSIBLE_FOR",
        leadPartyId,
        "PROSPECT",
        "LEAD_OWNER",
        UtilDateTime.nowTimestamp(),
        delegator);
  }

  /**
   * Common method used by getCurrentlyResponsibleParty and related methods. This method will obtain
   * the first PartyRelationship found with the given criteria and return the PartySummaryCRMView
   * with partyId = partyRelationship.partyIdTo.
   *
   * @param partyRelationshipTypeId The party relationship (e.g., reps that are RESPONSIBLE_FOR an
   *     account)
   * @param partyIdFrom The partyId of the account/contact/lead
   * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD)
   * @param securityGroupId Optional securityGroupId of the relationship
   * @param activeDate Check only for active relationships as of this timestamp
   * @return First non-expired PartySummaryCRMView or null if none found
   */
  public static GenericValue getActivePartyByRole(
      String partyRelationshipTypeId,
      String partyIdFrom,
      String roleTypeIdFrom,
      String securityGroupId,
      Timestamp activeDate,
      Delegator delegator)
      throws GenericEntityException {
    return org.opentaps.common.party.PartyHelper.getActivePartyByRole(
        partyRelationshipTypeId,
        partyIdFrom,
        roleTypeIdFrom,
        securityGroupId,
        activeDate,
        delegator);
  }

  /** As above but without security group Id specified */
  public static GenericValue getActivePartyByRole(
      String partyRelationshipTypeId,
      String partyIdFrom,
      String roleTypeIdFrom,
      Timestamp activeDate,
      Delegator delegator)
      throws GenericEntityException {
    return getActivePartyByRole(
        partyRelationshipTypeId, partyIdFrom, roleTypeIdFrom, null, activeDate, delegator);
  }

  /**
   * Method to copy all "To" relationships of a From party to another From party. For instance, use
   * this method to copy all relationships of an account (or optionally a specific relationship),
   * such as the managers and reps, over to a team. NOTE: This service works on unexpired
   * relationships as of now and will need to be refactored for other Dates.
   *
   * @param partyIdFrom
   * @param roleTypeIdFrom
   * @param partyRelationshipTypeId optional
   * @param newPartyIdFrom
   * @param newRoleTypeIdFrom
   */
  public static void copyToPartyRelationships(
      String partyIdFrom,
      String roleTypeIdFrom,
      String partyRelationshipTypeId,
      String newPartyIdFrom,
      String newRoleTypeIdFrom,
      GenericValue userLogin,
      Delegator delegator,
      LocalDispatcher dispatcher)
      throws GenericEntityException, GenericServiceException {

    org.opentaps.common.party.PartyHelper.copyToPartyRelationships(
        partyIdFrom,
        roleTypeIdFrom,
        partyRelationshipTypeId,
        newPartyIdFrom,
        newRoleTypeIdFrom,
        userLogin,
        delegator,
        dispatcher);
  }

  /**
   * Same as above, but passes partyRelationshipTypeId = null so that all relationship types are
   * selected.
   */
  public static void copyToPartyRelationships(
      String partyIdFrom,
      String roleTypeIdFrom,
      String newPartyIdFrom,
      String newRoleTypeIdFrom,
      GenericValue userLogin,
      Delegator delegator,
      LocalDispatcher dispatcher)
      throws GenericEntityException, GenericServiceException {

    copyToPartyRelationships(
        partyIdFrom,
        roleTypeIdFrom,
        null,
        newPartyIdFrom,
        newRoleTypeIdFrom,
        userLogin,
        delegator,
        dispatcher);
  }

  /**
   * This array determines the entities in which to delete the party and the order of deletion. The
   * second element in each row denotes the partyId field to check. XXX Note: We are deleting
   * historical data. For instance, activity records involving the partyId will be gone forever!
   */
  private static String[][] CRM_PARTY_DELETE_CASCADE = {
    {"CustRequestRole", "partyId"},
    {"PartyNote", "partyId"},
    {"PartyDataSource", "partyId"},
    {"WorkEffortPartyAssignment", "partyId"},
    {"PartyContactMechPurpose", "partyId"},
    {"PartyContactMech", "partyId"},
    {"PartySupplementalData", "partyId"},
    {"PartyNameHistory", "partyId"},
    {"PartyGroup", "partyId"},
    {"PartyRelationship", "partyIdFrom"},
    {"PartyRelationship", "partyIdTo"},
    {"Person", "partyId"},
    {"CommunicationEventRole", "partyId"},
    {"ContentRole", "partyId"},
    {"FacilityParty", "partyId"},
    {"MarketingCampaignRole", "partyId"},
    {"PartyRole", "partyId"},
    {"PartyContent", "partyId"},
    {"PartyStatus", "partyId"}
  };

  /**
   * 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);
  }

  /**
   * Generates a party name in the standard CRMSFA style. Input is a PartySummaryCRMView or any view
   * entity with fields partyId, groupName, firstName and lastName.
   */
  public static String getCrmsfaPartyName(GenericValue party) {
    if (party == null) {
      return null;
    }
    StringBuffer name = new StringBuffer();
    if (party.get("groupName") != null) {
      name.append(party.get("groupName")).append(" ");
    }
    if (party.get("firstName") != null) {
      name.append(party.get("firstName")).append(" ");
    }
    if (party.get("lastName") != null) {
      name.append(party.get("lastName")).append(" ");
    }
    name.append("(").append(party.get("partyId")).append(")");
    return name.toString();
  }

  /** As above, but does a lookup on PartySummaryCRMView for an input partyId. */
  public static String getCrmsfaPartyName(Delegator delegator, String partyId)
      throws GenericEntityException {
    GenericValue party =
        delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId));
    return getCrmsfaPartyName(party);
  }

  /**
   * Retrieve the view url with partyId.
   *
   * @param partyId
   * @param delegator
   * @param externalLoginKey
   * @return view page url
   * @deprecated Use <code>org.opentaps.domain.party.Party.createViewPageURL()</code>
   */
  public static String createViewPageURL(
      String partyId, Delegator delegator, String externalLoginKey) throws GenericEntityException {
    GenericValue party =
        delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId));

    return org.opentaps.common.party.PartyHelper.createViewPageURL(
        party, CLIENT_PARTY_ROLES, externalLoginKey);
  }

  /**
   * Generates a hyperlink to the correct view profile page for the given party with the standard
   * CRM party using createViewPageURL description string ${groupName} ${firstName} ${lastName}
   * (${partyId}). Some pages show list of all kinds of parties, including Leads, Accounts, and
   * non-CRM parties. This method generate a hyperlink to the correct view page, such as viewAccount
   * for Accounts, or partymgr viewprofile for non-CRM parties.
   *
   * @param partyId
   * @param delegator
   * @param externalLoginKey
   * @return view page url
   * @deprecated Use <code>org.opentaps.domain.party.Party.createViewPageLink()</code>
   */
  public static String createViewPageLink(
      String partyId, Delegator delegator, String externalLoginKey) throws GenericEntityException {
    GenericValue party =
        delegator.findByPrimaryKeyCache("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId));
    if (party == null) {
      Debug.logError(
          "No PartySummaryCRMView found for partyId [" + partyId + "], cannot create link", MODULE);
      return "";
    }

    // generate the contents of href=""
    String uri =
        org.opentaps.common.party.PartyHelper.createViewPageURL(
            party, CLIENT_PARTY_ROLES, externalLoginKey);
    // generate the display name
    StringBuffer name = new StringBuffer(getCrmsfaPartyName(party));

    // put everything together
    StringBuffer buff = new StringBuffer("<a class=\"linktext\" href=\"");
    buff.append(uri).append("\">");
    buff.append(name).append("</a>");
    return buff.toString();
  }

  /**
   * Retrieve the oldest current email address with a PRIMARY_EMAIL purposeTypeId for a party.
   *
   * @param partyId
   * @param delegator
   * @return The email address
   * @deprecated Use <code>org.opentaps.domain.party.Party.getPrimaryEmail()</code>
   */
  @Deprecated
  public static String getPrimaryEmailForParty(String partyId, Delegator delegator) {
    return org.opentaps.common.party.PartyHelper.getPrimaryEmailForParty(partyId, delegator);
  }

  /**
   * Find active "from" parties such as accounts, contacts, and leads based on
   * PartyFromSummaryByRelationship. These parties can be thought of the main subjects or clients
   * tracked by CRMSFA. Uses the prepareFind service to help build search conditions.
   *
   * <p>The ordering of the fields is controlled by a parameter named activeOrderBy, which may take
   * on the values "lastName" or "companyName". The default is to order by groupName.
   *
   * @param parameters A map of fields and condition parameters to be consumed by prepareFind
   *     service.
   * @param ec Optional EntityCondition to filter the results by
   * @param roles Optional list of CRMSFA roles to limit to. If roles is null or empty, uses the
   *     default CLIENT_PARTY_ROLES.
   * @return EntityListIterator of results or null if the find condition is nothing.
   */
  public static EntityListIterator findActiveClientParties(
      Delegator delegator,
      LocalDispatcher dispatcher,
      Map<String, ?> parameters,
      List<String> roles,
      EntityCondition ec)
      throws GeneralException {
    EntityCondition conditions = getActiveClientPartiesCondition(dispatcher, parameters, roles, ec);
    List<String> orderBy = getActiveClientPartiesOrderBy(parameters);
    return delegator.findListIteratorByCondition(
        "PartyFromSummaryByRelationship",
        conditions,
        null,
        FIND_PARTY_FIELDS,
        orderBy,
        UtilCommon.DISTINCT_READ_OPTIONS);
  }

  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);
  }

  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;
  }

  /** As above, but only consider the search parameters with optional conditions. */
  public static EntityListIterator findActiveClientParties(
      Delegator delegator,
      LocalDispatcher dispatcher,
      Map<String, ?> parameters,
      EntityCondition ec)
      throws GeneralException {
    return findActiveClientParties(delegator, dispatcher, parameters, null, ec);
  }

  /** Finds all active accounts, contacts, leads and so on of a given partyId */
  public static EntityListIterator findActiveClientParties(
      Delegator delegator, LocalDispatcher dispatcher, String partyId) throws GeneralException {
    Map<String, Object> parameters = UtilMisc.<String, Object>toMap("partyIdTo", partyId);
    return findActiveClientParties(delegator, dispatcher, parameters, null, null);
  }

  /** Finds active Accounts for a party. */
  public static EntityListIterator findActiveAccounts(
      Delegator delegator, LocalDispatcher dispatcher, String partyId) throws GeneralException {
    return findActiveClientParties(
        delegator,
        dispatcher,
        UtilMisc.toMap("partyIdTo", partyId),
        UtilMisc.toList("ACCOUNT"),
        null);
  }

  /** Finds active Contacts for a party. */
  public static EntityListIterator findActiveContacts(
      Delegator delegator, LocalDispatcher dispatcher, String partyId) throws GeneralException {
    return findActiveClientParties(
        delegator,
        dispatcher,
        UtilMisc.toMap("partyIdTo", partyId),
        UtilMisc.toList("CONTACT"),
        null);
  }

  /** 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);
  }

  /** As findActiveClientParties, but returns a ListBuilder for use in pagination. */
  public static ListBuilder findActiveClientPartiesListBuilder(
      LocalDispatcher dispatcher, Map<String, ?> parameters, List<String> roles, EntityCondition ec)
      throws GeneralException {
    EntityCondition conditions = getActiveClientPartiesCondition(dispatcher, parameters, roles, ec);
    List<String> orderBy = getActiveClientPartiesOrderBy(parameters);
    return new EntityListBuilder(
        "PartyFromSummaryByRelationship", conditions, FIND_PARTY_FIELDS, orderBy);
  }

  public static Map<String, Object> assembleCrmsfaFormMergeContext(
      Delegator delegator,
      Locale locale,
      String partyId,
      String orderId,
      String shipGroupSeqId,
      String shipmentId,
      TimeZone timeZone) {
    Map<String, Object> templateContext = assembleCrmsfaGenericFormMergeContext(timeZone, locale);
    templateContext.putAll(assembleCrmsfaPartyFormMergeContext(delegator, partyId));
    templateContext.putAll(assembleCrmsfaOrderFormMergeContext(delegator, orderId));
    templateContext.putAll(
        assembleCrmsfaShipmentFormMergeContext(
            delegator, orderId, shipGroupSeqId, shipmentId, locale));
    return templateContext;
  }

  public static Map<String, Object> assembleCrmsfaShipmentFormMergeContext(
      Delegator delegator,
      String orderId,
      String shipGroupSeqId,
      String shipmentId,
      Locale locale) {
    Map<String, Object> templateContext = new HashMap<String, Object>();

    try {

      // Prefer shipment data if shipmentId is provided
      if (UtilValidate.isNotEmpty(shipmentId)) {

        GenericValue shipment =
            delegator.findByPrimaryKey("Shipment", UtilMisc.toMap("shipmentId", shipmentId));
        if (UtilValidate.isNotEmpty(shipment)) {

          GenericValue shipLoc = shipment.getRelatedOne("DestinationPostalAddress");
          if (UtilValidate.isNotEmpty(shipLoc)) {
            templateContext.put("orderShippingAddress1", shipLoc.get("address1"));
            templateContext.put("orderShippingAddress2", shipLoc.get("address2"));
            templateContext.put("orderShippingCity", shipLoc.get("city"));
            templateContext.put("orderShippingPostalCode", shipLoc.get("postalCode"));

            GenericValue stateProvGeo = shipLoc.getRelatedOne("StateProvinceGeo");
            if (UtilValidate.isNotEmpty(stateProvGeo)) {
              templateContext.put("orderShippingStateProvince", stateProvGeo.get("geoName"));
            }
            GenericValue countryGeo = shipLoc.getRelatedOne("CountryGeo");
            if (UtilValidate.isNotEmpty(countryGeo)) {
              templateContext.put("orderShippingCountry", countryGeo.get("geoName"));
            }
          }

          GenericValue phoneNumber = shipment.getRelatedOne("DestinationTelecomNumber");
          if (UtilValidate.isNotEmpty(phoneNumber)) {

            String phoneNumberString =
                UtilValidate.isEmpty(phoneNumber.getString("countryCode"))
                    ? ""
                    : phoneNumber.getString("countryCode") + " ";
            if (UtilValidate.isNotEmpty(phoneNumber.getString("areaCode"))) {
              phoneNumberString += phoneNumber.getString("areaCode") + " ";
            }
            if (UtilValidate.isNotEmpty(phoneNumber.getString("contactNumber"))) {
              phoneNumberString += phoneNumber.getString("contactNumber");
            }
            templateContext.put("orderShippingPhone", phoneNumberString);
          }

          GenericValue statusItem = shipment.getRelatedOne("StatusItem");
          if (UtilValidate.isNotEmpty(statusItem)) {
            templateContext.put("shipmentStatus", statusItem.get("description", locale));
          }
        }

      } else if (UtilValidate.isNotEmpty(orderId)) {

        OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
        GenericValue shipGroup = orh.getOrderItemShipGroup(shipGroupSeqId);
        if (UtilValidate.isEmpty(shipGroup)) {

          // Default to the first ship group if no shipGroupSeqId is provided
          List shipGroups = orh.getOrderItemShipGroups();
          if (UtilValidate.isNotEmpty(shipGroups)) {
            shipGroup = (GenericValue) shipGroups.get(0);
          }
        }

        if (UtilValidate.isNotEmpty(shipGroup)) {
          GenericValue shipLoc = shipGroup.getRelatedOne("PostalAddress");
          if (UtilValidate.isNotEmpty(shipLoc)) {
            templateContext.put("orderShippingAddress1", shipLoc.get("address1"));
            templateContext.put("orderShippingAddress2", shipLoc.get("address2"));
            templateContext.put("orderShippingCity", shipLoc.get("city"));
            templateContext.put("orderShippingPostalCode", shipLoc.get("postalCode"));

            GenericValue stateProvGeo = shipLoc.getRelatedOne("StateProvinceGeo");
            if (UtilValidate.isNotEmpty(stateProvGeo)) {
              templateContext.put("orderShippingStateProvince", stateProvGeo.get("geoName"));
            }
            GenericValue countryGeo = shipLoc.getRelatedOne("CountryGeo");
            if (UtilValidate.isNotEmpty(countryGeo)) {
              templateContext.put("orderShippingCountry", countryGeo.get("geoName"));
            }
          }

          GenericValue phoneNumber = shipGroup.getRelatedOne("TelecomTelecomNumber");
          if (UtilValidate.isNotEmpty(phoneNumber)) {

            String phoneNumberString =
                UtilValidate.isEmpty(phoneNumber.getString("countryCode"))
                    ? ""
                    : phoneNumber.getString("countryCode") + " ";
            if (UtilValidate.isNotEmpty(phoneNumber.getString("areaCode"))) {
              phoneNumberString += phoneNumber.getString("areaCode") + " ";
            }
            if (UtilValidate.isNotEmpty(phoneNumber.getString("contactNumber"))) {
              phoneNumberString += phoneNumber.getString("contactNumber");
            }
            templateContext.put("orderShippingPhone", phoneNumberString);
          }

          // Find any shipments relating to this ship group
          List<GenericValue> shipments =
              delegator.findByAnd(
                  "Shipment",
                  UtilMisc.toMap(
                      "primaryOrderId",
                      orderId,
                      "primaryShipGroupSeqId",
                      shipGroup.getString("shipGroupSeqId")),
                  UtilMisc.toList("createdStamp DESC"));
          GenericValue shipment = EntityUtil.getFirst(shipments);
          if (UtilValidate.isNotEmpty(shipment)) {
            GenericValue statusItem = shipment.getRelatedOne("StatusItem");
            if (UtilValidate.isNotEmpty(statusItem)) {
              templateContext.put("shipmentStatus", statusItem.get("description", locale));
            }
          }
        }
      }
    } catch (GenericEntityException e) {
      Debug.logError(e, MODULE);
    }
    return templateContext;
  }

  public static Map<String, Object> assembleCrmsfaOrderFormMergeContext(
      Delegator delegator, String orderId) {
    Map<String, Object> templateContext = new HashMap<String, Object>();
    if (UtilValidate.isNotEmpty(orderId)) {
      try {
        OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
        templateContext.put("orderId", orderId);
        templateContext.put("externalOrderId", orh.getOrderHeader().get("externalId"));
        templateContext.put("orderDate", orh.getOrderHeader().getTimestamp("orderDate"));

        GenericValue billingParty = orh.getBillToParty();
        if (UtilValidate.isNotEmpty(billingParty)) {
          if ("Person".equalsIgnoreCase(billingParty.getEntityName())) {
            templateContext.put("orderBillingFirstName", billingParty.get("firstName"));
            templateContext.put("orderBillingLastName", billingParty.get("lastName"));
          }
          templateContext.put("orderPartyId", billingParty.get("partyId"));
          templateContext.put(
              "orderBillingFullName",
              org.ofbiz.party.party.PartyHelper.getPartyName(billingParty, false));
        }

        templateContext.put("orderSubtotal", orh.getOrderItemsSubTotal());
        templateContext.put("orderTaxTotal", orh.getTaxTotal());
        templateContext.put("orderShippingTotal", orh.getShippingTotal());
        templateContext.put("orderGrandTotal", orh.getOrderGrandTotal());
        templateContext.put(
            "orderPaymentTotal",
            orh.getOrderGrandTotal().subtract(UtilOrder.getOrderOpenAmount(orh)));

        GenericValue shippingParty = orh.getShipToParty();
        if (UtilValidate.isNotEmpty(shippingParty)) {
          if ("Person".equalsIgnoreCase(shippingParty.getEntityName())) {
            templateContext.put("orderShippingFirstName", shippingParty.get("firstName"));
            templateContext.put("orderShippingLastName", shippingParty.get("lastName"));
          } else {
            templateContext.put("orderShippingCompanyName", shippingParty.get("groupName"));
          }
          templateContext.put(
              "orderShippingFullName",
              org.ofbiz.party.party.PartyHelper.getPartyName(shippingParty, false));
        }

        List<GenericValue> orderItemVals = orh.getOrderItems();
        List<Map<String, Object>> orderItems = new ArrayList<Map<String, Object>>();
        for (GenericValue orderItemVal : orderItemVals) {
          Map<String, Object> orderItem = orderItemVal.getAllFields();
          GenericValue product = orderItemVal.getRelatedOne("Product");
          if (UtilValidate.isEmpty(product)) {
            continue;
          }
          for (String fieldName : (Set<String>) product.keySet()) {
            orderItem.put(fieldName, product.get(fieldName));
          }
          orderItems.add(orderItem);
        }
        templateContext.put("orderItems", orderItems);

      } catch (GenericEntityException e) {
        Debug.logError(e, MODULE);
      }
    }
    return templateContext;
  }

  public static Map<String, Object> assembleCrmsfaGenericFormMergeContext(
      TimeZone timeZone, Locale locale) {
    Map<String, Object> templateContext = new HashMap<String, Object>();

    Calendar now = Calendar.getInstance(timeZone, locale);
    String mmddyyyy = new java.text.SimpleDateFormat("MM/dd/yyyy").format(now.getTime());
    String mmddyyyy2 = new java.text.SimpleDateFormat("MM-dd-yyyy").format(now.getTime());
    String yyyymmdd = new java.text.SimpleDateFormat("yyyy/MM/dd").format(now.getTime());
    String yyyymmdd2 = new java.text.SimpleDateFormat("yyyy-MM-dd").format(now.getTime());
    Integer month = Integer.valueOf(now.get(Calendar.MONTH));
    month++;
    String monthStr = month.toString();
    if (monthStr.length() == 1) {
      monthStr = "0" + monthStr;
    }
    // TODO: oandreyev. Test this code more carefully.
    ArrayList<String> monthNames = (ArrayList<String>) UtilDateTime.getMonthNames(locale);
    String monthName = monthNames.get(month - 1);
    // String monthLabel = null;
    // if (month == 1) {
    //    monthLabel = "CommonJanuary";
    // } else if (month == 2) {
    //    monthLabel = "CommonFebruary";
    // } else if (month == 3) {
    //    monthLabel = "CommonMarch";
    // } else if (month == 4) {
    //    monthLabel = "CommonApril";
    // } else if (month == 5) {
    //    monthLabel = "CommonMay";
    // } else if (month == 6) {
    //    monthLabel = "CommonJune";
    // } else if (month == 7) {
    //    monthLabel = "CommonJuly";
    // } else if (month == 8) {
    //    monthLabel = "CommonAugust";
    // } else if (month == 9) {
    //    monthLabel = "CommonSeptember";
    // } else if (month == 10) {
    //    monthLabel = "CommonOctober";
    // } else if (month == 11) {
    //    monthLabel = "CommonNovember";
    // } else if (month == 12) {
    //    monthLabel = "CommonDecember";
    // }
    // if (UtilValidate.isNotEmpty(monthLabel)) {
    //    monthName = UtilProperties.getMessage("CommonUiLabels", monthLabel, locale);
    // }

    templateContext.put("mmddyyyy", mmddyyyy);
    templateContext.put("mmddyyyy2", mmddyyyy2);
    templateContext.put("yyyymmdd", yyyymmdd);
    templateContext.put("yyyymmdd2", yyyymmdd2);
    templateContext.put("month", monthStr);
    templateContext.put("monthName", monthName);
    templateContext.put("day", new Integer(now.get(Calendar.DAY_OF_MONTH)).toString());
    templateContext.put("year", new Integer(now.get(Calendar.YEAR)).toString());

    return templateContext;
  }

  public static Map<String, Object> assembleCrmsfaPartyFormMergeContext(
      Delegator delegator, String partyId) {
    Map<String, Object> templateContext = new HashMap<String, Object>();
    if (UtilValidate.isNotEmpty(partyId)) {
      try {
        String email =
            PartyContactHelper.getElectronicAddressByPurpose(
                partyId, "EMAIL_ADDRESS", "PRIMARY_EMAIL", delegator);
        if (UtilValidate.isNotEmpty(email)) {
          templateContext.put("email", email);
        }
        GenericValue address =
            PartyContactHelper.getPostalAddressValueByPurpose(
                partyId, "PRIMARY_LOCATION", true, delegator);
        if (UtilValidate.isNotEmpty(address)) {
          templateContext.put("attnName", address.get("attnName"));
          templateContext.put("toName", address.get("toName"));
          templateContext.put("address1", address.get("address1"));
          templateContext.put("address2", address.get("address2"));
          templateContext.put("city", address.get("city"));
          templateContext.put("zip", address.get("postalCode"));

          GenericValue stateProvGeo = address.getRelatedOne("StateProvinceGeo");
          if (UtilValidate.isNotEmpty(stateProvGeo)) {
            templateContext.put("state", stateProvGeo.get("geoName"));
          }
          GenericValue countryGeo = address.getRelatedOne("CountryGeo");
          if (UtilValidate.isNotEmpty(countryGeo)) {
            templateContext.put("country", countryGeo.get("geoName"));
          }
        }
        GenericValue party =
            delegator.findByPrimaryKey("PartySummaryCRMView", UtilMisc.toMap("partyId", partyId));
        Map<String, Object> partyMap = party.getAllFields();
        if (UtilValidate.isNotEmpty(partyMap)) {
          Iterator<String> pmf = partyMap.keySet().iterator();
          while (pmf.hasNext()) {
            String fieldName = pmf.next();
            Object value = partyMap.get(fieldName);
            if (UtilValidate.isNotEmpty(value)) {
              templateContext.put(fieldName, value);
            }
          }
        }

        templateContext.put(
            "fullName", org.ofbiz.party.party.PartyHelper.getPartyName(party, false));

      } catch (GenericEntityException ge) {
        Debug.logError(ge, MODULE);
      }
    }
    return templateContext;
  }

  public static Map<String, String> mergePartyWithForm(
      Delegator delegator,
      String mergeFormId,
      String partyId,
      String orderId,
      String shipGroupSeqId,
      String shipmentId,
      Locale locale,
      boolean leaveTags,
      TimeZone timeZone)
      throws GenericEntityException {
    return mergePartyWithForm(
        delegator,
        mergeFormId,
        partyId,
        orderId,
        shipGroupSeqId,
        shipmentId,
        locale,
        leaveTags,
        timeZone,
        true);
  }

  public static Map<String, String> mergePartyWithForm(
      Delegator delegator,
      String mergeFormId,
      String partyId,
      String orderId,
      String shipGroupSeqId,
      String shipmentId,
      Locale locale,
      boolean leaveTags,
      TimeZone timeZone,
      boolean highlightTags)
      throws GenericEntityException {
    Map<String, Object> mergeContext =
        PartyHelper.assembleCrmsfaFormMergeContext(
            delegator, locale, partyId, orderId, shipGroupSeqId, shipmentId, timeZone);
    GenericValue mergeForm =
        delegator.findByPrimaryKey("MergeForm", UtilMisc.toMap("mergeFormId", mergeFormId));
    if (mergeForm == null) return null;
    String mergeFormText = mergeForm.getString("mergeFormText");
    String mergeFormSubject = mergeForm.getString("subject");
    Writer wr = new StringWriter();
    Map<String, String> output = new HashMap<String, String>();
    try {
      FreemarkerUtil.renderTemplateWithTags(
          "MergeForm", mergeFormText, mergeContext, wr, leaveTags, highlightTags);
      output.put("mergeFormText", wr.toString());
      wr = new StringWriter();
      if (UtilValidate.isNotEmpty(mergeForm.getString("subject"))) {
        FreemarkerUtil.renderTemplateWithTags(
            "MergeForm", mergeFormSubject, mergeContext, wr, leaveTags, false);
        output.put("subject", wr.toString());
      } else {
        output.put("subject", mergeForm.getString("mergeFormName"));
      }
    } catch (TemplateException e) {
      Debug.logError(e, MODULE);
      return null;
    } catch (IOException e) {
      Debug.logError(e, MODULE);
      return null;
    }
    return output;
  }

  /**
   * 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;
  }

  /**
   * 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")));
  }

  /** Checks if the given party with role is unassigned. */
  public static boolean isUnassigned(Delegator delegator, String partyId, String roleTypeId)
      throws GenericEntityException {
    List<GenericValue> activeRelationships =
        EntityUtil.filterByDate(
            delegator.findByAnd(
                "PartyRelationship",
                UtilMisc.toMap(
                    "partyIdFrom",
                    partyId,
                    "roleTypeIdFrom",
                    roleTypeId,
                    "partyRelationshipTypeId",
                    "ASSIGNED_TO")));
    return activeRelationships.size() == 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;
  }

  /**
   * Find the active ASSIGNED_TO party relationships with given From and To party IDs, and the role
   * type ID of From party such as 'CONTACT'.
   *
   * @param delegator a Delegator instance
   * @param partyIdFrom a String object that represents the From party ID
   * @param roleTypeIdFrom a String object that represents the role type ID of From party
   * @param partyIdTo a String object that represents the To party ID
   * @return a List of GenericValue objects
   */
  public static List<GenericValue> findActiveAssignedToPartyRelationships(
      final Delegator delegator,
      final String partyIdFrom,
      final String roleTypeIdFrom,
      final String partyIdTo)
      throws GenericEntityException {
    EntityCondition conditions =
        EntityCondition.makeCondition(
            EntityOperator.AND,
            EntityCondition.makeCondition("partyIdFrom", partyIdFrom),
            EntityCondition.makeCondition("roleTypeIdFrom", roleTypeIdFrom),
            EntityCondition.makeCondition("partyIdTo", partyIdTo),
            EntityCondition.makeCondition("partyRelationshipTypeId", "ASSIGNED_TO"),
            EntityUtil.getFilterByDateExpr());
    return delegator.findByCondition("PartyRelationship", conditions, null, null);
  }
}
Ejemplo n.º 21
0
  public static Map<String, Object> assembleCrmsfaShipmentFormMergeContext(
      Delegator delegator,
      String orderId,
      String shipGroupSeqId,
      String shipmentId,
      Locale locale) {
    Map<String, Object> templateContext = new HashMap<String, Object>();

    try {

      // Prefer shipment data if shipmentId is provided
      if (UtilValidate.isNotEmpty(shipmentId)) {

        GenericValue shipment =
            delegator.findByPrimaryKey("Shipment", UtilMisc.toMap("shipmentId", shipmentId));
        if (UtilValidate.isNotEmpty(shipment)) {

          GenericValue shipLoc = shipment.getRelatedOne("DestinationPostalAddress");
          if (UtilValidate.isNotEmpty(shipLoc)) {
            templateContext.put("orderShippingAddress1", shipLoc.get("address1"));
            templateContext.put("orderShippingAddress2", shipLoc.get("address2"));
            templateContext.put("orderShippingCity", shipLoc.get("city"));
            templateContext.put("orderShippingPostalCode", shipLoc.get("postalCode"));

            GenericValue stateProvGeo = shipLoc.getRelatedOne("StateProvinceGeo");
            if (UtilValidate.isNotEmpty(stateProvGeo)) {
              templateContext.put("orderShippingStateProvince", stateProvGeo.get("geoName"));
            }
            GenericValue countryGeo = shipLoc.getRelatedOne("CountryGeo");
            if (UtilValidate.isNotEmpty(countryGeo)) {
              templateContext.put("orderShippingCountry", countryGeo.get("geoName"));
            }
          }

          GenericValue phoneNumber = shipment.getRelatedOne("DestinationTelecomNumber");
          if (UtilValidate.isNotEmpty(phoneNumber)) {

            String phoneNumberString =
                UtilValidate.isEmpty(phoneNumber.getString("countryCode"))
                    ? ""
                    : phoneNumber.getString("countryCode") + " ";
            if (UtilValidate.isNotEmpty(phoneNumber.getString("areaCode"))) {
              phoneNumberString += phoneNumber.getString("areaCode") + " ";
            }
            if (UtilValidate.isNotEmpty(phoneNumber.getString("contactNumber"))) {
              phoneNumberString += phoneNumber.getString("contactNumber");
            }
            templateContext.put("orderShippingPhone", phoneNumberString);
          }

          GenericValue statusItem = shipment.getRelatedOne("StatusItem");
          if (UtilValidate.isNotEmpty(statusItem)) {
            templateContext.put("shipmentStatus", statusItem.get("description", locale));
          }
        }

      } else if (UtilValidate.isNotEmpty(orderId)) {

        OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
        GenericValue shipGroup = orh.getOrderItemShipGroup(shipGroupSeqId);
        if (UtilValidate.isEmpty(shipGroup)) {

          // Default to the first ship group if no shipGroupSeqId is provided
          List shipGroups = orh.getOrderItemShipGroups();
          if (UtilValidate.isNotEmpty(shipGroups)) {
            shipGroup = (GenericValue) shipGroups.get(0);
          }
        }

        if (UtilValidate.isNotEmpty(shipGroup)) {
          GenericValue shipLoc = shipGroup.getRelatedOne("PostalAddress");
          if (UtilValidate.isNotEmpty(shipLoc)) {
            templateContext.put("orderShippingAddress1", shipLoc.get("address1"));
            templateContext.put("orderShippingAddress2", shipLoc.get("address2"));
            templateContext.put("orderShippingCity", shipLoc.get("city"));
            templateContext.put("orderShippingPostalCode", shipLoc.get("postalCode"));

            GenericValue stateProvGeo = shipLoc.getRelatedOne("StateProvinceGeo");
            if (UtilValidate.isNotEmpty(stateProvGeo)) {
              templateContext.put("orderShippingStateProvince", stateProvGeo.get("geoName"));
            }
            GenericValue countryGeo = shipLoc.getRelatedOne("CountryGeo");
            if (UtilValidate.isNotEmpty(countryGeo)) {
              templateContext.put("orderShippingCountry", countryGeo.get("geoName"));
            }
          }

          GenericValue phoneNumber = shipGroup.getRelatedOne("TelecomTelecomNumber");
          if (UtilValidate.isNotEmpty(phoneNumber)) {

            String phoneNumberString =
                UtilValidate.isEmpty(phoneNumber.getString("countryCode"))
                    ? ""
                    : phoneNumber.getString("countryCode") + " ";
            if (UtilValidate.isNotEmpty(phoneNumber.getString("areaCode"))) {
              phoneNumberString += phoneNumber.getString("areaCode") + " ";
            }
            if (UtilValidate.isNotEmpty(phoneNumber.getString("contactNumber"))) {
              phoneNumberString += phoneNumber.getString("contactNumber");
            }
            templateContext.put("orderShippingPhone", phoneNumberString);
          }

          // Find any shipments relating to this ship group
          List<GenericValue> shipments =
              delegator.findByAnd(
                  "Shipment",
                  UtilMisc.toMap(
                      "primaryOrderId",
                      orderId,
                      "primaryShipGroupSeqId",
                      shipGroup.getString("shipGroupSeqId")),
                  UtilMisc.toList("createdStamp DESC"));
          GenericValue shipment = EntityUtil.getFirst(shipments);
          if (UtilValidate.isNotEmpty(shipment)) {
            GenericValue statusItem = shipment.getRelatedOne("StatusItem");
            if (UtilValidate.isNotEmpty(statusItem)) {
              templateContext.put("shipmentStatus", statusItem.get("description", locale));
            }
          }
        }
      }
    } catch (GenericEntityException e) {
      Debug.logError(e, MODULE);
    }
    return templateContext;
  }
Ejemplo n.º 22
0
  public static void indexKeywords(GenericValue product, boolean doAll)
      throws GenericEntityException {
    if (product == null) return;
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

    if (!doAll) {
      if ("N".equals(product.getString("autoCreateKeywords"))) {
        return;
      }
      if ("Y".equals(product.getString("isVariant"))
          && "true"
              .equals(UtilProperties.getPropertyValue("prodsearch", "index.ignore.variants"))) {
        return;
      }
      Timestamp salesDiscontinuationDate = product.getTimestamp("salesDiscontinuationDate");
      if (salesDiscontinuationDate != null
          && salesDiscontinuationDate.before(nowTimestamp)
          && "true"
              .equals(
                  UtilProperties.getPropertyValue(
                      "prodsearch", "index.ignore.discontinued.sales"))) {
        return;
      }
    }

    Delegator delegator = product.getDelegator();
    if (delegator == null) return;
    String productId = product.getString("productId");

    // get these in advance just once since they will be used many times for the multiple strings to
    // index
    String separators = KeywordSearchUtil.getSeparators();
    String stopWordBagOr = KeywordSearchUtil.getStopWordBagOr();
    String stopWordBagAnd = KeywordSearchUtil.getStopWordBagAnd();
    boolean removeStems = KeywordSearchUtil.getRemoveStems();
    Set<String> stemSet = KeywordSearchUtil.getStemSet();

    Map<String, Long> keywords = new TreeMap<String, Long>();
    List<String> strings = FastList.newInstance();

    int pidWeight = 1;
    try {
      pidWeight =
          Integer.parseInt(
              UtilProperties.getPropertyValue("prodsearch", "index.weight.Product.productId", "0"));
    } catch (Exception e) {
      Debug.logWarning("Could not parse weight number: " + e.toString(), module);
    }
    keywords.put(product.getString("productId").toLowerCase(), Long.valueOf(pidWeight));

    // Product fields - default is 0 if not found in the properties file
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.productName", "0"))) {
      addWeightedKeywordSourceString(product, "productName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.internalName", "0"))) {
      addWeightedKeywordSourceString(product, "internalName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue("prodsearch", "index.weight.Product.brandName", "0"))) {
      addWeightedKeywordSourceString(product, "brandName", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.description", "0"))) {
      addWeightedKeywordSourceString(product, "description", strings);
    }
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.Product.longDescription", "0"))) {
      addWeightedKeywordSourceString(product, "longDescription", strings);
    }

    // ProductFeatureAppl
    if (!"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.description", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.abbrev", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductFeatureAndAppl.idCode", "0"))) {
      // get strings from attributes and features
      List<GenericValue> productFeatureAndAppls =
          delegator.findByAnd("ProductFeatureAndAppl", UtilMisc.toMap("productId", productId));
      for (GenericValue productFeatureAndAppl : productFeatureAndAppls) {
        addWeightedKeywordSourceString(productFeatureAndAppl, "description", strings);
        addWeightedKeywordSourceString(productFeatureAndAppl, "abbrev", strings);
        addWeightedKeywordSourceString(productFeatureAndAppl, "idCode", strings);
      }
    }

    // ProductAttribute
    if (!"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductAttribute.attrName", "0"))
        || !"0"
            .equals(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductAttribute.attrValue", "0"))) {
      List<GenericValue> productAttributes =
          delegator.findByAnd("ProductAttribute", UtilMisc.toMap("productId", productId));
      for (GenericValue productAttribute : productAttributes) {
        addWeightedKeywordSourceString(productAttribute, "attrName", strings);
        addWeightedKeywordSourceString(productAttribute, "attrValue", strings);
      }
    }

    // GoodIdentification
    if (!"0"
        .equals(
            UtilProperties.getPropertyValue(
                "prodsearch", "index.weight.GoodIdentification.idValue", "0"))) {
      List<GenericValue> goodIdentifications =
          delegator.findByAnd("GoodIdentification", UtilMisc.toMap("productId", productId));
      for (GenericValue goodIdentification : goodIdentifications) {
        addWeightedKeywordSourceString(goodIdentification, "idValue", strings);
      }
    }

    // Variant Product IDs
    if ("Y".equals(product.getString("isVirtual"))) {
      if (!"0"
          .equals(
              UtilProperties.getPropertyValue(
                  "prodsearch", "index.weight.Variant.Product.productId", "0"))) {
        List<GenericValue> variantProductAssocs =
            delegator.findByAnd(
                "ProductAssoc",
                UtilMisc.toMap("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT"));
        variantProductAssocs = EntityUtil.filterByDate(variantProductAssocs);
        for (GenericValue variantProductAssoc : variantProductAssocs) {
          int weight = 1;
          try {
            weight =
                Integer.parseInt(
                    UtilProperties.getPropertyValue(
                        "prodsearch", "index.weight.Variant.Product.productId", "0"));
          } catch (Exception e) {
            Debug.logWarning("Could not parse weight number: " + e.toString(), module);
          }
          for (int i = 0; i < weight; i++) {
            strings.add(variantProductAssoc.getString("productIdTo"));
          }
        }
      }
    }

    String productContentTypes =
        UtilProperties.getPropertyValue("prodsearch", "index.include.ProductContentTypes");
    for (String productContentTypeId : productContentTypes.split(",")) {
      int weight = 1;
      try {
        // this is defaulting to a weight of 1 because you specified you wanted to index this type
        weight =
            Integer.parseInt(
                UtilProperties.getPropertyValue(
                    "prodsearch", "index.weight.ProductContent." + productContentTypeId, "1"));
      } catch (Exception e) {
        Debug.logWarning("Could not parse weight number: " + e.toString(), module);
      }

      List<GenericValue> productContentAndInfos =
          delegator.findByAnd(
              "ProductContentAndInfo",
              UtilMisc.toMap("productId", productId, "productContentTypeId", productContentTypeId),
              null);
      for (GenericValue productContentAndInfo : productContentAndInfos) {
        addWeightedDataResourceString(productContentAndInfo, weight, strings, delegator, product);

        List<GenericValue> alternateViews =
            productContentAndInfo.getRelated(
                "ContentAssocDataResourceViewTo",
                UtilMisc.toMap("caContentAssocTypeId", "ALTERNATE_LOCALE"),
                UtilMisc.toList("-caFromDate"));
        alternateViews =
            EntityUtil.filterByDate(
                alternateViews, UtilDateTime.nowTimestamp(), "caFromDate", "caThruDate", true);
        for (GenericValue thisView : alternateViews) {
          addWeightedDataResourceString(thisView, weight, strings, delegator, product);
        }
      }
    }
    if (UtilValidate.isNotEmpty(strings)) {
      for (String str : strings) {
        // call process keywords method here
        KeywordSearchUtil.processKeywordsForIndex(
            str, keywords, separators, stopWordBagAnd, stopWordBagOr, removeStems, stemSet);
      }
    }

    List<GenericValue> toBeStored = FastList.newInstance();
    int keywordMaxLength =
        Integer.parseInt(
            UtilProperties.getPropertyValue("prodsearch", "product.keyword.max.length"));
    for (Map.Entry<String, Long> entry : keywords.entrySet()) {
      if (entry.getKey().length() <= keywordMaxLength) {
        GenericValue productKeyword =
            delegator.makeValue(
                "ProductKeyword",
                UtilMisc.toMap(
                    "productId",
                    product.getString("productId"),
                    "keyword",
                    entry.getKey(),
                    "keywordTypeId",
                    "KWT_KEYWORD",
                    "relevancyWeight",
                    entry.getValue()));
        toBeStored.add(productKeyword);
      }
    }
    if (toBeStored.size() > 0) {
      if (Debug.verboseOn())
        Debug.logVerbose(
            "[KeywordIndex.indexKeywords] Storing "
                + toBeStored.size()
                + " keywords for productId "
                + product.getString("productId"),
            module);

      if ("true"
          .equals(
              UtilProperties.getPropertyValue("prodsearch", "index.delete.on_index", "false"))) {
        // delete all keywords if the properties file says to
        delegator.removeByAnd(
            "ProductKeyword", UtilMisc.toMap("productId", product.getString("productId")));
      }

      delegator.storeAll(toBeStored);
    }
  }
Ejemplo n.º 23
0
 // ======= Some Convenience Oriented Factory Methods =======
 public static List<ModelKeyMap> makeKeyMapList(String fieldName1) {
   return UtilMisc.toList(new ModelKeyMap(fieldName1, null));
 }
Ejemplo n.º 24
0
  public static void saveGroup(String groupId, String stype, HashMap hashMap) throws Exception {

    EntityCondition whereCondition =
        EntityCondition.makeCondition(
            UtilMisc.toList(
                EntityCondition.makeCondition("id", EntityOperator.EQUALS, groupId),
                EntityCondition.makeCondition("stype", EntityOperator.EQUALS, stype)),
            EntityOperator.AND);

    List<GenericValue> groups =
        getDelegator()
            .findList("SvGroup", whereCondition, null, UtilMisc.toList("idx"), null, false);
    if (!(groups.size() > 0)) {
      GenericValue group = getDelegator().makeValue("SvGroup");
      group.set("id", groupId);
      String[] splits = groupId.split("\\.");
      if (splits.length > 1) {
        group.set("parent", splits[0]);
      }
      group.set("stype", stype);
      group.create();
    }

    whereCondition =
        EntityCondition.makeCondition(
            UtilMisc.toList(
                EntityCondition.makeCondition("groupId", EntityOperator.EQUALS, groupId),
                EntityCondition.makeCondition("stype", EntityOperator.EQUALS, stype)),
            EntityOperator.AND);
    List<GenericValue> groupValue =
        getDelegator()
            .findList("SvGroupValue", whereCondition, null, UtilMisc.toList("idx"), null, false);
    long maxIdx = 0;
    try {
      int index = groupValue.size() - 1;
      GenericValue val = groupValue.get(index);
      maxIdx = val.getInteger("idx");
    } catch (Exception e) {
    }

    for (GenericValue val : groupValue) {
      String key = val.getString("attrName");
      if (key == null) continue;
      boolean bExist = false;
      Enumeration<?> enumKeys = hashMap.keys();
      while (enumKeys.hasMoreElements()) {
        Object obj = enumKeys.nextElement();
        String keyi = null;
        if (obj instanceof StringProperty) {
          keyi = ((StringProperty) obj).getName();
        } else {
          keyi = (String) obj;
        }
        if (key.equals(keyi)) {
          bExist = true;
        }
      }
      if (!bExist) {
        val.remove();
      }
    }

    Enumeration<?> enumeration = hashMap.keys();
    while (enumeration.hasMoreElements()) {
      Object obj = enumeration.nextElement();
      String key = null;
      if (obj instanceof StringProperty) {
        key = ((StringProperty) obj).getName();
      } else {
        key = (String) obj;
      }
      if (key == null) continue;

      String value = null;
      if (obj instanceof StringProperty) {
        value = ((StringProperty) obj).getValue();
      } else if (obj instanceof Array) {

      } else if (obj instanceof String) {
        value = "" + hashMap.get(key);
      }
      value = "".equals(value) ? null : value;
      boolean bExist = false;

      for (GenericValue val : groupValue) {
        if (key.equals(val.getString("attrName"))) {
          if (value == null) {
            val.remove();
          } else {
            val.set("attrValue", value);
            val.store();
          }
          bExist = true;
        }
      }
      if (!bExist && value != null) {
        GenericValue val = getDelegator().makeValue("SvGroupValue");
        val.set("groupId", groupId);
        val.set("stype", stype);
        maxIdx++;
        val.set("idx", maxIdx);
        val.set("attrName", key);
        val.set("attrValue", value);
        val.create();
      }
    }
  }
Ejemplo n.º 25
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();
  }
Ejemplo n.º 26
0
  public static Map<String, Object> sendCatalogRequestNotificationEmail(
      DispatchContext dctx, Map<String, Object> context) {

    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    Locale locale = UtilCommon.getLocale(context);
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String custRequestId = (String) context.get("custRequestId");

    boolean sendEmail =
        "true"
            .equalsIgnoreCase(
                UtilProperties.getMessage(
                        notificationResource,
                        "email.marketing.catalog.sendCatalogRequestEmails",
                        locale)
                    .trim());
    if (!sendEmail) {
      Debug.logInfo(
          UtilProperties.getMessage(
              resource,
              "crmsfa.sendCrmNotificationEmailsCatRqTurnedOff",
              UtilMisc.toMap("custRequestId", custRequestId),
              locale),
          MODULE);
      return ServiceUtil.returnSuccess();
    }

    String mailToPartyId = (String) context.get("fromPartyId");

    try {
      Map<String, Object> paramsMap = FastMap.newInstance();

      paramsMap.put("eventType", "marketing.catalog");
      paramsMap.put(
          "subject",
          UtilProperties.getMessage(notificationResource, "subject.marketing.catalog", locale));
      paramsMap.put("locale", locale);
      paramsMap.put("userLogin", userLogin);
      paramsMap.put("notifyPartyIds", UtilMisc.toList(mailToPartyId));

      Map<String, Object> bodyParameters = FastMap.newInstance();

      GenericValue custRequest =
          delegator.findByPrimaryKey("CustRequest", UtilMisc.toMap("custRequestId", custRequestId));
      GenericValue contactMech = custRequest.getRelatedOne("FulfillContactMech");
      GenericValue postalAddress = contactMech.getRelatedOne("PostalAddress");
      String address1 = (String) postalAddress.get("address1");
      String address2 = (String) postalAddress.get("address2");
      String city = (String) postalAddress.get("city");
      String postalCode = (String) postalAddress.get("postalCode");
      String stateProvinceGeoId = (String) postalAddress.get("stateProvinceGeoId");
      GenericValue country = postalAddress.getRelatedOne("CountryGeo");
      String countryName = (String) country.get("geoName");
      GenericValue party =
          delegator.findByPrimaryKey(
              "PartySummaryCRMView", UtilMisc.toMap("partyId", custRequest.get("fromPartyId")));

      bodyParameters.put("firstName", party.get("firstName"));
      bodyParameters.put("lastName", party.get("lastName"));
      bodyParameters.put("address1", address1);
      bodyParameters.put("address2", address2);
      bodyParameters.put("city", city);
      bodyParameters.put("postalCode", postalCode);
      bodyParameters.put("stateProvinceGeoId", stateProvinceGeoId);
      bodyParameters.put("countryName", countryName);

      paramsMap.put("bodyParameters", bodyParameters);

      dispatcher.runSync("crmsfa.sendCrmNotificationEmails", paramsMap);

    } catch (GenericServiceException gse) {
      return UtilMessage.createAndLogServiceError(gse, MODULE);
    } catch (GenericEntityException gee) {
      return UtilMessage.createAndLogServiceError(gee, MODULE);
    }

    return ServiceUtil.returnSuccess();
  }
Ejemplo n.º 27
0
  // Note we're not doing a lot of error checking here as this method is really only used
  // to confirm the order with PayPal, the subsequent authorizations will handle any errors
  // that may occur.
  public static Map<String, Object> doExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    OrderReadHelper orh = new OrderReadHelper(delegator, paymentPref.getString("orderId"));
    Locale locale = (Locale) context.get("locale");

    GenericValue payPalPaymentSetting = getPaymentMethodGatewayPayPal(dctx, context, null);
    GenericValue payPalPaymentMethod = null;
    try {
      payPalPaymentMethod = paymentPref.getRelatedOne("PaymentMethod", false);
      payPalPaymentMethod = payPalPaymentMethod.getRelatedOne("PayPalPaymentMethod", false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    BigDecimal processAmount = paymentPref.getBigDecimal("maxAmount");

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "DoExpressCheckoutPayment");
    encoder.add("TOKEN", payPalPaymentMethod.getString("expressCheckoutToken"));
    encoder.add("PAYMENTACTION", "Order");
    encoder.add("PAYERID", payPalPaymentMethod.getString("payerId"));
    // set the amount
    encoder.add("AMT", processAmount.setScale(2).toPlainString());
    encoder.add("CURRENCYCODE", orh.getCurrency());
    BigDecimal grandTotal = orh.getOrderGrandTotal();
    BigDecimal shippingTotal = orh.getShippingTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal taxTotal = orh.getTaxTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    BigDecimal subTotal =
        grandTotal.subtract(shippingTotal).subtract(taxTotal).setScale(2, BigDecimal.ROUND_HALF_UP);
    encoder.add("ITEMAMT", subTotal.toPlainString());
    encoder.add("SHIPPINGAMT", shippingTotal.toPlainString());
    encoder.add("TAXAMT", taxTotal.toPlainString());

    NVPDecoder decoder = null;
    try {
      decoder = sendNVPRequest(payPalPaymentSetting, 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, String> errorMessages = getErrorMessageMap(decoder);
    if (UtilValidate.isNotEmpty(errorMessages)) {
      if (errorMessages.containsKey("10417")) {
        // "The transaction cannot complete successfully,  Instruct the customer to use an
        // alternative payment method"
        // I've only encountered this once and there's no indication of the cause so the temporary
        // solution is to try again
        boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
        if (retry) {
          context.put("_RETRY_", false);
          return PayPalServices.doExpressCheckout(dctx, context);
        }
      }
      return ServiceUtil.returnError(UtilMisc.toList(errorMessages.values()));
    }

    Map<String, Object> inMap = FastMap.newInstance();
    inMap.put("userLogin", userLogin);
    inMap.put("paymentMethodId", payPalPaymentMethod.get("paymentMethodId"));
    inMap.put("transactionId", decoder.get("TRANSACTIONID"));

    Map<String, Object> outMap = null;
    try {
      outMap = dispatcher.runSync("updatePayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(outMap)) {
      Debug.logError(ServiceUtil.getErrorMessage(outMap), module);
      return outMap;
    }
    return ServiceUtil.returnSuccess();
  }
Ejemplo n.º 28
0
  /**
   * Finds all matching parties based on the values provided. Excludes party records with a statusId
   * of PARTY_DISABLED. Results are ordered by descending PartyContactMech.fromDate. 1. Candidate
   * addresses are found by querying PartyAndPostalAddress using the supplied city and if provided,
   * stateProvinceGeoId, postalCode, postalCodeExt and countryGeoId 2. In-memory address line
   * comparisons are then performed against the supplied address1 and if provided, address2. Address
   * lines are compared after the strings have been converted using {@link
   * #makeMatchingString(Delegator, String)}.
   *
   * @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 partyTypeId Optional Party.partyTypeId to match against.
   * @return List of PartyAndPostalAddress GenericValue objects that match the supplied criteria.
   * @throws GenericEntityException
   */
  public static List<GenericValue> findMatchingPartyPostalAddress(
      Delegator delegator,
      String address1,
      String address2,
      String city,
      String stateProvinceGeoId,
      String postalCode,
      String postalCodeExt,
      String countryGeoId,
      String partyTypeId)
      throws GenericEntityException {

    if (address1 == null || city == null || postalCode == null) {
      throw new IllegalArgumentException();
    }

    List<EntityCondition> addrExprs = FastList.newInstance();
    if (stateProvinceGeoId != null) {
      if ("**".equals(stateProvinceGeoId)) {
        Debug.logWarning("Illegal state code passed!", module);
      } else if ("NA".equals(stateProvinceGeoId)) {
        addrExprs.add(
            EntityCondition.makeCondition("stateProvinceGeoId", EntityOperator.EQUALS, "_NA_"));
      } else {
        addrExprs.add(
            EntityCondition.makeCondition(
                "stateProvinceGeoId", EntityOperator.EQUALS, stateProvinceGeoId.toUpperCase()));
      }
    }

    if (!postalCode.startsWith("*")) {
      if (postalCode.length() == 10 && postalCode.indexOf("-") != -1) {
        String[] zipSplit = postalCode.split("-", 2);
        postalCode = zipSplit[0];
        postalCodeExt = zipSplit[1];
      }
      addrExprs.add(EntityCondition.makeCondition("postalCode", EntityOperator.EQUALS, postalCode));
    }

    if (postalCodeExt != null) {
      addrExprs.add(
          EntityCondition.makeCondition("postalCodeExt", EntityOperator.EQUALS, postalCodeExt));
    }

    addrExprs.add(
        EntityCondition.makeCondition(
            EntityFunction.UPPER_FIELD("city"), EntityOperator.EQUALS, EntityFunction.UPPER(city)));

    if (countryGeoId != null) {
      addrExprs.add(
          EntityCondition.makeCondition(
              "countryGeoId", EntityOperator.EQUALS, countryGeoId.toUpperCase()));
    }

    // limit to only non-disabled status
    addrExprs.add(
        EntityCondition.makeCondition(
            EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, null),
            EntityOperator.OR,
            EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "PARTY_DISABLED")));

    if (partyTypeId != null) {
      addrExprs.add(
          EntityCondition.makeCondition("partyTypeId", EntityOperator.EQUALS, partyTypeId));
    }

    List<String> sort = UtilMisc.toList("-fromDate");
    EntityCondition addrCond = EntityCondition.makeCondition(addrExprs, EntityOperator.AND);
    List<GenericValue> addresses =
        EntityUtil.filterByDate(
            delegator.findList("PartyAndPostalAddress", addrCond, null, sort, null, false));
    // Debug.logInfo("Checking for matching address: " + addrCond.toString() + "[" +
    // addresses.size() + "]", module);

    if (UtilValidate.isEmpty(addresses)) {
      // No address matches, return an empty list
      return addresses;
    }

    List<GenericValue> validFound = FastList.newInstance();
    // check the address line
    for (GenericValue address : addresses) {
      // address 1 field
      String addr1Source = PartyWorker.makeMatchingString(delegator, address1);
      String addr1Target = PartyWorker.makeMatchingString(delegator, address.getString("address1"));

      if (addr1Target != null) {
        Debug.logInfo("Comparing address1 : " + addr1Source + " / " + addr1Target, module);
        if (addr1Target.equals(addr1Source)) {

          // address 2 field
          if (address2 != null) {
            String addr2Source = PartyWorker.makeMatchingString(delegator, address2);
            String addr2Target =
                PartyWorker.makeMatchingString(delegator, address.getString("address2"));
            if (addr2Target != null) {
              Debug.logInfo("Comparing address2 : " + addr2Source + " / " + addr2Target, module);

              if (addr2Source.equals(addr2Target)) {
                Debug.logInfo("Matching address2; adding valid address", module);
                validFound.add(address);
                // validParty.put(address.getString("partyId"), address.getString("contactMechId"));
              }
            }
          } else {
            if (address.get("address2") == null) {
              Debug.logInfo("No address2; adding valid address", module);
              validFound.add(address);
              // validParty.put(address.getString("partyId"), address.getString("contactMechId"));
            }
          }
        }
      }
    }
    return validFound;
  }
Ejemplo n.º 29
0
  public static String timeSheetChecker(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    Delegator delegator = (Delegator) session.getAttribute("delegator");
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    List<Map<String, Object>> noTimeEntryList = new LinkedList<Map<String, Object>>();
    String partyId = userLogin.getString("partyId");
    Timestamp now = UtilDateTime.nowTimestamp();
    Timestamp weekStart = UtilDateTime.getWeekStart(now);

    if (UtilValidate.isEmpty(delegator)) {
      delegator = (Delegator) request.getAttribute("delegator");
    }

    try {
      // should be scrum team or scrum master.
      EntityConditionList<EntityExpr> exprOrs =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_TEAM"),
                  EntityCondition.makeCondition(
                      "roleTypeId", EntityOperator.EQUALS, "SCRUM_MASTER")),
              EntityOperator.OR);
      EntityConditionList<EntityCondition> exprAnds =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  exprOrs,
                  EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)),
              EntityOperator.AND);
      List<GenericValue> partyRoleList =
          EntityQuery.use(delegator).from("PartyRole").where(exprAnds).queryList();
      if (UtilValidate.isNotEmpty(partyRoleList)) {
        List<GenericValue> timesheetList =
            EntityQuery.use(delegator)
                .from("Timesheet")
                .where("partyId", partyId, "statusId", "TIMESHEET_IN_PROCESS")
                .cache(true)
                .queryList();
        if (UtilValidate.isNotEmpty(timesheetList)) {
          for (GenericValue timesheetMap : timesheetList) {
            String timesheetId = timesheetMap.getString("timesheetId");
            Timestamp timesheetDate = timesheetMap.getTimestamp("fromDate");
            // check monday - friday
            for (int i = 0; i < 5; i++) {
              Timestamp realTimeDate = UtilDateTime.addDaysToTimestamp(timesheetDate, i);
              Timestamp nowStartDate = UtilDateTime.getDayStart(now);
              // compare week and compare date
              if ((timesheetDate.compareTo(weekStart) <= 0)
                  && (realTimeDate.compareTo(nowStartDate) < 0)) {
                // check time entry
                List<GenericValue> timeEntryList =
                    timesheetMap.getRelated(
                        "TimeEntry",
                        UtilMisc.toMap(
                            "partyId",
                            partyId,
                            "timesheetId",
                            timesheetId,
                            "fromDate",
                            realTimeDate),
                        null,
                        false);
                // check EmplLeave
                List<GenericValue> emplLeaveList =
                    EntityQuery.use(delegator)
                        .from("EmplLeave")
                        .where("partyId", partyId, "fromDate", realTimeDate)
                        .cache(true)
                        .queryList();
                if (UtilValidate.isEmpty(timeEntryList) && UtilValidate.isEmpty(emplLeaveList)) {
                  Map<String, Object> noEntryMap = new HashMap<String, Object>();
                  noEntryMap.put("timesheetId", timesheetId);
                  noTimeEntryList.add(noEntryMap);
                  break;
                }
              }
            }
          }
        }
      }
    } catch (GenericEntityException EntEx) {
      EntEx.printStackTrace();
      Debug.logError(EntEx.getMessage(), module);
    }
    if (UtilValidate.isNotEmpty(noTimeEntryList)) {
      StringBuilder warningDataBuffer = new StringBuilder();
      int size = noTimeEntryList.size();
      for (Map<String, Object> dataMap : noTimeEntryList) {
        if (--size == 0) {
          warningDataBuffer.append(dataMap.get("timesheetId"));
        } else {
          warningDataBuffer.append(dataMap.get("timesheetId")).append(", ");
        }
        warningDataBuffer.append(dataMap.get("timesheetId"));
      }
      String warningData = warningDataBuffer.toString();
      Debug.logInfo("The following time sheet no time entry: [" + warningData + "]", module);
      request.setAttribute(
          "_ERROR_MESSAGE_",
          UtilProperties.getMessage(
              "scrumUiLabels",
              "ScrumTimesheetWarningMessage",
              UtilMisc.toMap("warningMessage", warningData),
              UtilHttp.getLocale(request)));
    }
    return "success";
  }
Ejemplo n.º 30
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();
  }