Пример #1
0
  /**
   * Generic service to find party by id. By default return the party find by partyId but you can
   * pass searchPartyFirst at false if you want search in partyIdentification before or pass
   * searchAllId at true to find apartyuct with this id (party.partyId and
   * partyIdentification.idValue)
   *
   * @param delegator
   * @param idToFind
   * @param partyIdentificationTypeId
   * @param searchPartyFirst
   * @param searchAllId
   * @return
   * @throws GenericEntityException
   */
  public static List<GenericValue> findPartiesById(
      Delegator delegator,
      String idToFind,
      String partyIdentificationTypeId,
      boolean searchPartyFirst,
      boolean searchAllId)
      throws GenericEntityException {

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

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

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

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

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

    if (UtilValidate.isNotEmpty(party)) {
      if (UtilValidate.isNotEmpty(partiesFound)) partiesFound.add(party);
      else partiesFound = UtilMisc.toList(party);
    }
    if (Debug.verboseOn())
      Debug.logVerbose(
          "Analyze partyIdentification: found party.partyId = "
              + party
              + ", and list : "
              + partiesFound,
          module);
    return partiesFound;
  }
  public static boolean isProductInCategory(
      Delegator delegator, String productId, String productCategoryId)
      throws GenericEntityException {
    if (productCategoryId == null) return false;
    if (UtilValidate.isEmpty(productId)) return false;

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

      return false;
    } else {
      return true;
    }
  }
Пример #3
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;
  }
Пример #4
0
 /**
  * Gets the cached value object for this merchant's keys
  *
  * @return Cached GenericValue object
  */
 public GenericValue getGenericValue() {
   GenericValue value = null;
   try {
     value =
         delegator.findByPrimaryKeyCache("ValueLinkKey", UtilMisc.toMap("merchantId", merchantId));
   } catch (GenericEntityException e) {
     Debug.logError(e, module);
   }
   if (value == null) {
     throw new RuntimeException("No ValueLinkKey record found for Merchant ID : " + merchantId);
   }
   return value;
 }
Пример #5
0
  /**
   * If TrackingCode monitoring is desired this event should be added to the list of events that run
   * on every request. This event looks for the parameter <code>autoTrackingCode</code> or a
   * shortened version: <code>atc</code>.
   */
  public static String checkTrackingCodeUrlParam(
      HttpServletRequest request, HttpServletResponse response) {
    String trackingCodeId = request.getParameter("autoTrackingCode");
    if (UtilValidate.isEmpty(trackingCodeId)) trackingCodeId = request.getParameter("atc");

    if (UtilValidate.isNotEmpty(trackingCodeId)) {
      // tracking code is specified on the request, get the TrackingCode value and handle
      // accordingly
      Delegator delegator = (Delegator) request.getAttribute("delegator");
      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);
        return "error";
      }

      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
        return "error";
      }

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

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

    // put everything together
    StringBuffer buff = new StringBuffer("<a class=\"linktext\" href=\"");
    buff.append(uri).append("\">");
    buff.append(name).append("</a>");
    return buff.toString();
  }
Пример #7
0
  /**
   * 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;
  }
Пример #8
0
  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_:";
  }
Пример #9
0
  /**
   * 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";
  }
Пример #10
0
  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";
  }
Пример #11
0
  /**
   * If TrackingCode monitoring is desired this event should be added to the list of events that run
   * on every request. This event looks for the parameter <code>ptc</code> and handles the value as
   * a Partner Managed Tracking Code.
   *
   * <p>If the specified trackingCodeId exists then it is used as is, otherwise a new one is created
   * with the ptc value as the trackingCodeId. The values for the fields of the new TrackingCode can
   * come from one of two places: if a <code>dtc</code> parameter is included the value will be used
   * to lookup a TrackingCode with default values, otherwise the default trackingCodeId will be
   * looked up in the <code>partner.trackingCodeId.default</code> in the <code>general.properties
   * </code> file. If that is still not found just use an empty TrackingCode.
   */
  public static String checkPartnerTrackingCodeUrlParam(
      HttpServletRequest request, HttpServletResponse response) {
    String trackingCodeId = request.getParameter("ptc");

    if (UtilValidate.isNotEmpty(trackingCodeId)) {
      // partner managed tracking code is specified on the request
      Delegator delegator = (Delegator) request.getAttribute("delegator");
      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);
        return "error";
      }

      if (trackingCode == null) {
        // create new TrackingCode with default values from a "dtc" parameter or from a properties
        // file

        String dtc = request.getParameter("dtc");
        if (UtilValidate.isEmpty(dtc)) {
          dtc = UtilProperties.getPropertyValue("general", "partner.trackingCodeId.default");
        }
        if (UtilValidate.isNotEmpty(dtc)) {
          GenericValue defaultTrackingCode = null;
          try {
            defaultTrackingCode =
                delegator.findByPrimaryKeyCache(
                    "TrackingCode", UtilMisc.toMap("trackingCodeId", dtc));
          } catch (GenericEntityException e) {
            Debug.logError(
                e,
                "Error looking up Default values TrackingCode with trackingCodeId ["
                    + dtc
                    + "], not using the dtc value for new TrackingCode defaults",
                module);
          }

          if (defaultTrackingCode != null) {
            defaultTrackingCode.set("trackingCodeId", trackingCodeId);
            defaultTrackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
            // null out userLogin fields, no use tracking to customer, or is there?; set dates to
            // current
            defaultTrackingCode.set("createdDate", UtilDateTime.nowTimestamp());
            defaultTrackingCode.set("createdByUserLogin", null);
            defaultTrackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            defaultTrackingCode.set("lastModifiedByUserLogin", null);

            trackingCode = defaultTrackingCode;
            try {
              trackingCode.create();
            } catch (GenericEntityException e) {
              Debug.logError(
                  e,
                  "Error creating new Partner TrackingCode with trackingCodeId ["
                      + trackingCodeId
                      + "], ignoring this trackingCodeId",
                  module);
              return "error";
            }
          }
        }

        // if trackingCode is still null then the defaultTrackingCode thing didn't work out, use
        // empty TrackingCode
        if (trackingCode == null) {
          trackingCode = delegator.makeValue("TrackingCode");
          trackingCode.set("trackingCodeId", trackingCodeId);
          trackingCode.set("trackingCodeTypeId", "PARTNER_MGD");
          // leave userLogin fields empty, no use tracking to customer, or is there?; set dates to
          // current
          trackingCode.set("createdDate", UtilDateTime.nowTimestamp());
          trackingCode.set("lastModifiedDate", UtilDateTime.nowTimestamp());

          // use nearly unlimited trackable lifetime: 10 billion seconds, 310 years
          trackingCode.set("trackableLifetime", Long.valueOf(10000000000L));
          // use 2592000 seconds as billable lifetime: equals 1 month
          trackingCode.set("billableLifetime", Long.valueOf(2592000));

          trackingCode.set(
              "comments",
              "This TrackingCode has default values because no default TrackingCode could be found.");

          Debug.logWarning(
              "No default TrackingCode record was found, using a TrackingCode with hard coded default values: "
                  + trackingCode,
              module);

          try {
            trackingCode.create();
          } catch (GenericEntityException e) {
            Debug.logError(
                e,
                "Error creating new Partner TrackingCode with trackingCodeId ["
                    + trackingCodeId
                    + "], ignoring this trackingCodeId",
                module);
            return "error";
          }
        }
      }

      return processTrackingCode(trackingCode, request, response);
    } else {
      return "success";
    }
  }
Пример #12
0
  public static Map<String, Object> rateProductTaxCalcForDisplay(
      DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String productStoreId = (String) context.get("productStoreId");
    String billToPartyId = (String) context.get("billToPartyId");
    String productId = (String) context.get("productId");
    BigDecimal quantity = (BigDecimal) context.get("quantity");
    BigDecimal basePrice = (BigDecimal) context.get("basePrice");
    BigDecimal shippingPrice = (BigDecimal) context.get("shippingPrice");
    Locale locale = (Locale) context.get("locale");

    if (quantity == null) quantity = ONE_BASE;
    BigDecimal amount = basePrice.multiply(quantity);

    BigDecimal taxTotal = ZERO_BASE;
    BigDecimal taxPercentage = ZERO_BASE;
    BigDecimal priceWithTax = basePrice;
    if (shippingPrice != null) priceWithTax = priceWithTax.add(shippingPrice);

    try {
      GenericValue product =
          delegator.findByPrimaryKeyCache("Product", UtilMisc.toMap("productId", productId));
      GenericValue productStore =
          delegator.findByPrimaryKeyCache(
              "ProductStore", UtilMisc.toMap("productStoreId", productStoreId));
      if (productStore == null) {
        throw new IllegalArgumentException(
            "Could not find ProductStore with ID [" + productStoreId + "] for tax calculation");
      }

      if ("Y".equals(productStore.getString("showPricesWithVatTax"))) {
        Set<GenericValue> taxAuthoritySet = FastSet.newInstance();
        if (productStore.get("vatTaxAuthPartyId") == null) {
          List<GenericValue> taxAuthorityRawList =
              delegator.findList(
                  "TaxAuthority",
                  EntityCondition.makeCondition(
                      "taxAuthGeoId", EntityOperator.EQUALS, productStore.get("vatTaxAuthGeoId")),
                  null,
                  null,
                  null,
                  true);
          taxAuthoritySet.addAll(taxAuthorityRawList);
        } else {
          GenericValue taxAuthority =
              delegator.findByPrimaryKeyCache(
                  "TaxAuthority",
                  UtilMisc.toMap(
                      "taxAuthGeoId",
                      productStore.get("vatTaxAuthGeoId"),
                      "taxAuthPartyId",
                      productStore.get("vatTaxAuthPartyId")));
          taxAuthoritySet.add(taxAuthority);
        }

        if (taxAuthoritySet.size() == 0) {
          throw new IllegalArgumentException(
              "Could not find any Tax Authories for store with ID ["
                  + productStoreId
                  + "] for tax calculation; the store settings may need to be corrected.");
        }

        List<GenericValue> taxAdustmentList =
            getTaxAdjustments(
                delegator,
                product,
                productStore,
                null,
                billToPartyId,
                taxAuthoritySet,
                basePrice,
                quantity,
                amount,
                shippingPrice,
                ZERO_BASE);
        if (taxAdustmentList.size() == 0) {
          // this is something that happens every so often for different products and such, so don't
          // blow up on it...
          Debug.logWarning(
              "Could not find any Tax Authories Rate Rules for store with ID ["
                  + productStoreId
                  + "], productId ["
                  + productId
                  + "], basePrice ["
                  + basePrice
                  + "], amount ["
                  + amount
                  + "], for tax calculation; the store settings may need to be corrected.",
              module);
        }

        // add up amounts from adjustments (amount OR exemptAmount, sourcePercentage)
        for (GenericValue taxAdjustment : taxAdustmentList) {
          if ("SALES_TAX".equals(taxAdjustment.getString("orderAdjustmentTypeId"))) {
            taxPercentage = taxPercentage.add(taxAdjustment.getBigDecimal("sourcePercentage"));
            BigDecimal adjAmount = taxAdjustment.getBigDecimal("amount");
            taxTotal = taxTotal.add(adjAmount);
            priceWithTax =
                priceWithTax.add(
                    adjAmount.divide(quantity, salestaxCalcDecimals, salestaxRounding));
            Debug.logInfo(
                "For productId ["
                    + productId
                    + "] added ["
                    + adjAmount.divide(quantity, salestaxCalcDecimals, salestaxRounding)
                    + "] of tax to price for geoId ["
                    + taxAdjustment.getString("taxAuthGeoId")
                    + "], new price is ["
                    + priceWithTax
                    + "]",
                module);
          }
        }
      }
    } catch (GenericEntityException e) {
      Debug.logError(e, "Data error getting tax settings: " + e.toString(), module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource,
              "AccountingTaxSettingError",
              UtilMisc.toMap("errorString", e.toString()),
              locale));
    }

    // round to 2 decimal places for display/etc
    taxTotal = taxTotal.setScale(salestaxFinalDecimals, salestaxRounding);
    priceWithTax = priceWithTax.setScale(salestaxFinalDecimals, salestaxRounding);

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("taxTotal", taxTotal);
    result.put("taxPercentage", taxPercentage);
    result.put("priceWithTax", priceWithTax);
    return result;
  }