/** Creates request fields for a customer, such as email and postal addresses. */
  private static Map buildCustomerRequest(Delegator delegator, Map context)
      throws GenericEntityException {
    Map request = FastMap.newInstance();
    GenericValue customer = (GenericValue) context.get("billToParty");
    GenericValue address = (GenericValue) context.get("billingAddress");
    GenericValue email = (GenericValue) context.get("billToEmail");

    if (customer != null && "Person".equals(customer.getEntityName())) {
      request.put("x_first_name", customer.get("firstName"));
      request.put("x_last_name", customer.get("lastName"));
    }
    if (customer != null && "PartyGroup".equals(customer.getEntityName())) {
      request.put("x_company", customer.get("groupName"));
    }
    if (address != null) {
      request.put("x_address", address.get("address1"));
      request.put("x_city", address.get("city"));
      request.put("x_zip", address.get("postalCode"));
      GenericValue country = address.getRelatedOneCache("CountryGeo");
      if (country != null) {
        request.put("x_country", country.get("geoCode"));
        if ("USA".equals(country.get("geoId"))) {
          request.put("x_state", address.get("stateProvinceGeoId"));
        }
      }
    }
    if (email != null && UtilValidate.isNotEmpty(email.getString("infoString"))) {
      request.put("x_email", email.get("infoString"));
    }

    return request;
  }
Exemple #2
0
 /**
  * Method to return the amount applied converted to the currency of payment
  *
  * @param paymentApplicationId the payment application id
  * @return appliedAmount the applied amount as BigDecimal
  */
 public static BigDecimal getPaymentAppliedAmount(
     Delegator delegator, String paymentApplicationId) {
   GenericValue paymentApplication = null;
   BigDecimal appliedAmount = BigDecimal.ZERO;
   try {
     paymentApplication =
         delegator.findByPrimaryKey(
             "PaymentApplication", UtilMisc.toMap("paymentApplicationId", paymentApplicationId));
     appliedAmount = paymentApplication.getBigDecimal("amountApplied");
     if (paymentApplication.get("paymentId") != null) {
       GenericValue payment = paymentApplication.getRelatedOne("Payment");
       if (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"))) {
           appliedAmount =
               appliedAmount
                   .multiply(payment.getBigDecimal("amount"))
                   .divide(payment.getBigDecimal("actualCurrencyAmount"), new MathContext(100));
         }
       }
     }
   } catch (GenericEntityException e) {
     Debug.logError(e, "Problem getting Payment", module);
   }
   return appliedAmount;
 }
  public static void getCategoryContentWrappers(
      Map<String, CategoryContentWrapper> catContentWrappers,
      List<GenericValue> categoryList,
      HttpServletRequest request)
      throws GenericEntityException {
    if (catContentWrappers == null || categoryList == null) {
      return;
    }
    for (GenericValue cat : categoryList) {
      String productCategoryId = (String) cat.get("productCategoryId");

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

      CategoryContentWrapper catContentWrapper = new CategoryContentWrapper(cat, request);
      catContentWrappers.put(productCategoryId, catContentWrapper);
      List<GenericValue> subCat =
          getRelatedCategoriesRet(request, "subCatList", productCategoryId, true);
      if (subCat != null) {
        getCategoryContentWrappers(catContentWrappers, subCat, request);
      }
    }
  }
Exemple #4
0
 public static String formatPartyNameObject(GenericValue partyValue, boolean lastNameFirst) {
   if (partyValue == null) {
     return "";
   }
   StringBuilder result = new StringBuilder();
   ModelEntity modelEntity = partyValue.getModelEntity();
   if (modelEntity.isField("firstName")
       && modelEntity.isField("middleName")
       && modelEntity.isField("lastName")) {
     if (lastNameFirst) {
       if (UtilFormatOut.checkNull(partyValue.getString("lastName")) != null) {
         result.append(UtilFormatOut.checkNull(partyValue.getString("lastName")));
         if (partyValue.getString("firstName") != null) {
           result.append(", ");
         }
       }
       result.append(UtilFormatOut.checkNull(partyValue.getString("firstName")));
     } else {
       result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("firstName"), "", " "));
       result.append(UtilFormatOut.ifNotEmpty(partyValue.getString("middleName"), "", " "));
       result.append(UtilFormatOut.checkNull(partyValue.getString("lastName")));
     }
   }
   if (modelEntity.isField("groupName") && partyValue.get("groupName") != null) {
     result.append(partyValue.getString("groupName"));
   }
   return result.toString();
 }
 /** 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;
 }
Exemple #6
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;
  }
Exemple #7
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;
 }
 private static String translateAccountNumber(GenericValue eftAccount) {
   String accountNumber = eftAccount.getString("accountNumber").replaceAll("\\D", "");
   if (accountNumber.length() > 20) {
     Debug.logWarning(
         "EftAccount with paymentMethodId ["
             + eftAccount.get("paymentMethodId")
             + "] has a accountNumber larger than 20 digits.  Truncating to 20.",
         module);
     return accountNumber.substring(0, 20);
   }
   return accountNumber;
 }
 private static String translateRoutingNumber(GenericValue eftAccount) {
   String routingNumber = eftAccount.getString("routingNumber").replaceAll("\\D", "");
   if (routingNumber.length() > 9) {
     Debug.logWarning(
         "EftAccount with paymentMethodId ["
             + eftAccount.get("paymentMethodId")
             + "] has a routingNumber larger than 9 digits.  Truncating to 9.",
         module);
     return routingNumber.substring(0, 9);
   }
   return routingNumber;
 }
Exemple #10
0
  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;
  }
Exemple #11
0
  /**
   * Create Note Record
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp noteDate = (Timestamp) context.get("noteDate");
    String partyId = (String) context.get("partyId");
    String noteName = (String) context.get("noteName");
    String note = (String) context.get("note");
    String noteId = delegator.getNextSeqId("NoteData");
    Locale locale = (Locale) context.get("locale");
    if (noteDate == null) {
      noteDate = UtilDateTime.nowTimestamp();
    }

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

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

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

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

    result.put("noteId", noteId);
    result.put("partyId", partyId);
    return result;
  }
  private static String translateAccountType(GenericValue eftAccount) {
    String type = eftAccount.getString("accountType");
    if (UtilValidate.isEmpty(type)) {
      Debug.logWarning(
          "EftAccount with paymentMethodId ["
              + eftAccount.get("paymentMethodId")
              + "] does not have an account type defined.  Assuming CHECKING.",
          module);
      return "CHECKING";
    }
    type = type.toUpperCase();

    if (type.contains("BUSINESS")) return "BUSINESSCHECKING";
    if (type.contains("SAVING")) return "SAVINGS";
    return "CHECKING";
  }
  /** Method to get a condition that checks that the given fieldName is in a given timePeriod. */
  public static EntityCondition getFilterByPeriodExpr(String fieldName, GenericValue timePeriod) {
    Timestamp fromDate;
    Timestamp thruDate;
    if (timePeriod.get("fromDate") instanceof Timestamp) {
      fromDate = timePeriod.getTimestamp("fromDate");
      thruDate = timePeriod.getTimestamp("thruDate");
    } else {
      fromDate = UtilDateTime.toTimestamp(timePeriod.getDate("fromDate"));
      thruDate = UtilDateTime.toTimestamp(timePeriod.getDate("thruDate"));
    }

    EntityConditionList betweenCondition =
        EntityCondition.makeCondition(
            EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN, fromDate),
            EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
    return EntityCondition.makeCondition(
        EntityCondition.makeCondition(fieldName, EntityOperator.NOT_EQUAL, null), betweenCondition);
  }
Exemple #14
0
 /**
  * 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();
 }
  public static Map<String, Object> finAccountReleaseAuth(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    Locale locale = (Locale) context.get("locale");

    String err =
        UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeExpired", locale);
    try {

      // expire the related financial authorization transaction
      GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
      if (authTransaction == null) {
        return ServiceUtil.returnError(
            err
                + UtilProperties.getMessage(
                    resourceError, "AccountingFinAccountCannotFindAuthorization", locale));
      }

      Map<String, Object> input =
          UtilMisc.toMap(
              "userLogin", userLogin, "finAccountAuthId", authTransaction.get("referenceNum"));
      Map<String, Object> serviceResults = dispatcher.runSync("expireFinAccountAuth", input);

      Map<String, Object> result = ServiceUtil.returnSuccess();
      result.put("releaseRefNum", authTransaction.getString("referenceNum"));
      result.put("releaseAmount", authTransaction.getBigDecimal("amount"));
      result.put("releaseResult", Boolean.TRUE);

      // if there's an error, don't release
      if (ServiceUtil.isError(serviceResults)) {
        return ServiceUtil.returnError(err + ServiceUtil.getErrorMessage(serviceResults));
      }

      return result;
    } catch (GenericServiceException e) {
      Debug.logError(e, e.getMessage(), module);
      return ServiceUtil.returnError(err + e.getMessage());
    }
  }
Exemple #16
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;
 }
  /**
   * Populates request fields for a given eft account, amount, and transaction type. The transaction
   * type will be one of "AUTH_CAPTURE" or "REFUND". If there is some critical data missing, this
   * throws GenericServiceException.
   */
  private static Map buildRequest(
      GenericValue eftAccount, Double amount, String currencyUomId, String transactionType) {
    Map request = FastMap.newInstance();

    request.put("x_method", "ECHECK");
    request.put("x_amount", amount.toString());
    request.put("x_currency_code", currencyUomId);
    request.put("x_type", transactionType);
    request.put("x_bank_aba_code", translateRoutingNumber(eftAccount));
    request.put("x_bank_acct_num", translateAccountNumber(eftAccount));
    request.put("x_bank_acct_type", translateAccountType(eftAccount));
    request.put("x_bank_name", eftAccount.get("bankName"));

    // use the company name of the account, otherwise the customer name
    String nameOnAccount = eftAccount.getString("companyNameOnAccount");
    if (UtilValidate.isEmpty(nameOnAccount)) {
      nameOnAccount = eftAccount.getString("nameOnAccount");
    }
    request.put("x_bank_acct_name", nameOnAccount);

    return request;
  }
Exemple #18
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();
  }
 /** Creates request fields for an order, such as the items and quantities. */
 private static Map buildOrderRequest(Map context) {
   Map request = FastMap.newInstance();
   GenericValue pref = (GenericValue) context.get("orderPaymentPreference");
   if (pref != null) request.put("x_invoice_num", "Order " + pref.get("orderId"));
   return request;
 }
Exemple #20
0
  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;
  }
Exemple #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;
  }
  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();
  }
  public static Map<String, Object> finAccountCapture(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue authTrans = (GenericValue) context.get("authTrans");
    BigDecimal amount = (BigDecimal) context.get("captureAmount");
    String currency = (String) context.get("currency");

    // get the authorization transaction
    if (authTrans == null) {
      authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
    }
    if (authTrans == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotCapture", locale));
    }

    // get the auth record
    String finAccountAuthId = authTrans.getString("referenceNum");
    GenericValue finAccountAuth;
    try {
      finAccountAuth =
          EntityQuery.use(delegator)
              .from("FinAccountAuth")
              .where("finAccountAuthId", finAccountAuthId)
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    Debug.logInfo(
        "Financial account capture ["
            + finAccountAuth.get("finAccountId")
            + "] for the amount of $"
            + amount
            + " Tx #"
            + finAccountAuth.get("finAccountAuthId"),
        module);

    // get the financial account
    GenericValue finAccount;
    try {
      finAccount = finAccountAuth.getRelatedOne("FinAccount", false);
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // make sure authorization has not expired
    Timestamp authExpiration = finAccountAuth.getTimestamp("thruDate");
    if ((authExpiration != null) && (authExpiration.before(UtilDateTime.nowTimestamp()))) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountAuthorizationExpired",
              UtilMisc.toMap(
                  "paymentGatewayResponseId",
                  authTrans.getString("paymentGatewayResponseId"),
                  "authExpiration",
                  authExpiration),
              locale));
    }

    // make sure the fin account itself has not expired
    if ((finAccount.getTimestamp("thruDate") != null)
        && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountExpired",
              UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")),
              locale));
    }
    String finAccountId = finAccount.getString("finAccountId");

    // need the product store ID & party ID
    String orderId = orderPaymentPreference.getString("orderId");
    String productStoreId = null;
    String partyId = null;
    if (orderId != null) {
      OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
      productStoreId = orh.getProductStoreId();

      GenericValue billToParty = orh.getBillToParty();
      if (billToParty != null) {
        partyId = billToParty.getString("partyId");
      }
    }

    // BIG NOTE: make sure the expireFinAccountAuth and finAccountWithdraw services are done in the
    // SAME TRANSACTION
    // (i.e. no require-new-transaction in either of them AND no running async)

    // cancel the authorization before doing the withdraw to avoid problems with way negative
    // available amount on account; should happen in same transaction to avoid conflict problems
    Map<String, Object> releaseResult;
    try {
      releaseResult =
          dispatcher.runSync(
              "expireFinAccountAuth",
              UtilMisc.<String, Object>toMap(
                  "userLogin", userLogin, "finAccountAuthId", finAccountAuthId));
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(releaseResult)) {
      return releaseResult;
    }

    // build the withdraw context
    Map<String, Object> withdrawCtx = new HashMap<String, Object>();
    withdrawCtx.put("finAccountId", finAccountId);
    withdrawCtx.put("productStoreId", productStoreId);
    withdrawCtx.put("currency", currency);
    withdrawCtx.put("partyId", partyId);
    withdrawCtx.put("orderId", orderId);
    withdrawCtx.put("amount", amount);
    withdrawCtx.put("reasonEnumId", "FATR_PURCHASE");
    withdrawCtx.put("requireBalance", Boolean.FALSE); // for captures; if auth passed, allow
    withdrawCtx.put("userLogin", userLogin);

    // call the withdraw service
    Map<String, Object> withdrawResp;
    try {
      withdrawResp = dispatcher.runSync("finAccountWithdraw", withdrawCtx);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    if (ServiceUtil.isError(withdrawResp)) {
      return withdrawResp;
    }

    // create the capture response
    Map<String, Object> result = ServiceUtil.returnSuccess();
    Boolean processResult = (Boolean) withdrawResp.get("processResult");
    BigDecimal withdrawAmount = (BigDecimal) withdrawResp.get("amount");
    String referenceNum = (String) withdrawResp.get("referenceNum");
    result.put("captureResult", processResult);
    result.put("captureRefNum", referenceNum);
    result.put("captureCode", "C");
    result.put("captureFlag", "1");
    result.put("captureAmount", withdrawAmount);

    return result;
  }
  /**
   * Makes a list of TrackingCodeOrder entities to be attached to the current order; called by the
   * createOrder event; the values in the returned List will not have the orderId set
   */
  public static List<GenericValue> makeTrackingCodeOrders(HttpServletRequest request) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp();
    List<GenericValue> trackingCodeOrders = FastList.newInstance();

    Cookie[] cookies = request.getCookies();
    Timestamp affiliateReferredTimeStamp = null;
    String siteId = null;
    String isBillable = null;
    String trackingCodeId = null;
    if (cookies != null && cookies.length > 0) {
      for (int i = 0; i < cookies.length; i++) {
        String cookieName = cookies[i].getName();

        Debug.logInfo(" cookieName is " + cookieName, module);
        Debug.logInfo(" cookieValue is " + cookies[i].getValue(), module);
        // find the siteId cookie if it exists
        if ("Ofbiz.TKCD.SiteId".equals(cookieName)) {
          siteId = cookies[i].getValue();
        }

        // find the referred timestamp cookie if it exists
        if ("Ofbiz.TKCD.UpdatedTimeStamp".equals(cookieName)) {
          String affiliateReferredTime = cookies[i].getValue();
          if (affiliateReferredTime != null && !affiliateReferredTime.equals("")) {
            try {
              affiliateReferredTimeStamp = Timestamp.valueOf(affiliateReferredTime);
            } catch (IllegalArgumentException e) {
              Debug.logError(
                  e, "Error parsing affiliateReferredTimeStamp value from cookie", module);
            }
          }
        }

        // find any that start with TKCDB_ for billable tracking code cookies with isBillable=Y
        // also and for each TKCDT_ cookie that doesn't have a corresponding billable code add it to
        // the list with isBillable=N
        // This cookie value keeps trackingCodeId
        if (cookieName.startsWith("TKCDB_")) {
          isBillable = "Y";
          trackingCodeId = cookies[i].getValue();
        } else if (cookieName.startsWith("TKCDT_")) {
          isBillable = "N";
          trackingCodeId = cookies[i].getValue();
        }
      }
    }
    GenericValue trackingCode = null;
    try {
      trackingCode =
          delegator.findByPrimaryKeyCache(
              "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
    } catch (GenericEntityException e) {
      Debug.logError(
          e,
          "Error looking up TrackingCode with trackingCodeId ["
              + trackingCodeId
              + "], ignoring this trackingCodeId",
          module);
    }

    if (trackingCode != null) {
      // check effective dates
      if (trackingCode.get("fromDate") != null
          && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
        if (Debug.infoOn())
          Debug.logInfo(
              "The TrackingCode with ID ["
                  + trackingCodeId
                  + "] has not yet gone into effect, ignoring this trackingCodeId",
              module);
      }
      if (trackingCode.get("thruDate") != null
          && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
        if (Debug.infoOn())
          Debug.logInfo(
              "The TrackingCode with ID ["
                  + trackingCodeId
                  + "] has expired, ignoring this trackingCodeId",
              module);
      }
      GenericValue trackingCodeOrder =
          delegator.makeValue(
              "TrackingCodeOrder",
              UtilMisc.toMap(
                  "trackingCodeTypeId",
                  trackingCode.get("trackingCodeTypeId"),
                  "trackingCodeId",
                  trackingCodeId,
                  "isBillable",
                  isBillable,
                  "siteId",
                  siteId,
                  "hasExported",
                  "N",
                  "affiliateReferredTimeStamp",
                  affiliateReferredTimeStamp));

      Debug.logInfo(" trackingCodeOrder is " + trackingCodeOrder, module);
      trackingCodeOrders.add(trackingCodeOrder);
    } else {
      // Only log an error if there was a trackingCodeId to begin with
      if (trackingCodeId != null) {
        Debug.logError(
            "TrackingCode not found for trackingCodeId ["
                + trackingCodeId
                + "], ignoring this trackingCodeId.",
            module);
      }
    }

    return trackingCodeOrders;
  }
  public static String checkAccessTrackingCode(
      HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp();

    String trackingCodeId = request.getParameter("autoTrackingCode");
    if (UtilValidate.isEmpty(trackingCodeId)) trackingCodeId = request.getParameter("atc");
    if (UtilValidate.isEmpty(trackingCodeId)) {
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if ("TKCDT_ACCESS".equals(cookie.getName())) {
            trackingCodeId = cookie.getValue();
          }
        }
      }
    }

    if (UtilValidate.isNotEmpty(trackingCodeId)) {
      // find the tracking code object
      GenericValue trackingCode = null;
      try {
        trackingCode =
            delegator.findByPrimaryKeyCache(
                "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
      } catch (GenericEntityException e) {
        Debug.logError(
            e,
            "Error looking up TrackingCode with trackingCodeId ["
                + trackingCodeId
                + "], ignoring this trackingCodeId",
            module);
      }
      if (trackingCode != null) {
        // verify the tracking code type
        if ("ACCESS".equals(trackingCode.getString("trackingCodeTypeId"))) {
          // verify the effective date
          if (trackingCode.get("fromDate") != null
              && nowStamp.after(trackingCode.getTimestamp("fromDate"))) {
            if (trackingCode.get("thruDate") != null
                && nowStamp.before(trackingCode.getTimestamp("thruDate"))) {
              // tracking code is valid
              return "success";
            } else {
              if (Debug.infoOn())
                Debug.logInfo(
                    "The TrackingCode with ID ["
                        + trackingCodeId
                        + "] has expired, ignoring this trackingCodeId",
                    module);
              request.setAttribute(
                  "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "], is not valid.");
            }
          } else {
            if (Debug.infoOn())
              Debug.logInfo(
                  "The TrackingCode with ID ["
                      + trackingCodeId
                      + "] has not yet gone into effect, ignoring this trackingCodeId",
                  module);
            request.setAttribute(
                "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "], is not valid.");
          }
        } else {
          Debug.logWarning(
              "Tracking code found ["
                  + trackingCodeId
                  + "] but was not of the type ACCESS; access denied",
              module);
          request.setAttribute(
              "_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "] not found.");
        }
      } else {
        request.setAttribute("_ERROR_MESSAGE_", "Access code [" + trackingCodeId + "] not found.");
      }
    }

    // no tracking code or tracking code invalid; redirect to the access page (i.e. request named
    // 'protect')
    return ":_protect_:";
  }
  /**
   * If attaching TrackingCode Cookies to the visit is desired this event should be added to the
   * list of events that run on the first hit in a visit.
   */
  public static String checkTrackingCodeCookies(
      HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp();
    GenericValue visit = VisitHandler.getVisit(request.getSession());
    if (visit == null) {
      Debug.logWarning(
          "Could not get visit, not checking trackingCode cookies to associate with visit", module);
    } else {
      // loop through cookies and look for ones with a name that starts with TKCDT_ for trackable
      // cookies
      Cookie[] cookies = request.getCookies();

      if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().startsWith("TKCDT_")) {
            String trackingCodeId = cookies[i].getValue();
            GenericValue trackingCode;
            try {
              trackingCode =
                  delegator.findByPrimaryKeyCache(
                      "TrackingCode", UtilMisc.toMap("trackingCodeId", trackingCodeId));
            } catch (GenericEntityException e) {
              Debug.logError(
                  e,
                  "Error looking up TrackingCode with trackingCodeId ["
                      + trackingCodeId
                      + "], ignoring this trackingCodeId",
                  module);
              continue;
            }

            if (trackingCode == null) {
              Debug.logError(
                  "TrackingCode not found for trackingCodeId ["
                      + trackingCodeId
                      + "], ignoring this trackingCodeId.",
                  module);
              // this return value will be ignored, but we'll designate this as an error anyway
              continue;
            }

            // check effective dates
            if (trackingCode.get("fromDate") != null
                && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
              if (Debug.infoOn())
                Debug.logInfo(
                    "The TrackingCode with ID ["
                        + trackingCodeId
                        + "] has not yet gone into effect, ignoring this trackingCodeId",
                    module);
              continue;
            }
            if (trackingCode.get("thruDate") != null
                && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
              if (Debug.infoOn())
                Debug.logInfo(
                    "The TrackingCode with ID ["
                        + trackingCodeId
                        + "] has expired, ignoring this trackingCodeId",
                    module);
              continue;
            }

            // for each trackingCodeId found in this way attach to the visit with the TKCDSRC_COOKIE
            // sourceEnumId
            GenericValue trackingCodeVisit =
                delegator.makeValue(
                    "TrackingCodeVisit",
                    UtilMisc.toMap(
                        "trackingCodeId",
                        trackingCodeId,
                        "visitId",
                        visit.get("visitId"),
                        "fromDate",
                        nowStamp,
                        "sourceEnumId",
                        "TKCDSRC_COOKIE"));
            try {
              // not doing this inside a transaction, want each one possible to go in
              trackingCodeVisit.create();
            } catch (GenericEntityException e) {
              Debug.logError(e, "Error while saving TrackingCodeVisit", module);
              // don't return error, want to get as many as possible: return "error";
            }
          }
        }
      }
    }

    return "success";
  }
  private static String processTrackingCode(
      GenericValue trackingCode, HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String trackingCodeId = trackingCode.getString("trackingCodeId");

    // check effective dates
    java.sql.Timestamp nowStamp = UtilDateTime.nowTimestamp();
    if (trackingCode.get("fromDate") != null
        && nowStamp.before(trackingCode.getTimestamp("fromDate"))) {
      if (Debug.infoOn())
        Debug.logInfo(
            "The TrackingCode with ID ["
                + trackingCodeId
                + "] has not yet gone into effect, ignoring this trackingCodeId",
            module);
      return "success";
    }
    if (trackingCode.get("thruDate") != null
        && nowStamp.after(trackingCode.getTimestamp("thruDate"))) {
      if (Debug.infoOn())
        Debug.logInfo(
            "The TrackingCode with ID ["
                + trackingCodeId
                + "] has expired, ignoring this trackingCodeId",
            module);
      return "success";
    }

    // persist that info by associating with the current visit
    GenericValue visit = VisitHandler.getVisit(request.getSession());
    if (visit == null) {
      Debug.logWarning(
          "Could not get visit, not associating trackingCode [" + trackingCodeId + "] with visit",
          module);
    } else {
      GenericValue trackingCodeVisit =
          delegator.makeValue(
              "TrackingCodeVisit",
              UtilMisc.toMap(
                  "trackingCodeId",
                  trackingCodeId,
                  "visitId",
                  visit.get("visitId"),
                  "fromDate",
                  UtilDateTime.nowTimestamp(),
                  "sourceEnumId",
                  "TKCDSRC_URL_PARAM"));
      try {
        trackingCodeVisit.create();
      } catch (GenericEntityException e) {
        Debug.logError(e, "Error while saving TrackingCodeVisit", module);
      }
    }

    // write trackingCode cookies with the value set to the trackingCodeId
    // NOTE: just write these cookies and if others exist from other tracking codes they will be
    // overwritten, ie only keep the newest

    // load the properties from the website entity
    String cookieDomain = null;

    String webSiteId = WebSiteWorker.getWebSiteId(request);
    if (webSiteId != null) {
      try {
        GenericValue webSite =
            delegator.findByPrimaryKeyCache("WebSite", UtilMisc.toMap("webSiteId", webSiteId));
        if (webSite != null) {
          cookieDomain = webSite.getString("cookieDomain");
        }
      } catch (GenericEntityException e) {
        Debug.logWarning(
            e, "Problems with WebSite entity; using global default cookie domain", module);
      }
    }

    if (cookieDomain == null) {
      cookieDomain = UtilProperties.getPropertyValue("url", "cookie.domain", "");
    }

    // if trackingCode.trackableLifetime not null and is > 0 write a trackable cookie with name in
    // the form: TKCDT_{trackingCode.trackingCodeTypeId} and timeout will be
    // trackingCode.trackableLifetime
    Long trackableLifetime = trackingCode.getLong("trackableLifetime");
    if (trackableLifetime != null
        && (trackableLifetime.longValue() > 0 || trackableLifetime.longValue() == -1)) {
      Cookie trackableCookie =
          new Cookie(
              "TKCDT_" + trackingCode.getString("trackingCodeTypeId"),
              trackingCode.getString("trackingCodeId"));
      if (trackableLifetime.longValue() > 0)
        trackableCookie.setMaxAge(trackableLifetime.intValue());
      trackableCookie.setPath("/");
      if (cookieDomain.length() > 0) trackableCookie.setDomain(cookieDomain);
      response.addCookie(trackableCookie);
    }

    // if trackingCode.billableLifetime not null and is > 0 write a billable cookie with name in the
    // form: TKCDB_{trackingCode.trackingCodeTypeId} and timeout will be
    // trackingCode.billableLifetime
    Long billableLifetime = trackingCode.getLong("billableLifetime");
    if (billableLifetime != null
        && (billableLifetime.longValue() > 0 || billableLifetime.longValue() == -1)) {
      Cookie billableCookie =
          new Cookie(
              "TKCDB_" + trackingCode.getString("trackingCodeTypeId"),
              trackingCode.getString("trackingCodeId"));
      if (billableLifetime.longValue() > 0) billableCookie.setMaxAge(billableLifetime.intValue());
      billableCookie.setPath("/");
      if (cookieDomain.length() > 0) billableCookie.setDomain(cookieDomain);
      response.addCookie(billableCookie);
    }

    // if site id exist in cookies then it is not required to create it, if exist with different
    // site then create it
    int siteIdCookieAge = (60 * 60 * 24 * 365); // should this be configurable?
    String siteId = request.getParameter("siteId");
    if (UtilValidate.isNotEmpty(siteId)) {
      String visitorSiteIdCookieName = "Ofbiz.TKCD.SiteId";
      String visitorSiteId = null;
      // first try to get the current ID from the visitor cookie
      javax.servlet.http.Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
          if (cookies[i].getName().equals(visitorSiteIdCookieName)) {
            visitorSiteId = cookies[i].getValue();
            break;
          }
        }
      }

      if (visitorSiteId == null || (visitorSiteId != null && !visitorSiteId.equals(siteId))) {
        // if trackingCode.siteId is  not null  write a trackable cookie with name in the form:
        // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365
        Cookie siteIdCookie = new Cookie("Ofbiz.TKCD.SiteId", siteId);
        siteIdCookie.setMaxAge(siteIdCookieAge);
        siteIdCookie.setPath("/");
        if (cookieDomain.length() > 0) siteIdCookie.setDomain(cookieDomain);
        response.addCookie(siteIdCookie);
        // if trackingCode.siteId is  not null  write a trackable cookie with name in the form:
        // Ofbiz.TKCSiteId and timeout will be 60 * 60 * 24 * 365
        Cookie updatedTimeStampCookie =
            new Cookie("Ofbiz.TKCD.UpdatedTimeStamp", UtilDateTime.nowTimestamp().toString());
        updatedTimeStampCookie.setMaxAge(siteIdCookieAge);
        updatedTimeStampCookie.setPath("/");
        if (cookieDomain.length() > 0) updatedTimeStampCookie.setDomain(cookieDomain);
        response.addCookie(updatedTimeStampCookie);
      }
    }

    // if we have overridden logo, css and/or catalogId set some session attributes
    HttpSession session = request.getSession();
    String overrideLogo = trackingCode.getString("overrideLogo");
    if (overrideLogo != null) session.setAttribute("overrideLogo", overrideLogo);
    String overrideCss = trackingCode.getString("overrideCss");
    if (overrideCss != null) session.setAttribute("overrideCss", overrideCss);
    String prodCatalogId = trackingCode.getString("prodCatalogId");
    if (UtilValidate.isNotEmpty(prodCatalogId)) {
      session.setAttribute("CURRENT_CATALOG_ID", prodCatalogId);
      CategoryWorker.setTrail(request, FastList.<String>newInstance());
    }

    // if forward/redirect is needed, do a response.sendRedirect and return null to tell the control
    // servlet to not do any other requests/views
    String redirectUrl = trackingCode.getString("redirectUrl");
    if (UtilValidate.isNotEmpty(redirectUrl)) {
      try {
        response.sendRedirect(redirectUrl);
      } catch (java.io.IOException e) {
        Debug.logError(
            e, "Could not redirect as requested in the trackingCode to: " + redirectUrl, module);
      }
      return null;
    }

    return "success";
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    Delegator delegator =
        (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator");

    // Get ServletContext
    ServletContext servletContext = config.getServletContext();

    ContextFilter.setCharacterEncoding(request);

    // Set request attribute and session
    UrlServletHelper.setRequestAttributes(request, delegator, servletContext);

    // set initial parameters
    String initDefaultLocalesString = config.getInitParameter("defaultLocaleString");
    String initRedirectUrl = config.getInitParameter("redirectUrl");
    defaultLocaleString =
        UtilValidate.isNotEmpty(initDefaultLocalesString) ? initDefaultLocalesString : "";
    redirectUrl = UtilValidate.isNotEmpty(initRedirectUrl) ? initRedirectUrl : "";

    String pathInfo = httpRequest.getServletPath();
    if (UtilValidate.isNotEmpty(pathInfo)) {
      List<String> pathElements = StringUtil.split(pathInfo, "/");
      String alternativeUrl = pathElements.get(0);

      String productId = null;
      String productCategoryId = null;
      String urlContentId = null;
      try {
        // look for productId
        if (alternativeUrl.endsWith("-p")) {
          List<EntityCondition> productContentConds = FastList.newInstance();
          productContentConds.add(
              EntityCondition.makeCondition("productContentTypeId", "ALTERNATIVE_URL"));
          productContentConds.add(EntityUtil.getFilterByDateExpr());
          List<GenericValue> productContentInfos =
              EntityQuery.use(delegator)
                  .from("ProductContentAndInfo")
                  .where(productContentConds)
                  .orderBy("-fromDate")
                  .cache(true)
                  .queryList();
          if (UtilValidate.isNotEmpty(productContentInfos)) {
            for (GenericValue productContentInfo : productContentInfos) {
              String contentId = (String) productContentInfo.get("contentId");
              List<GenericValue> ContentAssocDataResourceViewTos =
                  EntityQuery.use(delegator)
                      .from("ContentAssocDataResourceViewTo")
                      .where(
                          "contentIdStart",
                          contentId,
                          "caContentAssocTypeId",
                          "ALTERNATE_LOCALE",
                          "drDataResourceTypeId",
                          "ELECTRONIC_TEXT")
                      .cache(true)
                      .queryList();
              if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) {
                for (GenericValue ContentAssocDataResourceViewTo :
                    ContentAssocDataResourceViewTos) {
                  GenericValue ElectronicText =
                      ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true);
                  if (UtilValidate.isNotEmpty(ElectronicText)) {
                    String textData = (String) ElectronicText.get("textData");
                    textData = UrlServletHelper.invalidCharacter(textData);
                    if (alternativeUrl.matches(textData + ".+$")) {
                      String productIdStr = null;
                      productIdStr = alternativeUrl.replace(textData + "-", "");
                      productIdStr = productIdStr.replace("-p", "");
                      String checkProductId = (String) productContentInfo.get("productId");
                      if (productIdStr.equalsIgnoreCase(checkProductId)) {
                        productId = checkProductId;
                        break;
                      }
                    }
                  }
                }
              }
              if (UtilValidate.isEmpty(productId)) {
                List<GenericValue> contentDataResourceViews =
                    EntityQuery.use(delegator)
                        .from("ContentDataResourceView")
                        .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT")
                        .cache(true)
                        .queryList();
                for (GenericValue contentDataResourceView : contentDataResourceViews) {
                  GenericValue ElectronicText =
                      contentDataResourceView.getRelatedOne("ElectronicText", true);
                  if (UtilValidate.isNotEmpty(ElectronicText)) {
                    String textData = (String) ElectronicText.get("textData");
                    if (UtilValidate.isNotEmpty(textData)) {
                      textData = UrlServletHelper.invalidCharacter(textData);
                      if (alternativeUrl.matches(textData + ".+$")) {
                        String productIdStr = null;
                        productIdStr = alternativeUrl.replace(textData + "-", "");
                        productIdStr = productIdStr.replace("-p", "");
                        String checkProductId = (String) productContentInfo.get("productId");
                        if (productIdStr.equalsIgnoreCase(checkProductId)) {
                          productId = checkProductId;
                          break;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        // look for productCategoryId
        if (alternativeUrl.endsWith("-c")) {
          List<EntityCondition> productCategoryContentConds = FastList.newInstance();
          productCategoryContentConds.add(
              EntityCondition.makeCondition("prodCatContentTypeId", "ALTERNATIVE_URL"));
          productCategoryContentConds.add(EntityUtil.getFilterByDateExpr());
          List<GenericValue> productCategoryContentInfos =
              EntityQuery.use(delegator)
                  .from("ProductCategoryContentAndInfo")
                  .where(productCategoryContentConds)
                  .orderBy("-fromDate")
                  .cache(true)
                  .queryList();
          if (UtilValidate.isNotEmpty(productCategoryContentInfos)) {
            for (GenericValue productCategoryContentInfo : productCategoryContentInfos) {
              String contentId = (String) productCategoryContentInfo.get("contentId");
              List<GenericValue> ContentAssocDataResourceViewTos =
                  EntityQuery.use(delegator)
                      .from("ContentAssocDataResourceViewTo")
                      .where(
                          "contentIdStart",
                          contentId,
                          "caContentAssocTypeId",
                          "ALTERNATE_LOCALE",
                          "drDataResourceTypeId",
                          "ELECTRONIC_TEXT")
                      .cache(true)
                      .queryList();
              if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) {
                for (GenericValue ContentAssocDataResourceViewTo :
                    ContentAssocDataResourceViewTos) {
                  GenericValue ElectronicText =
                      ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true);
                  if (UtilValidate.isNotEmpty(ElectronicText)) {
                    String textData = (String) ElectronicText.get("textData");
                    if (UtilValidate.isNotEmpty(textData)) {
                      textData = UrlServletHelper.invalidCharacter(textData);
                      if (alternativeUrl.matches(textData + ".+$")) {
                        String productCategoryStr = null;
                        productCategoryStr = alternativeUrl.replace(textData + "-", "");
                        productCategoryStr = productCategoryStr.replace("-c", "");
                        String checkProductCategoryId =
                            (String) productCategoryContentInfo.get("productCategoryId");
                        if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) {
                          productCategoryId = checkProductCategoryId;
                          break;
                        }
                      }
                    }
                  }
                }
              }
              if (UtilValidate.isEmpty(productCategoryId)) {
                List<GenericValue> contentDataResourceViews =
                    EntityQuery.use(delegator)
                        .from("ContentDataResourceView")
                        .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT")
                        .cache(true)
                        .queryList();
                for (GenericValue contentDataResourceView : contentDataResourceViews) {
                  GenericValue ElectronicText =
                      contentDataResourceView.getRelatedOne("ElectronicText", true);
                  if (UtilValidate.isNotEmpty(ElectronicText)) {
                    String textData = (String) ElectronicText.get("textData");
                    if (UtilValidate.isNotEmpty(textData)) {
                      textData = UrlServletHelper.invalidCharacter(textData);
                      if (alternativeUrl.matches(textData + ".+$")) {
                        String productCategoryStr = null;
                        productCategoryStr = alternativeUrl.replace(textData + "-", "");
                        productCategoryStr = productCategoryStr.replace("-c", "");
                        String checkProductCategoryId =
                            (String) productCategoryContentInfo.get("productCategoryId");
                        if (productCategoryStr.equalsIgnoreCase(checkProductCategoryId)) {
                          productCategoryId = checkProductCategoryId;
                          break;
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

      } catch (GenericEntityException e) {
        Debug.logWarning("Cannot look for product and product category", module);
      }

      // generate forward URL
      StringBuilder urlBuilder = new StringBuilder();
      urlBuilder.append("/" + CONTROL_MOUNT_POINT);

      if (UtilValidate.isNotEmpty(productId)) {
        try {
          List<EntityCondition> conds = FastList.newInstance();
          conds.add(EntityCondition.makeCondition("productId", productId));
          conds.add(EntityUtil.getFilterByDateExpr());
          List<GenericValue> productCategoryMembers =
              EntityQuery.use(delegator)
                  .select("productCategoryId")
                  .from("ProductCategoryMember")
                  .where(conds)
                  .orderBy("-fromDate")
                  .cache(true)
                  .queryList();
          if (UtilValidate.isNotEmpty(productCategoryMembers)) {
            GenericValue productCategoryMember = EntityUtil.getFirst(productCategoryMembers);
            productCategoryId = productCategoryMember.getString("productCategoryId");
          }
        } catch (GenericEntityException e) {
          Debug.logError(e, "Cannot find product category for product: " + productId, module);
        }
        urlBuilder.append("/" + PRODUCT_REQUEST);

      } else {
        urlBuilder.append("/" + CATEGORY_REQUEST);
      }

      // generate trail belong to a top category
      String topCategoryId = CategoryWorker.getCatalogTopCategory(httpRequest, null);
      List<GenericValue> trailCategories =
          CategoryWorker.getRelatedCategoriesRet(
              httpRequest, "trailCategories", topCategoryId, false, false, true);
      List<String> trailCategoryIds =
          EntityUtil.getFieldListFromEntityList(trailCategories, "productCategoryId", true);

      // look for productCategoryId from productId
      if (UtilValidate.isNotEmpty(productId)) {
        try {
          List<EntityCondition> rolllupConds = FastList.newInstance();
          rolllupConds.add(EntityCondition.makeCondition("productId", productId));
          rolllupConds.add(EntityUtil.getFilterByDateExpr());
          List<GenericValue> productCategoryMembers =
              EntityQuery.use(delegator)
                  .from("ProductCategoryMember")
                  .where(rolllupConds)
                  .orderBy("-fromDate")
                  .cache(true)
                  .queryList();
          for (GenericValue productCategoryMember : productCategoryMembers) {
            String trailCategoryId = productCategoryMember.getString("productCategoryId");
            if (trailCategoryIds.contains(trailCategoryId)) {
              productCategoryId = trailCategoryId;
              break;
            }
          }
        } catch (GenericEntityException e) {
          Debug.logError(e, "Cannot generate trail from product category", module);
        }
      }

      // generate trail elements from productCategoryId
      if (UtilValidate.isNotEmpty(productCategoryId)) {
        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 =
                EntityQuery.use(delegator)
                    .from("ProductCategoryRollup")
                    .where(rolllupConds)
                    .orderBy("-fromDate")
                    .cache(true)
                    .queryList();
            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 (trailCategoryIds.contains(trailCategoryId)) {
                  trailElements.add(trailCategoryId);
                  break;
                }
              }
            } else {
              parentProductCategoryId = null;
            }
          } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot generate trail from product category", module);
          }
        }
        Collections.reverse(trailElements);

        List<String> trail = CategoryWorker.getTrail(httpRequest);
        if (trail == null) {
          trail = FastList.newInstance();
        }

        // adjust trail
        String previousCategoryId = null;
        if (trail.size() > 0) {
          previousCategoryId = trail.get(trail.size() - 1);
        }
        trail = CategoryWorker.adjustTrail(trail, productCategoryId, previousCategoryId);

        if (trailElements.size() == 1) {
          CategoryWorker.setTrail(request, trailElements.get(0), null);
        } else if (trailElements.size() == 2) {
          CategoryWorker.setTrail(request, trailElements.get(1), trailElements.get(0));
        } else if (trailElements.size() > 2) {
          if (trail.contains(trailElements.get(0))) {
            // first category is in the trail, so remove it everything after that and fill it in
            // with the list from the pathInfo
            int firstElementIndex = trail.indexOf(trailElements.get(0));
            while (trail.size() > firstElementIndex) {
              trail.remove(firstElementIndex);
            }
            trail.addAll(trailElements);
          } else {
            // first category is NOT in the trail, so clear out the trail and use the trailElements
            // list
            trail.clear();
            trail.addAll(trailElements);
          }
          CategoryWorker.setTrail(request, trail);
        }

        request.setAttribute("productCategoryId", productCategoryId);

        if (productId != null) {
          request.setAttribute("product_id", productId);
          request.setAttribute("productId", productId);
        }
      }

      // Set view query parameters
      UrlServletHelper.setViewQueryParameters(request, urlBuilder);
      if (UtilValidate.isNotEmpty(productId)
          || UtilValidate.isNotEmpty(productCategoryId)
          || UtilValidate.isNotEmpty(urlContentId)) {
        Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module);
        ContextFilter.setAttributesFromRequestBody(request);
        RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString());
        dispatch.forward(request, response);
        return;
      }

      // Check path alias
      UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo);
    }

    // we're done checking; continue on
    chain.doFilter(request, response);
  }
  // base payment integration services
  public static Map<String, Object> finAccountPreAuth(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    String finAccountCode = (String) context.get("finAccountCode");
    String finAccountPin = (String) context.get("finAccountPin");
    String finAccountId = (String) context.get("finAccountId");
    String orderId = (String) context.get("orderId");
    BigDecimal amount = (BigDecimal) context.get("processAmount");

    // check for an existing auth trans and cancel it
    GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref);
    if (authTrans != null) {
      Map<String, Object> input =
          UtilMisc.toMap("userLogin", userLogin, "finAccountAuthId", authTrans.get("referenceNum"));
      try {
        dispatcher.runSync("expireFinAccountAuth", input);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    if (finAccountId == null && paymentPref != null) {
      finAccountId = paymentPref.getString("finAccountId");
    }

    // obtain the order information
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);

    // NOTE DEJ20070808: this means that we want store related settings for where the item is being
    // purchased,
    // NOT where the account was setup; should this be changed to use settings from the store where
    // the account was setup?
    String productStoreId = orh.getProductStoreId();

    // TODO, NOTE DEJ20070808: why is this setup this way anyway? for the allowAuthToNegative
    // wouldn't that be better setup
    // on the FinAccount and not on the ProductStoreFinActSetting? maybe an override on the
    // FinAccount would be good...

    // get the financial account
    GenericValue finAccount;
    if (finAccountId != null) {
      try {
        finAccount =
            EntityQuery.use(delegator)
                .from("FinAccount")
                .where("finAccountId", finAccountId)
                .queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    } else {
      if (finAccountCode != null) {
        try {
          finAccount = FinAccountHelper.getFinAccountFromCode(finAccountCode, delegator);
        } catch (GenericEntityException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(
              UtilProperties.getMessage(
                  resourceError, "AccountingFinAccountCannotLocateItFromAccountCode", locale));
        }
      } else {
        return ServiceUtil.returnError(
            UtilProperties.getMessage(
                resourceError, "AccountingFinAccountIdAndFinAccountCodeAreNull", locale));
      }
    }
    if (finAccount == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resourceError, "AccountingFinAccountIdInvalid", locale));
    }

    String finAccountTypeId = finAccount.getString("finAccountTypeId");
    finAccountId = finAccount.getString("finAccountId");
    String statusId = finAccount.getString("statusId");

    try {
      // fin the store requires a pin number; validate the PIN with the code
      Map<String, Object> findProductStoreFinActSettingMap =
          UtilMisc.<String, Object>toMap(
              "productStoreId", productStoreId, "finAccountTypeId", finAccountTypeId);
      GenericValue finAccountSettings =
          EntityQuery.use(delegator)
              .from("ProductStoreFinActSetting")
              .where(findProductStoreFinActSettingMap)
              .cache()
              .queryOne();

      if (finAccountSettings == null) {
        Debug.logWarning(
            "In finAccountPreAuth could not find ProductStoreFinActSetting record, values searched by: "
                + findProductStoreFinActSettingMap,
            module);
      }
      if (Debug.verboseOn())
        Debug.logVerbose("In finAccountPreAuth finAccountSettings=" + finAccountSettings, module);

      BigDecimal minBalance = FinAccountHelper.ZERO;
      String allowAuthToNegative = "N";

      if (finAccountSettings != null) {
        allowAuthToNegative = finAccountSettings.getString("allowAuthToNegative");
        minBalance = finAccountSettings.getBigDecimal("minBalance");
        if (minBalance == null) {
          minBalance = FinAccountHelper.ZERO;
        }

        // validate the PIN if the store requires it
        if ("Y".equals(finAccountSettings.getString("requirePinCode"))) {
          if (!FinAccountHelper.validatePin(delegator, finAccountCode, finAccountPin)) {
            Map<String, Object> result = ServiceUtil.returnSuccess();
            result.put(
                "authMessage",
                UtilProperties.getMessage(
                    resourceError, "AccountingFinAccountPinCodeCombinatorNotFound", locale));
            result.put("authResult", Boolean.FALSE);
            result.put("processAmount", amount);
            result.put("authFlag", "0");
            result.put("authCode", "A");
            result.put("authRefNum", "0");
            Debug.logWarning("Unable to auth FinAccount: " + result, module);
            return result;
          }
        }
      }

      // check for expiration date
      if ((finAccount.getTimestamp("thruDate") != null)
          && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put(
            "authMessage",
            UtilProperties.getMessage(
                resourceError,
                "AccountingFinAccountExpired",
                UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")),
                locale));
        result.put("authResult", Boolean.FALSE);
        result.put("processAmount", amount);
        result.put("authFlag", "0");
        result.put("authCode", "A");
        result.put("authRefNum", "0");
        Debug.logWarning("Unable to auth FinAccount: " + result, module);
        return result;
      }

      // check for account being in bad standing somehow
      if ("FNACT_NEGPENDREPL".equals(statusId)
          || "FNACT_MANFROZEN".equals(statusId)
          || "FNACT_CANCELLED".equals(statusId)) {
        // refresh the finaccount
        finAccount.refresh();
        statusId = finAccount.getString("statusId");

        if ("FNACT_NEGPENDREPL".equals(statusId)
            || "FNACT_MANFROZEN".equals(statusId)
            || "FNACT_CANCELLED".equals(statusId)) {
          Map<String, Object> result = ServiceUtil.returnSuccess();
          if ("FNACT_NEGPENDREPL".equals(statusId)) {
            result.put(
                "authMessage",
                UtilProperties.getMessage(resourceError, "AccountingFinAccountNegative", locale));
          } else if ("FNACT_MANFROZEN".equals(statusId)) {
            result.put(
                "authMessage",
                UtilProperties.getMessage(resourceError, "AccountingFinAccountFrozen", locale));
          } else if ("FNACT_CANCELLED".equals(statusId)) {
            result.put(
                "authMessage",
                UtilProperties.getMessage(resourceError, "AccountingFinAccountCancelled", locale));
          }
          result.put("authResult", Boolean.FALSE);
          result.put("processAmount", amount);
          result.put("authFlag", "0");
          result.put("authCode", "A");
          result.put("authRefNum", "0");
          Debug.logWarning("Unable to auth FinAccount: " + result, module);
          return result;
        }
      }

      // check the amount to authorize against the available balance of fin account, which includes
      // active authorizations as well as transactions
      BigDecimal availableBalance = finAccount.getBigDecimal("availableBalance");
      if (availableBalance == null) {
        availableBalance = FinAccountHelper.ZERO;
      } else {
        BigDecimal availableBalanceOriginal = availableBalance;
        availableBalance =
            availableBalance.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);
        if (availableBalance.compareTo(availableBalanceOriginal) != 0) {
          Debug.logWarning(
              "In finAccountPreAuth for finAccountId ["
                  + finAccountId
                  + "] availableBalance ["
                  + availableBalanceOriginal
                  + "] was different after rounding ["
                  + availableBalance
                  + "]; it should never have made it into the database this way, so check whatever put it there.",
              module);
        }
      }

      Map<String, Object> result = ServiceUtil.returnSuccess();
      String authMessage = null;
      Boolean processResult;
      String refNum;

      // make sure to round and scale it to the same as availableBalance
      amount = amount.setScale(FinAccountHelper.decimals, FinAccountHelper.rounding);

      Debug.logInfo(
          "Allow auth to negative: "
              + allowAuthToNegative
              + " :: available: "
              + availableBalance
              + " comp: "
              + minBalance
              + " = "
              + availableBalance.compareTo(minBalance)
              + " :: req: "
              + amount,
          module);
      // check the available balance to see if we can auth this tx
      if (("Y".equals(allowAuthToNegative) && availableBalance.compareTo(minBalance) > -1)
          || (availableBalance.compareTo(amount) > -1)) {
        Timestamp thruDate;

        if (finAccountSettings != null && finAccountSettings.getLong("authValidDays") != null) {
          thruDate =
              UtilDateTime.getDayEnd(
                  UtilDateTime.nowTimestamp(), finAccountSettings.getLong("authValidDays"));
        } else {
          thruDate =
              UtilDateTime.getDayEnd(
                  UtilDateTime.nowTimestamp(), Long.valueOf(30)); // default 30 days for an auth
        }

        Map<String, Object> tmpResult =
            dispatcher.runSync(
                "createFinAccountAuth",
                UtilMisc.<String, Object>toMap(
                    "finAccountId",
                    finAccountId,
                    "amount",
                    amount,
                    "thruDate",
                    thruDate,
                    "userLogin",
                    userLogin));

        if (ServiceUtil.isError(tmpResult)) {
          return tmpResult;
        }
        refNum = (String) tmpResult.get("finAccountAuthId");
        processResult = Boolean.TRUE;

        // refresh the account
        finAccount.refresh();
      } else {
        Debug.logWarning(
            "Attempted to authorize ["
                + amount
                + "] against a balance of only ["
                + availableBalance
                + "] for finAccountId ["
                + finAccountId
                + "]",
            module);
        refNum = "0"; // a refNum is always required from authorization
        authMessage = "Insufficient funds";
        processResult = Boolean.FALSE;
      }

      result.put("processAmount", amount);
      result.put("authMessage", authMessage);
      result.put("authResult", processResult);
      result.put("processAmount", amount);
      result.put("authFlag", "1");
      result.put("authCode", "A");
      result.put("authRefNum", refNum);
      Debug.logInfo("FinAccont Auth: " + result, module);

      return result;
    } catch (GenericEntityException ex) {
      Debug.logError(ex, "Cannot authorize financial account", module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountCannotBeAuthorized",
              UtilMisc.toMap("errorString", ex.getMessage()),
              locale));
    } catch (GenericServiceException ex) {
      Debug.logError(ex, "Cannot authorize financial account", module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountCannotBeAuthorized",
              UtilMisc.toMap("errorString", ex.getMessage()),
              locale));
    }
  }
Exemple #30
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;
  }