public AssignmentEventAudit(EntityAuditMgr mgr, Delegator delegator) {
   super(mgr, delegator);
   this.newValue = true;
   this.assignmentEventAudit =
       delegator.makeValue(
           "WfAssignmentEventAudit", UtilMisc.toMap("eventAuditId", this.eventAuditId));
 }
예제 #2
0
  public static Map<String, Object> makeALotOfVisits(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    int count = ((Integer) context.get("count")).intValue();

    for (int i = 0; i < count; i++) {
      GenericValue v = delegator.makeValue("Visit");
      String seqId = delegator.getNextSeqId("Visit");

      v.set("visitId", seqId);
      v.set("userCreated", "N");
      v.set("sessionId", "NA-" + seqId);
      v.set("serverIpAddress", "127.0.0.1");
      v.set("serverHostName", "localhost");
      v.set("webappName", "webtools");
      v.set("initialLocale", "en_US");
      v.set("initialRequest", "http://localhost:8080/webtools/control/main");
      v.set("initialReferrer", "http://localhost:8080/webtools/control/main");
      v.set(
          "initialUserAgent",
          "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1");
      v.set("clientIpAddress", "127.0.0.1");
      v.set("clientHostName", "localhost");
      v.set("fromDate", UtilDateTime.nowTimestamp());

      try {
        delegator.create(v);
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }

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

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

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

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

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

    String freqStr = freq[frequency];

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

      value.set("frequency", freqStr);
      value.set("intervalNumber", Long.valueOf(interval));
      value.set("countNumber", Long.valueOf(count));
      if (endTime > 0) {
        value.set("untilDateTime", new java.sql.Timestamp(endTime));
      }
      delegator.createSetNextSeqId(value);
      RecurrenceRule newRule = new RecurrenceRule(value);
      return newRule;
    } catch (GenericEntityException ee) {
      throw new RecurrenceRuleException(ee.getMessage(), ee);
    } catch (RecurrenceRuleException re) {
      throw re;
    }
  }
예제 #5
0
  public static Map<String, Object> updateContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

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

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

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

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorUpdateContactFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
예제 #6
0
 public static Map<String, Object> createCmsCatalog(
     DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
   Map result = ServiceUtil.returnSuccess();
   Delegator delegator = dctx.getDelegator();
   String catalogId = delegator.getNextSeqId("CmsCatalog");
   GenericValue gv = delegator.makeValue("CmsCatalog", UtilMisc.toMap("catalogId", catalogId));
   gv.setNonPKFields(context);
   gv.create();
   result.put("catalogId", catalogId);
   return result;
 }
예제 #7
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;
  }
  public static Map<String, Object> createEPaketConfigStatus(
      Delegator delegator, Map<String, ? extends Object> context, String Action)
      throws GenericEntityException {

    String epaketConfigStatusId = delegator.getNextSeqId("EPaketConfigStatus");
    GenericValue ePaketConfigStatus =
        delegator.makeValue(
            "EPaketConfigStatus", UtilMisc.toMap("epaketConfigStatusId", epaketConfigStatusId));

    ePaketConfigStatus.setNonPKFields(context);
    ePaketConfigStatus.set("action", Action);
    ePaketConfigStatus.create();
    return ServiceUtil.returnSuccess();
  }
예제 #9
0
  /**
   * Generic Test SOAP Service
   *
   * @param dctx 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> testSOAPService(DispatchContext dctx, Map<String, ?> context) {
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> response = ServiceUtil.returnSuccess();

    List<GenericValue> testingNodes = FastList.newInstance();
    for (int i = 0; i < 3; i++) {
      GenericValue testingNode = delegator.makeValue("TestingNode");
      testingNode.put("testingNodeId", "TESTING_NODE" + i);
      testingNode.put("description", "Testing Node " + i);
      testingNode.put("createdStamp", UtilDateTime.nowTimestamp());
      testingNodes.add(testingNode);
    }
    response.put("testingNodes", testingNodes);
    return response;
  }
  /**
   * Creates a PartyRelationshipType
   *
   * @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> createPartyRelationshipType(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = FastMap.newInstance();
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");

    ServiceUtil.getPartyIdCheckSecurity(
        userLogin, security, context, result, "PARTYMGR", "_CREATE");

    if (result.size() > 0) return result;

    GenericValue partyRelationshipType =
        delegator.makeValue(
            "PartyRelationshipType",
            UtilMisc.toMap("partyRelationshipTypeId", context.get("partyRelationshipTypeId")));

    partyRelationshipType.set("parentTypeId", context.get("parentTypeId"), true);
    partyRelationshipType.set("hasTable", context.get("hasTable"), true);
    partyRelationshipType.set("roleTypeIdValidFrom", context.get("roleTypeIdValidFrom"), true);
    partyRelationshipType.set("roleTypeIdValidTo", context.get("roleTypeIdValidTo"), false);
    partyRelationshipType.set("description", context.get("description"), true);
    partyRelationshipType.set("partyRelationshipName", context.get("partyRelationshipName"), true);

    try {
      if (delegator.findOne(
              partyRelationshipType.getEntityName(), partyRelationshipType.getPrimaryKey(), false)
          != null) {
        return ServiceUtil.returnError("Could not create party relationship type: already exists");
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e, module);
      return ServiceUtil.returnError(
          "Could not create party relationship type (read failure): " + e.getMessage());
    }

    try {
      partyRelationshipType.create();
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          "Could not create party relationship type (write failure): " + e.getMessage());
    }

    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
  }
예제 #11
0
 /** Creates records for survey responses on survey items */
 public static int makeListItemSurveyResp(
     Delegator delegator, GenericValue item, List<String> surveyResps)
     throws GenericEntityException {
   if (UtilValidate.isNotEmpty(surveyResps)) {
     int count = 0;
     for (String responseId : surveyResps) {
       GenericValue listResp = delegator.makeValue("ShoppingListItemSurvey");
       listResp.set("shoppingListId", item.getString("shoppingListId"));
       listResp.set("shoppingListItemSeqId", item.getString("shoppingListItemSeqId"));
       listResp.set("surveyResponseId", responseId);
       delegator.create(listResp);
       count++;
     }
     return count;
   }
   return -1;
 }
예제 #12
0
  public static String editRoute(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    List toBeStored = new LinkedList();
    GenericValue route = delegator.makeValue("ShipmentRoute");
    String routeId = request.getParameter("routeId");
    if (UtilValidate.isEmpty(routeId)) {
      try {
        routeId = delegator.getNextSeqId("ShipmentRoute");
      } catch (IllegalArgumentException e) {
        return "Error";
      }
    }
    String routeName = request.getParameter("routeName");
    String origin = request.getParameter("origin");
    String destination = request.getParameter("destination");
    if (UtilValidate.isEmpty(routeName)
        || UtilValidate.isEmpty(origin)
        || UtilValidate.isEmpty(destination)) {
      request.setAttribute("_ERROR_MESSAGE_", " Fill all the require fields for Route ");
      return "error";
    }
    if (UtilValidate.areEqual(origin, destination)) {
      request.setAttribute("_ERROR_MESSAGE_", " Origin and Destination are not same ");
      return "error";
    }
    route.set("routeId", routeId);
    route.set("routeName", routeName);
    route.set("origin", origin);
    route.set("destination", destination);
    toBeStored.add(route);
    try {
      delegator.storeAll(toBeStored);
    } catch (GenericEntityException e) {
      request.setAttribute("_ERROR_MESSAGE_", "Route Id is Required");
      return "error";
    }

    request.setAttribute("routeId", routeId);
    request.setAttribute(
        "_EVENT_MESSAGE_", "Route ID" + " " + routeId + " " + "is Created Successfully");
    return "success";
  }
  public static Map<String, Object> createEPaketConfig(
      DispatchContext dctx, Map<String, ? extends Object> context) throws GenericEntityException {
    Timestamp now = UtilDateTime.nowTimestamp();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Delegator delegator = dctx.getDelegator();
    String epaketConfigId = (String) context.get("epaketConfigId");
    GenericValue gv =
        delegator.makeValue("EPaketConfig", UtilMisc.toMap("epaketConfigId", epaketConfigId));
    gv.set("createdDate", now);
    gv.set("lastModifiedDate", now);
    gv.set("createdByUserLogin", userLogin.getString("userLoginId"));
    gv.set("lastModifiedByUserLogin", userLogin.getString("userLoginId"));

    gv.setNonPKFields(context);
    gv.create();

    createEPaketConfigStatus(delegator, gv, "createEPaketConfig");
    return ServiceUtil.returnSuccess();
  }
예제 #14
0
  public static Map<String, Object> createContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

    if (!security.hasPermission("CRMSFA_CONTACT_CREATE", userLogin)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }

    // the net result of creating an contact is the generation of a Contact partyId
    String contactPartyId = (String) context.get("partyId");
    try {
      // make sure user has the right crmsfa roles defined.  otherwise the contact will be created
      // as deactivated.
      if (UtilValidate.isEmpty(
          PartyHelper.getFirstValidTeamMemberRoleTypeId(
              userLogin.getString("partyId"), delegator))) {
        return UtilMessage.createAndLogServiceError(
            "CrmError_NoRoleForCreateParty",
            UtilMisc.toMap(
                "userPartyName",
                org.ofbiz.party.party.PartyHelper.getPartyName(
                    delegator, userLogin.getString("partyId"), false),
                "requiredRoleTypes",
                PartyHelper.TEAM_MEMBER_ROLES),
            locale,
            MODULE);
      }

      // if we're given the partyId to create, then verify it is free to use
      if (contactPartyId != null) {
        Map<String, Object> findMap = UtilMisc.<String, Object>toMap("partyId", contactPartyId);
        GenericValue party = delegator.findByPrimaryKey("Party", findMap);
        if (party != null) {
          return UtilMessage.createAndLogServiceError(
              "person.create.person_exists", findMap, locale, MODULE);
        }
      }

      // create the Party and Person, which results in a partyId
      Map<String, Object> input =
          UtilMisc.<String, Object>toMap(
              "firstName", context.get("firstName"), "lastName", context.get("lastName"));
      if (contactPartyId != null) {
        input.put("partyId", contactPartyId);
      }
      input.put("firstNameLocal", context.get("firstNameLocal"));
      input.put("lastNameLocal", context.get("lastNameLocal"));
      input.put("personalTitle", context.get("personalTitle"));
      input.put("preferredCurrencyUomId", context.get("preferredCurrencyUomId"));
      input.put("description", context.get("description"));
      input.put("birthDate", context.get("birthDate"));
      Map<String, Object> serviceResults = dispatcher.runSync("createPerson", input);
      if (ServiceUtil.isError(serviceResults)) {
        return UtilMessage.createAndLogServiceError(
            serviceResults, "CrmErrorCreateContactFail", locale, MODULE);
      }
      contactPartyId = (String) serviceResults.get("partyId");

      // create a PartyRole for the resulting Contact partyId with roleTypeId = CONTACT
      serviceResults =
          dispatcher.runSync(
              "createPartyRole",
              UtilMisc.toMap(
                  "partyId", contactPartyId, "roleTypeId", "CONTACT", "userLogin", userLogin));
      if (ServiceUtil.isError(serviceResults)) {
        return UtilMessage.createAndLogServiceError(
            serviceResults, "CrmErrorCreateContactFail", locale, MODULE);
      }

      // create PartySupplementalData
      GenericValue partyData =
          delegator.makeValue("PartySupplementalData", UtilMisc.toMap("partyId", contactPartyId));
      partyData.setNonPKFields(context);
      partyData.create();

      // create a party relationship between the userLogin and the Contact with
      // partyRelationshipTypeId RESPONSIBLE_FOR
      createResponsibleContactRelationshipForParty(
          userLogin.getString("partyId"), contactPartyId, userLogin, delegator, dispatcher);

      // if initial marketing campaign is provided, add it
      String marketingCampaignId = (String) context.get("marketingCampaignId");
      if (marketingCampaignId != null) {
        serviceResults =
            dispatcher.runSync(
                "crmsfa.addContactMarketingCampaign",
                UtilMisc.toMap(
                    "partyId",
                    contactPartyId,
                    "marketingCampaignId",
                    marketingCampaignId,
                    "userLogin",
                    userLogin));
        if (ServiceUtil.isError(serviceResults)) {
          return UtilMessage.createAndLogServiceError(
              serviceResults, "CrmErrorCreateContactFail", locale, MODULE);
        }
      }

      // create basic contact info
      ModelService service = dctx.getModelService("crmsfa.createBasicContactInfoForParty");
      input = service.makeValid(context, "IN");
      input.put("partyId", contactPartyId);
      serviceResults = dispatcher.runSync(service.name, input);
      if (ServiceUtil.isError(serviceResults)) {
        return UtilMessage.createAndLogServiceError(
            serviceResults, "CrmErrorCreateContactFail", locale, MODULE);
      }

      // Sumit:  priority of warehouse for the specified party..
      String priorityOne = (String) context.get("warehousePriorityOne");
      String priorityTwo = (String) context.get("warehousePriorityTwo");
      String priorityThree = (String) context.get("warehousePriorityThree");
      String priorityFour = (String) context.get("warehousePriorityFour");

      if (UtilValidate.isNotEmpty(priorityOne)
          && UtilValidate.isNotEmpty(priorityTwo)
          && UtilValidate.isNotEmpty(priorityThree)
          && UtilValidate.isNotEmpty(priorityFour)) {
        Set<String> priorityList = new LinkedHashSet<String>();
        priorityList.add(priorityOne);
        priorityList.add(priorityTwo);
        priorityList.add(priorityThree);
        priorityList.add(priorityFour);
        List<GenericValue> warehousePriority = new ArrayList<GenericValue>();

        GenericValue facilityPriorityOne = delegator.makeValue("FacilityPartyPriority");
        Long count = 0L;
        for (String priority : priorityList) {
          count++;
          facilityPriorityOne.set("facilityId", priority);
          facilityPriorityOne.set("partyId", contactPartyId);
          facilityPriorityOne.set("priority", count);
          facilityPriorityOne.set("thruDate", UtilDateTime.nowTimestamp());
          warehousePriority.add(facilityPriorityOne);
        }
        delegator.storeAll(warehousePriority);
      }

    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorCreateContactFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorCreateContactFail", locale, MODULE);
    }

    // return the partyId of the newly created Contact
    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("partyId", contactPartyId);
    results.put("contactPartyId", contactPartyId);
    return results;
  }
예제 #15
0
  public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart");
    if (cart == null) {
      Debug.logInfo("No cart to save, doing nothing.", module);
      return;
    }

    String delegatorName = (String) session.getAttribute("delegatorName");
    Delegator delegator = null;
    if (UtilValidate.isNotEmpty(delegatorName)) {
      delegator = DelegatorFactory.getDelegator(delegatorName);
    }
    if (delegator == null) {
      Debug.logError(
          "Could not find delegator with delegatorName in session, not saving abandoned cart info.",
          module);
      return;
    }

    boolean beganTransaction = false;
    try {
      beganTransaction = TransactionUtil.begin();

      GenericValue visit = VisitHandler.getVisit(session);
      if (visit == null) {
        Debug.logError("Could not get the current visit, not saving abandoned cart info.", module);
        return;
      }

      Debug.logInfo("Saving abandoned cart", module);
      Iterator cartItems = cart.iterator();
      int seqId = 1;
      while (cartItems.hasNext()) {
        ShoppingCartItem cartItem = (ShoppingCartItem) cartItems.next();
        GenericValue cartAbandonedLine = delegator.makeValue("CartAbandonedLine");

        cartAbandonedLine.set("visitId", visit.get("visitId"));
        cartAbandonedLine.set("cartAbandonedLineSeqId", (Integer.valueOf(seqId)).toString());
        cartAbandonedLine.set("productId", cartItem.getProductId());
        cartAbandonedLine.set("prodCatalogId", cartItem.getProdCatalogId());
        cartAbandonedLine.set("quantity", cartItem.getQuantity());
        cartAbandonedLine.set("reservStart", cartItem.getReservStart());
        cartAbandonedLine.set("reservLength", cartItem.getReservLength());
        cartAbandonedLine.set("reservPersons", cartItem.getReservPersons());
        cartAbandonedLine.set("unitPrice", cartItem.getBasePrice());
        cartAbandonedLine.set("reserv2ndPPPerc", cartItem.getReserv2ndPPPerc());
        cartAbandonedLine.set("reservNthPPPerc", cartItem.getReservNthPPPerc());
        if (cartItem.getConfigWrapper() != null) {
          cartAbandonedLine.set("configId", cartItem.getConfigWrapper().getConfigId());
        }
        cartAbandonedLine.set("totalWithAdjustments", cartItem.getItemSubTotal());
        // not doing pre-reservations now, so this is always N
        cartAbandonedLine.set("wasReserved", "N");
        cartAbandonedLine.create();

        seqId++;
      }
    } catch (GenericEntityException e) {
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(beganTransaction, "Error saving abandoned cart info", e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      Debug.logError(
          e, "An entity engine error occurred while saving abandoned cart information", module);
    } finally {
      // only commit the transaction if we started one... this will throw an exception if it fails
      try {
        TransactionUtil.commit(beganTransaction);
      } catch (GenericEntityException e) {
        Debug.logError(
            e,
            "Could not commit transaction for entity engine error occurred while saving abandoned cart information",
            module);
      }
    }
  }
예제 #16
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";
    }
  }
예제 #17
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";
  }
  /**
   * Creates and updates a PartyRelationship creating related PartyRoles if needed. A side of the
   * relationship is checked to maintain history
   *
   * @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> createUpdatePartyRelationshipAndRoles(
      DispatchContext ctx, Map<String, ? extends Object> context) {
    Map<String, Object> result = FastMap.newInstance();
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();

    try {
      List<GenericValue> partyRelationShipList =
          PartyRelationshipHelper.getActivePartyRelationships(delegator, context);
      if (UtilValidate.isEmpty(
          partyRelationShipList)) { // If already exists and active nothing to do: keep the current
                                    // one
        String partyId = (String) context.get("partyId");
        String partyIdFrom = (String) context.get("partyIdFrom");
        String partyIdTo = (String) context.get("partyIdTo");
        String roleTypeIdFrom = (String) context.get("roleTypeIdFrom");
        String roleTypeIdTo = (String) context.get("roleTypeIdTo");
        String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId");

        // Before creating the partyRelationShip, create the partyRoles if they don't exist
        GenericValue partyToRole = null;
        partyToRole =
            delegator.findOne(
                "PartyRole",
                UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo),
                false);
        if (partyToRole == null) {
          partyToRole =
              delegator.makeValue(
                  "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo));
          partyToRole.create();
        }

        GenericValue partyFromRole = null;
        partyFromRole =
            delegator.findOne(
                "PartyRole",
                UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom),
                false);
        if (partyFromRole == null) {
          partyFromRole =
              delegator.makeValue(
                  "PartyRole",
                  UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom));
          partyFromRole.create();
        }

        // Check if there is already a partyRelationship of that type with another party from the
        // side indicated
        String sideChecked = partyIdFrom.equals(partyId) ? "partyIdFrom" : "partyIdTo";
        partyRelationShipList =
            delegator.findByAnd(
                "PartyRelationship",
                UtilMisc.toMap(
                    sideChecked,
                    partyId,
                    "roleTypeIdFrom",
                    roleTypeIdFrom,
                    "roleTypeIdTo",
                    roleTypeIdTo,
                    "partyRelationshipTypeId",
                    partyRelationshipTypeId));
        // We consider the last one (in time) as sole active (we try to maintain a unique
        // relationship and keep changes history)
        partyRelationShipList = EntityUtil.filterByDate(partyRelationShipList);
        GenericValue oldPartyRelationShip = EntityUtil.getFirst(partyRelationShipList);
        if (UtilValidate.isNotEmpty(oldPartyRelationShip)) {
          oldPartyRelationShip.setFields(
              UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp())); // Current becomes inactive
          oldPartyRelationShip.store();
        }
        try {
          dispatcher.runSync("createPartyRelationship", context); // Create new one
        } catch (GenericServiceException e) {
          Debug.logWarning(e.getMessage(), module);
          return ServiceUtil.returnError(
              "Could not create party relationship (write failure): " + e.getMessage());
        }
      }
    } catch (GenericEntityException e) {
      Debug.logWarning(e.getMessage(), module);
      return ServiceUtil.returnError(
          "Could not create party relationship (write failure): " + e.getMessage());
    }
    result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    return result;
  }
예제 #19
0
  public static void indexKeywords(GenericValue product, boolean doAll)
      throws GenericEntityException {
    if (product == null) return;
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      delegator.storeAll(toBeStored);
    }
  }
예제 #20
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";
  }
 public Process(EntityPersistentMgr mgr, Delegator delegator) {
   super(mgr, delegator);
   this.newValue = true;
   this.process = delegator.makeValue(org.ofbiz.shark.SharkConstants.WfProcess);
 }
예제 #22
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;
  }
예제 #23
0
  private static List<GenericValue> getTaxAdjustments(
      Delegator delegator,
      GenericValue product,
      GenericValue productStore,
      String payToPartyId,
      String billToPartyId,
      Set<GenericValue> taxAuthoritySet,
      BigDecimal itemPrice,
      BigDecimal itemQuantity,
      BigDecimal itemAmount,
      BigDecimal shippingAmount,
      BigDecimal orderPromotionsAmount) {
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    List<GenericValue> adjustments = FastList.newInstance();

    if (payToPartyId == null) {
      if (productStore != null) {
        payToPartyId = productStore.getString("payToPartyId");
      }
    }

    // store expr
    EntityCondition storeCond = null;
    if (productStore != null) {
      storeCond =
          EntityCondition.makeCondition(
              EntityCondition.makeCondition(
                  "productStoreId", EntityOperator.EQUALS, productStore.get("productStoreId")),
              EntityOperator.OR,
              EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, null));
    } else {
      storeCond = EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, null);
    }

    // build the TaxAuthority expressions (taxAuthGeoId, taxAuthPartyId)
    List<EntityCondition> taxAuthCondOrList = FastList.newInstance();
    // start with the _NA_ TaxAuthority...
    taxAuthCondOrList.add(
        EntityCondition.makeCondition(
            EntityCondition.makeCondition("taxAuthPartyId", EntityOperator.EQUALS, "_NA_"),
            EntityOperator.AND,
            EntityCondition.makeCondition("taxAuthGeoId", EntityOperator.EQUALS, "_NA_")));

    for (GenericValue taxAuthority : taxAuthoritySet) {
      EntityCondition taxAuthCond =
          EntityCondition.makeCondition(
              EntityCondition.makeCondition(
                  "taxAuthPartyId",
                  EntityOperator.EQUALS,
                  taxAuthority.getString("taxAuthPartyId")),
              EntityOperator.AND,
              EntityCondition.makeCondition(
                  "taxAuthGeoId", EntityOperator.EQUALS, taxAuthority.getString("taxAuthGeoId")));
      taxAuthCondOrList.add(taxAuthCond);
    }
    EntityCondition taxAuthoritiesCond =
        EntityCondition.makeCondition(taxAuthCondOrList, EntityOperator.OR);

    try {
      EntityCondition productCategoryCond = null;
      if (product != null) {
        // find the tax categories associated with the product and filter by those, with an IN
        // clause or some such
        // if this product is variant, find the virtual product id and consider also the categories
        // of the virtual
        // question: get all categories, or just a special type? for now let's do all categories...
        String virtualProductId = null;
        if ("Y".equals(product.getString("isVariant"))) {
          virtualProductId = ProductWorker.getVariantVirtualId(product);
        }
        Set<String> productCategoryIdSet = FastSet.newInstance();
        EntityCondition productIdCond = null;
        if (virtualProductId != null) {
          productIdCond =
              EntityCondition.makeCondition(
                  EntityCondition.makeCondition(
                      "productId", EntityOperator.EQUALS, product.getString("productId")),
                  EntityOperator.OR,
                  EntityCondition.makeCondition(
                      "productId", EntityOperator.EQUALS, virtualProductId));

        } else {
          productIdCond =
              EntityCondition.makeCondition(
                  "productId", EntityOperator.EQUALS, product.getString("productId"));
        }
        List<GenericValue> pcmList =
            delegator.findList(
                "ProductCategoryMember",
                productIdCond,
                UtilMisc.toSet("productCategoryId", "fromDate", "thruDate"),
                null,
                null,
                true);
        pcmList = EntityUtil.filterByDate(pcmList, true);
        for (GenericValue pcm : pcmList) {
          productCategoryIdSet.add(pcm.getString("productCategoryId"));
        }

        if (productCategoryIdSet.size() == 0) {
          productCategoryCond =
              EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, null);
        } else {
          productCategoryCond =
              EntityCondition.makeCondition(
                  EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, null),
                  EntityOperator.OR,
                  EntityCondition.makeCondition(
                      "productCategoryId", EntityOperator.IN, productCategoryIdSet));
        }
      } else {
        productCategoryCond =
            EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, null);
      }

      // FIXME handles shipping and promo tax. Simple solution, see
      // https://issues.apache.org/jira/browse/OFBIZ-4160 for a better one
      if (product == null && shippingAmount != null) {
        EntityCondition taxShippingCond =
            EntityCondition.makeCondition(
                EntityCondition.makeCondition("taxShipping", EntityOperator.EQUALS, null),
                EntityOperator.OR,
                EntityCondition.makeCondition("taxShipping", EntityOperator.EQUALS, "Y"));

        if (productCategoryCond != null) {
          productCategoryCond =
              EntityCondition.makeCondition(
                  productCategoryCond, EntityOperator.OR, taxShippingCond);
        }
      }

      if (product == null && orderPromotionsAmount != null) {
        EntityCondition taxOrderPromotionsCond =
            EntityCondition.makeCondition(
                EntityCondition.makeCondition("taxPromotions", EntityOperator.EQUALS, null),
                EntityOperator.OR,
                EntityCondition.makeCondition("taxPromotions", EntityOperator.EQUALS, "Y"));

        if (productCategoryCond != null) {
          productCategoryCond =
              EntityCondition.makeCondition(
                  productCategoryCond, EntityOperator.OR, taxOrderPromotionsCond);
        }
      }

      // build the main condition clause
      List<EntityCondition> mainExprs =
          UtilMisc.toList(storeCond, taxAuthoritiesCond, productCategoryCond);
      mainExprs.add(
          EntityCondition.makeCondition(
              EntityCondition.makeCondition("minItemPrice", EntityOperator.EQUALS, null),
              EntityOperator.OR,
              EntityCondition.makeCondition(
                  "minItemPrice", EntityOperator.LESS_THAN_EQUAL_TO, itemPrice)));
      mainExprs.add(
          EntityCondition.makeCondition(
              EntityCondition.makeCondition("minPurchase", EntityOperator.EQUALS, null),
              EntityOperator.OR,
              EntityCondition.makeCondition(
                  "minPurchase", EntityOperator.LESS_THAN_EQUAL_TO, itemAmount)));
      EntityCondition mainCondition = EntityCondition.makeCondition(mainExprs, EntityOperator.AND);

      // create the orderby clause
      List<String> orderList = UtilMisc.<String>toList("minItemPrice", "minPurchase", "fromDate");

      // finally ready... do the rate query
      List<GenericValue> lookupList =
          delegator.findList(
              "TaxAuthorityRateProduct", mainCondition, null, orderList, null, false);
      List<GenericValue> filteredList = EntityUtil.filterByDate(lookupList, true);

      if (filteredList.size() == 0) {
        Debug.logWarning(
            "In TaxAuthority Product Rate no records were found for condition:"
                + mainCondition.toString(),
            module);
        return adjustments;
      }

      // find the right entry(s) based on purchase amount
      for (GenericValue taxAuthorityRateProduct : filteredList) {
        BigDecimal taxRate =
            taxAuthorityRateProduct.get("taxPercentage") != null
                ? taxAuthorityRateProduct.getBigDecimal("taxPercentage")
                : ZERO_BASE;
        BigDecimal taxable = ZERO_BASE;

        if (product != null
            && (product.get("taxable") == null
                || (product.get("taxable") != null
                    && product.getBoolean("taxable").booleanValue()))) {
          taxable = taxable.add(itemAmount);
        }
        if (shippingAmount != null
            && taxAuthorityRateProduct != null
            && (taxAuthorityRateProduct.get("taxShipping") == null
                || (taxAuthorityRateProduct.get("taxShipping") != null
                    && taxAuthorityRateProduct.getBoolean("taxShipping").booleanValue()))) {
          taxable = taxable.add(shippingAmount);
        }
        if (orderPromotionsAmount != null
            && taxAuthorityRateProduct != null
            && (taxAuthorityRateProduct.get("taxPromotions") == null
                || (taxAuthorityRateProduct.get("taxPromotions") != null
                    && taxAuthorityRateProduct.getBoolean("taxPromotions").booleanValue()))) {
          taxable = taxable.add(orderPromotionsAmount);
        }

        if (taxable.compareTo(BigDecimal.ZERO) == 0) {
          // this should make it less confusing if the taxable flag on the product is not Y/true,
          // and there is no shipping and such
          continue;
        }

        // taxRate is in percentage, so needs to be divided by 100
        BigDecimal taxAmount =
            (taxable.multiply(taxRate))
                .divide(PERCENT_SCALE, salestaxCalcDecimals, salestaxRounding);

        String taxAuthGeoId = taxAuthorityRateProduct.getString("taxAuthGeoId");
        String taxAuthPartyId = taxAuthorityRateProduct.getString("taxAuthPartyId");

        // get glAccountId from TaxAuthorityGlAccount entity using the payToPartyId as the
        // organizationPartyId
        GenericValue taxAuthorityGlAccount =
            delegator.findByPrimaryKey(
                "TaxAuthorityGlAccount",
                UtilMisc.toMap(
                    "taxAuthPartyId",
                    taxAuthPartyId,
                    "taxAuthGeoId",
                    taxAuthGeoId,
                    "organizationPartyId",
                    payToPartyId));
        String taxAuthGlAccountId = null;
        if (taxAuthorityGlAccount != null) {
          taxAuthGlAccountId = taxAuthorityGlAccount.getString("glAccountId");
        } else {
          // TODO: what to do if no TaxAuthorityGlAccount found? Use some default, or is that done
          // elsewhere later on?
        }

        GenericValue productPrice = null;
        if (product != null && taxAuthPartyId != null && taxAuthGeoId != null) {
          // find a ProductPrice for the productId and taxAuth* valxues, and see if it has a
          // priceWithTax value
          Map<String, String> priceFindMap =
              UtilMisc.toMap(
                  "productId",
                  product.getString("productId"),
                  "taxAuthPartyId",
                  taxAuthPartyId,
                  "taxAuthGeoId",
                  taxAuthGeoId,
                  "productPricePurposeId",
                  "PURCHASE");
          List<GenericValue> productPriceList =
              delegator.findByAnd("ProductPrice", priceFindMap, UtilMisc.toList("-fromDate"));
          productPriceList = EntityUtil.filterByDate(productPriceList, true);
          productPrice =
              (productPriceList != null && productPriceList.size() > 0)
                  ? productPriceList.get(0)
                  : null;
          // Debug.logInfo("=================== productId=" + product.getString("productId"),
          // module);
          // Debug.logInfo("=================== productPrice=" + productPrice, module);

        }

        GenericValue taxAdjValue = delegator.makeValue("OrderAdjustment");

        if (productPrice != null && "Y".equals(productPrice.getString("taxInPrice"))) {
          // tax is in the price already, so we want the adjustment to be a VAT_TAX adjustment to be
          // subtracted instead of a SALES_TAX adjustment to be added
          taxAdjValue.set("orderAdjustmentTypeId", "VAT_TAX");

          // the amount will be different because we want to figure out how much of the price was
          // tax, and not how much tax needs to be added
          // the formula is: taxAmount = priceWithTax - (priceWithTax/(1+taxPercentage/100))
          BigDecimal taxAmountIncluded =
              itemAmount.subtract(
                  itemAmount.divide(
                      BigDecimal.ONE.add(
                          taxRate.divide(PERCENT_SCALE, 4, BigDecimal.ROUND_HALF_UP)),
                      3,
                      BigDecimal.ROUND_HALF_UP));
          taxAdjValue.set("amountAlreadyIncluded", taxAmountIncluded);
          taxAdjValue.set("amount", BigDecimal.ZERO);
        } else {
          taxAdjValue.set("orderAdjustmentTypeId", "SALES_TAX");
          taxAdjValue.set("amount", taxAmount);
        }

        taxAdjValue.set("sourcePercentage", taxRate);
        taxAdjValue.set(
            "taxAuthorityRateSeqId", taxAuthorityRateProduct.getString("taxAuthorityRateSeqId"));
        // the primary Geo should be the main jurisdiction that the tax is for, and the secondary
        // would just be to define a parent or wrapping jurisdiction of the primary
        taxAdjValue.set("primaryGeoId", taxAuthGeoId);
        taxAdjValue.set("comments", taxAuthorityRateProduct.getString("description"));
        if (taxAuthPartyId != null) taxAdjValue.set("taxAuthPartyId", taxAuthPartyId);
        if (taxAuthGlAccountId != null) taxAdjValue.set("overrideGlAccountId", taxAuthGlAccountId);
        if (taxAuthGeoId != null) taxAdjValue.set("taxAuthGeoId", taxAuthGeoId);

        // check to see if this party has a tax ID for this, and if the party is tax exempt in the
        // primary (most-local) jurisdiction
        if (UtilValidate.isNotEmpty(billToPartyId) && UtilValidate.isNotEmpty(taxAuthGeoId)) {
          // see if partyId is a member of any groups, if so honor their tax exemptions
          // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is
          // the group member, so the partyIdFrom is the groupPartyId
          Set<String> billToPartyIdSet = FastSet.newInstance();
          billToPartyIdSet.add(billToPartyId);
          List<GenericValue> partyRelationshipList =
              EntityUtil.filterByDate(
                  delegator.findByAndCache(
                      "PartyRelationship",
                      UtilMisc.toMap(
                          "partyIdTo", billToPartyId, "partyRelationshipTypeId", "GROUP_ROLLUP")),
                  true);
          for (GenericValue partyRelationship : partyRelationshipList) {
            billToPartyIdSet.add(partyRelationship.getString("partyIdFrom"));
          }
          handlePartyTaxExempt(
              taxAdjValue,
              billToPartyIdSet,
              taxAuthGeoId,
              taxAuthPartyId,
              taxAmount,
              nowTimestamp,
              delegator);
        } else {
          Debug.logInfo(
              "NOTE: A tax calculation was done without a billToPartyId or taxAuthGeoId, so no tax exemptions or tax IDs considered; billToPartyId=["
                  + billToPartyId
                  + "] taxAuthGeoId=["
                  + taxAuthGeoId
                  + "]",
              module);
        }

        adjustments.add(taxAdjValue);

        if (productPrice != null
            && itemQuantity != null
            && productPrice.getBigDecimal("priceWithTax") != null
            && !"Y".equals(productPrice.getString("taxInPrice"))) {
          BigDecimal priceWithTax = productPrice.getBigDecimal("priceWithTax");
          BigDecimal price = productPrice.getBigDecimal("price");
          BigDecimal baseSubtotal = price.multiply(itemQuantity);
          BigDecimal baseTaxAmount =
              (baseSubtotal.multiply(taxRate))
                  .divide(PERCENT_SCALE, salestaxCalcDecimals, salestaxRounding);
          // Debug.logInfo("=================== priceWithTax=" + priceWithTax, module);
          // Debug.logInfo("=================== enteredTotalPriceWithTax=" +
          // enteredTotalPriceWithTax, module);
          // Debug.logInfo("=================== calcedTotalPriceWithTax=" + calcedTotalPriceWithTax,
          // module);

          // tax is not already in price so we want to add it in, but this is a VAT situation so
          // adjust to make it as accurate as possible

          // for VAT taxes if the calculated total item price plus calculated taxes is different
          // from what would be
          // expected based on the original entered price with taxes (if the price was entered this
          // way), then create
          // an adjustment that corrects for the difference, and this correction will be effectively
          // subtracted from the
          // price and not from the tax (the tax is meant to be calculated based on Tax Authority
          // rules and so should
          // not be shorted)

          // TODO (don't think this is needed, but just to keep it in mind): get this to work with
          // multiple VAT tax authorities instead of just one (right now will get incorrect totals
          // if there are multiple taxes included in the price)
          // TODO add constraint to ProductPrice lookup by any productStoreGroupId associated with
          // the current productStore

          BigDecimal enteredTotalPriceWithTax = priceWithTax.multiply(itemQuantity);
          BigDecimal calcedTotalPriceWithTax = (baseSubtotal).add(baseTaxAmount);
          if (!enteredTotalPriceWithTax.equals(calcedTotalPriceWithTax)) {
            // if the calced amount is higher than the entered amount we want the value to be
            // negative
            //     to get it down to match the entered amount
            // so, subtract the calced amount from the entered amount (ie: correction = entered -
            // calced)
            BigDecimal correctionAmount =
                enteredTotalPriceWithTax.subtract(calcedTotalPriceWithTax);
            // Debug.logInfo("=================== correctionAmount=" + correctionAmount, module);

            GenericValue correctionAdjValue = delegator.makeValue("OrderAdjustment");
            correctionAdjValue.set(
                "taxAuthorityRateSeqId",
                taxAuthorityRateProduct.getString("taxAuthorityRateSeqId"));
            correctionAdjValue.set("amount", correctionAmount);
            // don't set this, causes a doubling of the tax rate because calling code adds up all
            // tax rates: correctionAdjValue.set("sourcePercentage", taxRate);
            correctionAdjValue.set("orderAdjustmentTypeId", "VAT_PRICE_CORRECT");
            // the primary Geo should be the main jurisdiction that the tax is for, and the
            // secondary would just be to define a parent or wrapping jurisdiction of the primary
            correctionAdjValue.set("primaryGeoId", taxAuthGeoId);
            correctionAdjValue.set("comments", taxAuthorityRateProduct.getString("description"));
            if (taxAuthPartyId != null) correctionAdjValue.set("taxAuthPartyId", taxAuthPartyId);
            if (taxAuthGlAccountId != null)
              correctionAdjValue.set("overrideGlAccountId", taxAuthGlAccountId);
            if (taxAuthGeoId != null) correctionAdjValue.set("taxAuthGeoId", taxAuthGeoId);
            adjustments.add(correctionAdjValue);
          }
        }
      }
    } catch (GenericEntityException e) {
      Debug.logError(e, "Problems looking up tax rates", module);
      return FastList.newInstance();
    }

    return adjustments;
  }